Elffuss BraidHub

kikocis/utopia public

A half-mounted source should say so, not report failure (#144)

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Changesetb7cca7fa81d94b68b8571d1e656adb2c4a090d6edfacacb3460df8daea3ad8a2
AuthorWaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-08-31 19:05 +08:00
CommitterGitHub <noreply@github.com> · 2026-08-31 19:05 +08:00
Parents18eb6b0051a2

Browse the files at this changeset

7 files changed

modified crates/utopia-server/src/alerting.rs +41 −0
@@ -71,3 +71,44 @@
7171 }
7272 });
7373 }
74+
75+/// 数据源挂上了,库表结构却没摄进来。
76+///
77+/// **报的不是那次失败,是它留下的状态。** 挂载分两步:写 `kb_data_sources`,
78+/// 再把 schema 生成文档摄进库。第一步成了、第二步没成的时候,源是真挂着的——
79+/// `query_data` 会入列,而模型检索不到任何表结构,只能瞎猜列名。
80+///
81+/// 挂载那一刻的报错只有点按钮的人看得见。此后这个库就一直静默地缺着,
82+/// 而这正是 0009 说的那件事:真正伤人的不是失败,是失败无声。
83+pub async fn observe_schema_sync_failure(
84+ state: &AppState,
85+ kb_id: uuid::Uuid,
86+ source_id: uuid::Uuid,
87+ source_name: &str,
88+ err: &anyhow::Error,
89+) {
90+ if let Err(e) = alerts::raise(
91+ &state.pool,
92+ alerts::NewAlert {
93+ kb_id: Some(kb_id),
94+ severity: "warning",
95+ kind: alerts::kind::SCHEMA_SYNC_FAILED,
96+ // 配置类:要修的是连接串或网络,不是内容。找 admin
97+ min_role: Role::Admin,
98+ subject_type: Some("data_source"),
99+ subject_id: Some(source_id),
100+ // 名字在这里存一份——源被删掉之后 subject_id 解析不出名字,
101+ // 而告警该留得住
102+ detail: serde_json::json!({
103+ "source": source_name,
104+ "error": err.to_string(),
105+ }),
106+ },
107+ )
108+ .await
109+ {
110+ tracing::warn!(error = %e, "上报 data_source.schema_sync_failed 失败");
111+ return;
112+ }
113+ state.emit_alert();
114+}
modified crates/utopia-server/src/api/datasource_routes.rs +39 −7
@@ -135,10 +135,33 @@
135135 }
136136 utopia_store::datasources::mount(&state.pool, kb_id, ds_id).await?;
137137 // 挂载即摄取 schema:Chat 写 SQL 前能检索到表结构
138- let synced = sync_schema_doc(&state, kb_id, ds_id)
138+ //
139+ // **这一步失败不能回报成挂载失败。** 上面那行已经写进 kb_data_sources 了,
140+ // 源是真挂着的;从前这里 `?` 出去回 500,人以为没挂上,实际挂上了——
141+ // 而问数看不见它有哪些表。改成:照实说挂载成了,schema 没成,并且
142+ // 报进告警中心,因为那之后就是一个静默的缺失状态(0009)
143+ match sync_schema_doc(&state, kb_id, ds_id).await {
144+ Ok(synced) => Ok(Json(json!({ "ok": true, "schema_tables": synced }))),
145+ Err(e) => {
146+ let name = source_name(&state, ds_id).await;
147+ crate::alerting::observe_schema_sync_failure(&state, kb_id, ds_id, &name, &e).await;
148+ Ok(Json(json!({
149+ "ok": true,
150+ "schema_tables": 0,
151+ "schema_error": e.to_string(),
152+ })))
153+ }
154+ }
155+}
156+
157+/// 告警要留住名字:源被删之后 `subject_id` 就解析不出名字了。查不到时给占位符
158+/// 而不是让告警本身失败——**报警路径上的失败不该淹掉它要报的那件事**。
159+async fn source_name(state: &AppState, ds_id: Uuid) -> String {
160+ utopia_store::datasources::list(&state.pool)
139161 .await
140- .map_err(AppError::Other)?;
141- Ok(Json(json!({ "ok": true, "schema_tables": synced })))
162+ .ok()
163+ .and_then(|all| all.into_iter().find(|d| d.id == ds_id).map(|d| d.name))
164+ .unwrap_or_else(|| ds_id.to_string())
142165 }
143166
144167 pub async fn unmount(
@@ -151,16 +174,25 @@
151174 Ok(Json(json!({ "ok": true })))
152175 }
153176
177+/// 手动刷新结构。
178+///
179+/// **这里照旧把错误回给调用方**——点按钮的人正看着,而且什么都没半途发生。
180+/// 但同样报一条告警:留下的后果与挂载失败时一模一样(源挂着、表结构是旧的
181+/// 或空的),而点按钮的人未必是需要知道这件事的人。
154182 pub async fn sync_schema(
155183 State(state): State<AppState>,
156184 AuthUser(user): AuthUser,
157185 Path((kb_id, ds_id)): Path<(Uuid, Uuid)>,
158186 ) -> ApiResult<Json<serde_json::Value>> {
159187 require_kb(&state, &user, kb_id, Role::Admin).await?;
160- let synced = sync_schema_doc(&state, kb_id, ds_id)
161- .await
162- .map_err(AppError::Other)?;
163- Ok(Json(json!({ "ok": true, "schema_tables": synced })))
188+ match sync_schema_doc(&state, kb_id, ds_id).await {
189+ Ok(synced) => Ok(Json(json!({ "ok": true, "schema_tables": synced }))),
190+ Err(e) => {
191+ let name = source_name(&state, ds_id).await;
192+ crate::alerting::observe_schema_sync_failure(&state, kb_id, ds_id, &name, &e).await;
193+ Err(AppError::Other(e).into())
194+ }
195+ }
164196 }
165197
166198 /// Agentic 探索:后台任务读挂载源 schema,提议 指标/维度→字段 映射(低置信入 Review)。
modified crates/utopia-store/src/alerts.rs +6 −0
@@ -27,6 +27,12 @@
2727 /// 系统级:模型端点没给出可用的回答——连不上,或者连上了但回来的不是这个 API。
2828 /// 端点干净地回 4xx 不算:那说明它就是模型 API,只是密钥或配额不对
2929 pub const LLM_UNREACHABLE: &str = "llm.unreachable";
30+ /// 库级:数据源挂上了,它的库表结构却没摄进来。`min_role = admin`
31+ ///
32+ /// **这一条描述的不是那次失败,是它留下的状态**:源挂着,而问数看不见它有
33+ /// 哪些表——`query_data` 照样入列,模型却只能瞎猜列名。挂载那一刻的报错
34+ /// 只有点按钮的人看得见,此后这个库就一直这样静默地缺着。
35+ pub const SCHEMA_SYNC_FAILED: &str = "data_source.schema_sync_failed";
3036 }
3137
3238 /// 一次故障。打包成结构体不只是为了参数个数——调用点写 `severity: "error"`
modified web/src/api.ts +9 −6
@@ -1085,13 +1085,16 @@
10851085 request<{ data_sources: DataSourceView[] }>(
10861086 `/api/v1/kbs/${kbId}/data-sources/available`,
10871087 ),
1088+ /** 挂载。**`schema_error` 非空时挂载仍然成了**——源是真挂上的,只是它的
1089+ * 库表结构没摄进来,问数看不见有哪些表。同一件事会进告警中心 */
10881090 mountDataSource: (kbId: string, dsId: string) =>
1089- request<{ ok: boolean; schema_tables: number }>(
1090- `/api/v1/kbs/${kbId}/data-sources/${dsId}`,
1091- {
1092- method: "PUT",
1093- },
1094- ),
1091+ request<{
1092+ ok: boolean;
1093+ schema_tables: number;
1094+ schema_error?: string | null;
1095+ }>(`/api/v1/kbs/${kbId}/data-sources/${dsId}`, {
1096+ method: "PUT",
1097+ }),
10951098 unmountDataSource: (kbId: string, dsId: string) =>
10961099 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/data-sources/${dsId}`, {
10971100 method: "DELETE",
modified web/src/i18n/en.ts +8 −0
@@ -150,6 +150,10 @@
150150 title: "A source failed to sync",
151151 hint: "Nothing new came in from it. Check the source's settings.",
152152 },
153+ "data_source.schema_sync_failed": {
154+ title: "A data source is mounted, but its schema is not",
155+ hint: "Ask cannot see which tables exist, so it will guess column names. Check the connection, then use Refresh schema.",
156+ },
153157 "llm.unreachable": {
154158 title: "The model endpoint gave no usable answer",
155159 hint: "Extraction and embedding are stopped. Check the endpoint URL in system settings.",
@@ -1059,6 +1063,10 @@
10591063 unmount: "Unmount",
10601064 syncSchema: "Refresh schema",
10611065 schemaSynced: (n: number) => `Schema ingested (${n} tables)`,
1066+ // Mounted, schema did not. **Do not call this a failed mount** — the source is mounted
1067+ schemaFailed:
1068+ "The data source is mounted, but its schema could not be ingested — Ask cannot see which tables exist. " +
1069+ "This is in the alert centre; check the connection, then use Refresh schema.",
10621070 explore: "Explore mappings",
10631071 exploreHint:
10641072 "An agent reads these schemas and proposes metric and dimension definitions. Proposals land in Pending; Ask uses them only once confirmed.",
modified web/src/i18n/zh.ts +8 −0
@@ -132,6 +132,10 @@
132132 title: "来源同步失败",
133133 hint: "它没有带进新内容。去来源设置里看一下。",
134134 },
135+ "data_source.schema_sync_failed": {
136+ title: "数据源挂上了,库表结构没进来",
137+ hint: "问数看不见有哪些表,只能猜列名。检查连接串,然后点「刷新结构」。",
138+ },
135139 "llm.unreachable": {
136140 title: "模型端点没有给出可用的回答",
137141 hint: "抽取与向量化已停摆。去系统设置里检查端点地址。",
@@ -952,6 +956,10 @@
952956 unmount: "卸载",
953957 syncSchema: "刷新结构",
954958 schemaSynced: (n: number) => `结构已摄入(${n} 张表)`,
959+ // 挂载成了、结构没成。**别说成失败**——源是真挂上的
960+ schemaFailed:
961+ "数据源已挂载,但库表结构没能摄入——问数看不见有哪些表。已报进告警中心;" +
962+ "检查连接串后点「刷新结构」重试。",
955963 explore: "探查映射",
956964 exploreHint:
957965 "一个智能体读这些库表结构,提出指标/维度的口径。提出来的落在「待审批」,确认之后问数才会用。",
modified web/src/pages/Mappings.tsx +11 −1
@@ -450,14 +450,21 @@
450450 });
451451 const [picked, setPicked] = useState("");
452452 const [notice, setNotice] = useState<string | null>(null);
453+ // 与 notice 分开:一个是「成了」,一个是「成了一半」,配色也不同
454+ const [warning, setWarning] = useState<string | null>(null);
453455 const invalidate = () =>
454456 queryClient.invalidateQueries({ queryKey: ["kbDataSources", kbId] });
455457
456458 const mount = useMutation({
457459 mutationFn: (dsId: string) => api.mountDataSource(kbId, dsId),
460+ // **挂载成了、schema 没成,是两件事。** 服务端此时回的是 ok(源确实挂上了),
461+ // 所以不能照着 `schema_tables: 0` 说「已摄入 0 张表」——那等于说成功了。
462+ // 说清楚半成的是哪一半,同一件事也进了告警中心
458463 onSuccess: (r) => {
459464 setPicked("");
460- setNotice(S.mapping.schemaSynced(r.schema_tables));
465+ setNotice(null);
466+ setWarning(r.schema_error ? S.mapping.schemaFailed : null);
467+ if (!r.schema_error) setNotice(S.mapping.schemaSynced(r.schema_tables));
461468 invalidate();
462469 },
463470 onError: (e: unknown) => toast.error((e as Error).message),
@@ -582,6 +589,9 @@
582589 </div>
583590 )}
584591 {notice && <p className="text-xs text-[var(--u-ok)]">{notice}</p>}
592+ {warning && (
593+ <p className="text-xs text-[var(--u-warn)]">{warning}</p>
594+ )}
585595 </div>
586596 );
587597 }