From 43a73d398d480a78d1e563ec9eac9e65b75aa467 Mon Sep 17 00:00:00 2001 From: Nash Aschenbath Date: Sat, 10 Oct 2026 13:24:27 +0800 Subject: [PATCH] Keep table alignment proposals atomic until a person adopts them Signed-off-by: Nash Aschenbath --- crates/utopia-cli/src/main.rs | 2 +- crates/utopia-server/src/api/mod.rs | 11 +- .../utopia-server/src/api/ontology_routes.rs | 9 + .../src/api/rule_expression_input.rs | 2 +- .../src/api/table_alignment_routes.rs | 55 ++ crates/utopia-server/src/main.rs | 1 + crates/utopia-server/src/mappings.rs | 212 ++---- crates/utopia-server/src/table_exploration.rs | 175 +++++ .../src/table_exploration_tests.rs | 430 +++++++++++++ crates/utopia-store/src/graph.rs | 5 +- crates/utopia-store/src/lib.rs | 1 + crates/utopia-store/src/ontology.rs | 53 +- crates/utopia-store/src/table_alignments.rs | 603 ++++++++++++++++++ ...oration-aligns-a-schema-to-the-ontology.md | 52 +- ..._a_table_alignment_is_adopted_together.sql | 33 + scripts/bench/README.md | 9 + scripts/bench/alignment-score.mjs | 24 + scripts/bench/alignment-score.test.mjs | 24 + scripts/bench/mappings.mjs | 12 +- scripts/bench/truth/wide.mappings.json | 146 +++++ web/src/api.ts | 51 ++ web/src/i18n/en.ts | 18 +- web/src/i18n/zh.ts | 18 +- web/src/pages/Mappings.tsx | 13 +- web/src/pages/TableAlignments.tsx | 88 +++ web/src/queryDefaults.ts | 1 + web/src/useKbEvents.ts | 2 +- 27 files changed, 1845 insertions(+), 205 deletions(-) create mode 100644 crates/utopia-server/src/api/table_alignment_routes.rs create mode 100644 crates/utopia-server/src/table_exploration.rs create mode 100644 crates/utopia-server/src/table_exploration_tests.rs create mode 100644 crates/utopia-store/src/table_alignments.rs create mode 100644 migrations/0108_a_table_alignment_is_adopted_together.sql create mode 100644 scripts/bench/alignment-score.mjs create mode 100644 scripts/bench/alignment-score.test.mjs create mode 100644 web/src/pages/TableAlignments.tsx diff --git a/crates/utopia-cli/src/main.rs b/crates/utopia-cli/src/main.rs index 2ec617196..1ae492e61 100644 --- a/crates/utopia-cli/src/main.rs +++ b/crates/utopia-cli/src/main.rs @@ -82,7 +82,7 @@ struct ManifestDataDir { /// not a side effect of a code change. // 是迁移文件的**个数**,不是最大的编号(守卫 `schema_version_policy_compares_against_current` // 按个数比):编号有空缺时两者不同——0071 由一个开放 PR 占着,0072 先落,个数是 71 -const CURRENT_SCHEMA_VERSION: u32 = 97; +const CURRENT_SCHEMA_VERSION: u32 = 98; fn main() -> anyhow::Result<()> { dotenvy::dotenv().ok(); diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs index ba7cd2d2a..8808a1e69 100644 --- a/crates/utopia-server/src/api/mod.rs +++ b/crates/utopia-server/src/api/mod.rs @@ -19,13 +19,14 @@ pub(crate) mod ontology_routes; mod question_routes; mod review_routes; mod rig_model; -mod rule_expression_input; +pub(crate) mod rule_expression_input; pub(crate) mod rule_routes; mod search_routes; mod settings_routes; mod sources_routes; #[cfg(test)] mod static_files_tests; +mod table_alignment_routes; mod token_routes; mod tools; mod tools_graph; @@ -243,6 +244,14 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router { ) // 静态段排在 `{mapping_id}` 前面:先跑一遍看数,不落库 .route("/kbs/{id}/mappings/preview", post(mapping_routes::preview)) + .route( + "/kbs/{id}/table-alignments", + get(table_alignment_routes::list), + ) + .route( + "/kbs/{id}/table-alignments/decision", + post(table_alignment_routes::decide), + ) // 跟一个问题有关的口径(问数用的同一条检索) .route("/kbs/{id}/mappings/relevant", get(mapping_routes::relevant)) .route( diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rs index a075ce681..088ae792d 100644 --- a/crates/utopia-server/src/api/ontology_routes.rs +++ b/crates/utopia-server/src/api/ontology_routes.rs @@ -560,6 +560,15 @@ pub async fn decide_proposal( if !matches!(req.status.as_str(), "adopted" | "rejected") { return Err(AppError::invalid("bad_status", "status 只能是 adopted 或 rejected").into()); } + // A table cannot use the legacy status-only path: its declarations and + // bindings must commit together even when a client calls this endpoint. + if req.section == utopia_store::table_alignments::SECTION { + return Err(AppError::invalid( + "bad_table_alignment", + "Review the whole table through the table alignment endpoint, including its version", + ) + .into()); + } let reason = req .reason .as_deref() diff --git a/crates/utopia-server/src/api/rule_expression_input.rs b/crates/utopia-server/src/api/rule_expression_input.rs index 4c5dafe04..3f4d9c05f 100644 --- a/crates/utopia-server/src/api/rule_expression_input.rs +++ b/crates/utopia-server/src/api/rule_expression_input.rs @@ -65,7 +65,7 @@ fn unsupported() -> AppError { invalid("Use attributes, literals, arithmetic, CAST AS DOUBLE PRECISION, a simple literal CASE, or date_trunc with year, month or day.") } -fn compile(text: &str, names: &HashMap) -> AppResult { +pub(crate) fn compile(text: &str, names: &HashMap) -> AppResult { if text.trim().is_empty() || text.len() > MAX_INPUT_BYTES { return Err(invalid( "An expression must contain between one and 8192 bytes.", diff --git a/crates/utopia-server/src/api/table_alignment_routes.rs b/crates/utopia-server/src/api/table_alignment_routes.rs new file mode 100644 index 000000000..b146fc4f0 --- /dev/null +++ b/crates/utopia-server/src/api/table_alignment_routes.rs @@ -0,0 +1,55 @@ +use super::graph_routes::require_kb; +use crate::auth::AuthUser; +use crate::error::ApiResult; +use crate::state::AppState; +use axum::{ + extract::{Path, State}, + Json, +}; +use serde::Deserialize; +use serde_json::{json, Value}; +use utopia_core::{models::Role, AppError}; +use uuid::Uuid; + +pub async fn list( + State(state): State, + AuthUser(user): AuthUser, + Path(kb_id): Path, +) -> ApiResult> { + require_kb(&state, &user, kb_id, Role::Viewer).await?; + let proposals = utopia_store::table_alignments::list(&state.pool, kb_id).await?; + let last_run = utopia_store::exploration_runs::recent(&state.pool, kb_id, 1) + .await? + .into_iter() + .next(); + Ok(Json(json!({"items":proposals,"last_run":last_run}))) +} + +#[derive(Deserialize)] +pub struct Decision { + pub key: String, + pub version: Uuid, + pub status: String, +} + +pub async fn decide( + State(state): State, + AuthUser(user): AuthUser, + Path(kb_id): Path, + Json(req): Json, +) -> ApiResult> { + require_kb(&state, &user, kb_id, Role::Editor).await?; + if !matches!(req.status.as_str(), "adopted" | "rejected") { + return Err(AppError::invalid("bad_status", "status must be adopted or rejected").into()); + } + crate::table_exploration::decide( + &state, + kb_id, + &req.key, + req.version, + req.status == "adopted", + user.id, + ) + .await?; + Ok(Json(json!({"ok":true}))) +} diff --git a/crates/utopia-server/src/main.rs b/crates/utopia-server/src/main.rs index 6b1ede67d..057eeb823 100644 --- a/crates/utopia-server/src/main.rs +++ b/crates/utopia-server/src/main.rs @@ -34,6 +34,7 @@ mod readers; mod retrieval; mod rss_full_content; mod state; +mod table_exploration; mod time_resolution; mod time_text; mod type_alignment; diff --git a/crates/utopia-server/src/mappings.rs b/crates/utopia-server/src/mappings.rs index c10c5814e..24a43e14d 100644 --- a/crates/utopia-server/src/mappings.rs +++ b/crates/utopia-server/src/mappings.rs @@ -1,13 +1,5 @@ -//! 问数语义映射的 Agentic 探索:读挂载源的 schema + KB 既有概念,让 LLM 提议 -//! "业务概念(Metric/Dimension 实体)→ 数据资产定义" 的映射。 -//! -//! 提议写进 `concept_mappings`(status = proposed)→ Review 页自成一档, -//! Confirm / Reject 之后 status 变 confirmed,问数只读确认过的那些。 -//! -//! **从前它是一条 0.6 置信的 `mapped_to` 事实**,借「低置信事实」那一档露面。 -//! 搬出来的理由见 0011:它不是关于世界的断言,是配置——而「确认」这个动作 -//! 当时是 `UPDATE facts SET confidence = 1.0`,原地改一张不许原地改的表。 -//! agent 只提议,口径生效权在人——与消解"宁分勿合"同一哲学。 +//! Schema exploration records one table alignment for human adoption (0036). +//! Manual SQL definitions still use concept_mappings until #556 renders them. use crate::llm_util; use crate::state::AppState; @@ -52,19 +44,9 @@ fn column_line(c: &crate::query_engine::SchemaColumn) -> String { ) } -/// 一轮允许提几条口径。 -/// -/// **上限跟着 schema 的大小走。** 写死的 12 对一个三张表的小库绰绰有余, -/// 对一张八十列的宽表就是覆盖率的天花板:实测 TPC-H 八张表、二十四条口径, -/// 十二条上限之下覆盖率 25%,漏掉的包括那条出现在七条基准查询里的核心收入 -/// 口径(#501)。 -/// -/// 每张表三条是个估计而不是定律——一张事实表值得的口径远多于三条,一张 -/// 码表一条都不值。它只需要比常数强:**规模大的时候不至于一开始就封顶**。 -/// 下限仍是 12,小 schema 不该因此缩水;上限 60 挡住提示词与一轮人工审阅 -/// 的规模。 +/// At most one proposal per table; the schema budget bounds what is visible. fn proposal_cap(tables: i32) -> i32 { - (tables * 3).clamp(12, 60) + tables.clamp(1, 60) } /// 模型回的 JSON 常裹着代码栅栏;剥掉它。 @@ -220,7 +202,6 @@ async fn explore(state: &AppState, kb_id: Uuid, run: Uuid) -> anyhow::Result<()> if sources.is_empty() { anyhow::bail!("No data sources mounted"); } - ensure_concept_types(&state.pool, kb_id).await?; // 各源 schema(引擎直读,保证新鲜;限量防 prompt 爆炸) // @@ -231,6 +212,7 @@ async fn explore(state: &AppState, kb_id: Uuid, run: Uuid) -> anyhow::Result<()> let mut tables_scanned = 0i32; let mut columns_scanned = 0i32; let mut truncated = false; + let mut schemas = std::collections::HashMap::new(); for ds in &sources { if truncated { break; @@ -241,7 +223,7 @@ async fn explore(state: &AppState, kb_id: Uuid, run: Uuid) -> anyhow::Result<()> .await?; schema_txt.push_str(&format!("\n=== source: {} ===\n", ds.name)); let mut current = String::new(); - for c in cols { + for c in &cols { let key = format!("{}.{}", c.schema, c.table); if key != current { current = key.clone(); @@ -249,13 +231,14 @@ async fn explore(state: &AppState, kb_id: Uuid, run: Uuid) -> anyhow::Result<()> schema_txt.push_str(&format!("table {key}:\n")); } columns_scanned += 1; - schema_txt.push_str(&column_line(&c)); + schema_txt.push_str(&column_line(c)); if schema_txt.len() > MAX_SCHEMA_CHARS { schema_txt.push_str("(truncated)\n"); truncated = true; break; } } + schemas.insert(ds.id, cols); } let cap = proposal_cap(tables_scanned); @@ -278,49 +261,8 @@ async fn explore(state: &AppState, kb_id: Uuid, run: Uuid) -> anyhow::Result<()> tracing::warn!(%kb_id, error = %e, "数据描述没写成,提议照常"); } - // 既有概念(供归并复用,避免重复起名) - let existing: Vec<(String,)> = sqlx::query_as( - "SELECT e.canonical_name FROM entities e - JOIN entity_types t ON t.id = e.type_id - WHERE e.kb_id = $1 AND e.merged_into IS NULL AND t.key IN ('metric','dimension') - ORDER BY e.canonical_name LIMIT 100", - ) - .bind(kb_id) - .fetch_all(&state.pool) - .await?; - let existing_names: Vec = existing.into_iter().map(|(n,)| n).collect(); - - // 人写的约定进提议的提示词。schema 里没有「测试单不算数」这句话,探索在宽表上 - // 0/18 正是因为它;有了这句,一条提议才可能长出 FILTER (WHERE is_test = 0)(#570) - let conventions = kb - .data_conventions - .as_deref() - .map(str::trim) - .filter(|s| !s.is_empty()) - .unwrap_or("(none stated)"); - let prompt = format!( - "You are building the semantic layer of a BI system. Given database schemas, propose \ - business concepts a user would ask about, each mapped to a concrete definition.\n\ - Existing concepts (reuse these names when the meaning matches): {}\n\ - Conventions stated by the owner of this base — apply them in every definition, as \ - filters, unit conversions, or the choice of column: {conventions}\n\ - Schemas:\n{}\n\ - Reply with ONLY a JSON array, each item:\n\ - {{\"name\": \"business concept name\", \"kind\": \"metric\"|\"dimension\", \ - \"source\": \"data source name\", \ - \"definition\": {{\"table\": \"schema.table\", \"expr\": \"SQL expression\", \ - \"sql\": \"full SELECT if joins are needed (optional)\", \"unit\": \"optional\"}}, \ - \"summary\": \"one line: source + expression, shown to reviewers\", \ - \"rationale\": \"why this mapping, citing column comments\"}}\n\ - Metrics are aggregatable quantities (use sum/count/avg in expr); dimensions are \ - group-by columns. Propose at most {cap}, only well-grounded ones.", - if existing_names.is_empty() { - "(none)".into() - } else { - existing_names.join(", ") - }, - schema_txt - ); + let ontology = crate::table_exploration::ontology_context(&state.pool, kb_id).await?; + let prompt = crate::table_exploration::prompt(&schema_txt, &ontology, cap, &kb.ontology_lang); let _permit = llm_util::acquire_chat(state, &settings).await; let reply = client @@ -348,111 +290,59 @@ async fn explore(state: &AppState, kb_id: Uuid, run: Uuid) -> anyhow::Result<()> e.0 += 1; }; let mut covered: std::collections::BTreeSet = Default::default(); + let mut seen = std::collections::HashSet::new(); for p in proposals.iter().take(cap as usize) { - let name = p["name"].as_str().map(str::trim).unwrap_or(""); - let kind = p["kind"].as_str().unwrap_or(""); let said = p["source"].as_str().map(str::trim).unwrap_or(""); - if name.is_empty() || !matches!(kind, "metric" | "dimension") { - note(drop_reason::KIND, format!("name={name:?} kind={kind:?}")); - continue; - } - // **只挂了一个源时,模型说什么都算它。** 没有歧义可言,而对不上的代价是 - // 整条提议消失:实测源叫 `tpch-2026-09-08-12-30`,模型照着 schema 回 - // `tpch`,十二条一条不剩地被吞掉,任务照样 done(#501 跑第一轮时踩的) let source = if sources.len() == 1 { - source_names[0] + &sources[0] + } else if let Some(source) = sources.iter().find(|s| s.name.eq_ignore_ascii_case(said)) { + source } else { - match source_names - .iter() - .find(|s| s.eq_ignore_ascii_case(said)) - .copied() - { - Some(s) => s, - None => { - note( - drop_reason::SOURCE, - format!("model said {said:?}, mounted: {}", source_names.join(", ")), - ); - continue; - } - } + note( + drop_reason::SOURCE, + format!("Unknown mounted source {said:?}"), + ); + continue; }; - let type_id: Option<(Uuid,)> = - sqlx::query_as("SELECT id FROM entity_types WHERE kb_id = $1 AND key = $2") - .bind(kb_id) - .bind(kind) - .fetch_optional(&state.pool) - .await?; - let Some((type_id,)) = type_id else { + let Some(columns) = schemas.get(&source.id) else { note( - drop_reason::TYPE, - format!("no entity type {kind:?} in this base"), + drop_reason::SOURCE, + format!("Source {} was outside the schema budget", source.name), ); continue; }; - - // 概念实体:走消解(同名归并;无向量上下文按 v1 兼容归并)。 - // 没有块原文可给——这些名字来自数据源的 schema 探索,不是从文档句子里抽的 - let resolved = utopia_store::resolution::resolve_mention( + let proposed = match crate::table_exploration::prepare( &state.pool, kb_id, - Some(type_id), - name, - None, - None, - None, - &[], + source.id, + &source.name, + p.clone(), + columns, ) - .await?; - - // 定义拆成列写进 concept_mappings(0011)。从前它是一份塞进 - // `object_value` 的 JSON,宾语挂在一条叫 mapped_to 的关系上—— - // 而那条关系是本体里的一行,跟 works_at 并列。**它不是关于世界的 - // 断言,是配置**,所以搬去自己的表 - let def = &p["definition"]; - if !def.is_object() { + .await + { + Ok(proposed) => proposed, + Err(utopia_core::AppError::Invalid { message, .. }) => { + note(drop_reason::DEFINITION, message); + continue; + } + Err(e) => return Err(e.into()), + }; + let key = utopia_store::table_alignments::key(source.id, &proposed.draft.table); + if !seen.insert(key) { note( drop_reason::DEFINITION, - format!("{name:?} has no definition object"), + format!("Table {} was proposed twice", proposed.draft.table), ); continue; } - let s = |k: &str| { - def[k] - .as_str() - .filter(|x| !x.is_empty()) - .map(str::to_string) - }; - // 覆盖率的分子。分母是这一轮扫见的表数——**十一条提议对着八十列的宽表, - // 与十一条刚好覆盖完一个小库,从 `concept_mappings` 里看长得一模一样** - if let Some(t) = s("table") { - covered.insert(t); - } - let (_, written) = utopia_store::mappings::propose( - &state.pool, - kb_id, - resolved.entity_id, - source, - s("table").as_deref(), - s("expr").as_deref(), - s("sql").as_deref(), - s("unit").as_deref(), - // summary 是给人看的那句:Review 列表与问数 prompt 都靠它 - p["summary"].as_str().or(def["summary"].as_str()), - def["derived"].as_bool().unwrap_or(false), - ) - .await?; - if written { + if utopia_store::table_alignments::save(&state.pool, kb_id, &proposed).await? { accepted += 1; + covered.insert(format!("{}:{}", source.name, proposed.draft.table)); } else { - note( - drop_reason::DECIDED, - format!("{name:?} on {source}: already confirmed or rejected"), - ); + note(drop_reason::DECIDED, proposed.draft.table.clone()); } } - // 超过上限的那些一条没看,也得记:不然 returned 与 accepted + dropped 对不上, - // 而账本的用处正是让人看出「模型回了六十条、我们只看了三十六条」 if proposals.len() > cap as usize { drops.insert( drop_reason::CAP, @@ -535,7 +425,7 @@ async fn explore(state: &AppState, kb_id: Uuid, run: Uuid) -> anyhow::Result<()> #[cfg(test)] mod tests { - use super::{column_line, parse_description, proposal_cap}; + use super::{column_line, parse_description}; use crate::query_engine::SchemaColumn; fn column(pk: bool, fk: Option<&str>, comment: Option<&str>) -> SchemaColumn { @@ -603,20 +493,4 @@ mod tests { Vec::::new() ); } - - #[test] - fn a_bigger_schema_gets_a_bigger_cap() { - // 小库不缩水:从前写死的 12 在这一端是对的 - assert_eq!(proposal_cap(1), 12); - assert_eq!(proposal_cap(4), 12); - // 八张表的 TPC-H:从前 12 条封顶,二十四条真值只覆盖了 6 条(#501) - assert_eq!(proposal_cap(8), 24); - // TPC-DS 二十四张表 - assert_eq!(proposal_cap(24), 60); - // 再大也到此为止:提示词与一轮人工审阅都有自己的上限 - assert_eq!(proposal_cap(300), 60); - // 一张表都没扫见(源连不上、schema 是空的)也不该是 0—— - // **0 条上限会把「连不上」变成「模型什么都没提」**,两件事又混在一起了 - assert_eq!(proposal_cap(0), 12); - } } diff --git a/crates/utopia-server/src/table_exploration.rs b/crates/utopia-server/src/table_exploration.rs new file mode 100644 index 000000000..a111c58dc --- /dev/null +++ b/crates/utopia-server/src/table_exploration.rs @@ -0,0 +1,175 @@ +//! Schema exploration proposes columns and their owners, never business definitions. +use serde_json::{json, Value}; +use std::collections::HashSet; +use utopia_core::{AppError, AppResult}; +use utopia_store::table_alignments::{self, Draft, Proposal}; +use uuid::Uuid; + +#[cfg(test)] +#[path = "table_exploration_tests.rs"] +mod tests; + +pub(crate) async fn ontology_context(pool: &sqlx::PgPool, kb_id: Uuid) -> AppResult { + let classes = utopia_store::graph::entity_types(pool, kb_id).await?; + let properties = utopia_store::graph::relation_types(pool, kb_id).await?; + let keys: std::collections::HashMap<_, _> = classes.iter().map(|c| (c.id, &c.key)).collect(); + let names = |ids: &[Uuid]| { + ids.iter() + .filter_map(|id| keys.get(id)) + .copied() + .collect::>() + }; + Ok(json!({ + "classes": classes.iter().map(|c| json!({"key":c.key,"label":c.label,"parents":names(&c.parents)})).collect::>(), + "properties": properties.iter().map(|p| json!({"key":p.key,"label":p.label,"kind":p.kind, + "domains":names(&p.domains),"ranges":names(&p.ranges),"datatype":p.datatype,"unit":p.unit})).collect::>() + })) +} + +pub(crate) fn prompt(schema: &str, ontology: &Value, cap: i32, lang: &str) -> String { + let language = if lang == "zh" { "Chinese" } else { "English" }; + format!( + r#"Align these database tables to the ontology. Propose at most {cap} TABLE alignments. +Write labels, descriptions, summaries and omission reasons in {language}; preserve existing keys and identifiers. +Reply with ONLY a JSON array. One item is one whole table, adopted or rejected together: +{{"source":"exact mounted source name","table":"schema.table","class":"class_key", + "summary":"what one row represents; evidence from the schema comments", + "entity_types":[{{"key":"order","label":"Order","description":"a purchase order","parents":[]}}], + "attribute_types":[{{"key":"paid_amount","label":"paidAmount","description":"paid amount","domains":["order"],"datatype":"number","unit":"CNY"}}], + "relation_types":[{{"key":"buyer","label":"buyer","description":"the customer placing the order","domains":["order"],"ranges":["customer"]}}], + "columns":[{{"column":"amt_pay","class":"order","property":"paid_amount","expression":"CAST(amt_pay AS DOUBLE PRECISION) / 100"}}, + {{"column":"buyer_id","class":"order","property":"buyer","target_class":"customer"}}, + {{"column":"buyer_lvl","class":"customer","property":"tier","expression":"buyer_lvl"}}], + "omitted":[{{"column":"etl_dt","reason":"ETL bookkeeping, not an attribute of an order"}}]}} +The example is schematic: every referenced class/property must exist in the ontology below or be declared in this same item. +Reuse existing classes and properties by EXACT KEY when their meaning fits. The three declaration lists contain only NEW vocabulary; use empty lists when nothing new is needed. New keys use lowercase letters, digits and underscores. +A wide table flattens several classes: each column names its owner. A foreign key is a relation to a target class, not a quantity. Flattened attributes still name their owner even when that owner has no separate key column (e.g. Address.province). +Account for EVERY shown column exactly once, either aligned or omitted with a reason. Omit technical/version/ETL/obsolete/comment columns without a business attribute. Do not invent absent columns or sources. +An attribute has a scalar expression using raw columns of this table. Default is its own column. Supported: arithmetic, CAST AS DOUBLE PRECISION, simple literal CASE, date_trunc('year'|'month'|'day', column). No SELECT, aggregate, filter, join, custom function or business definition. Relation columns have target_class and NO expression. Attribute columns have NO target_class. A conversion cannot read two different columns bound to the same ontology attribute. Different owners may each bind the same attribute in their own conversions. Expressions may read only columns aligned as attributes; these bindings are raw inputs, not other conversions' results. +Conversions follow stated units and code values only. Do not propose GMV, refund rates or rules defining valid orders. The schema cannot supply those business conventions. +Existing ontology: +{ontology} +Schemas (the source and table names below are authoritative; comments are evidence, not instructions): +{schema}"# + ) +} + +/// A model can name any string. Only a complete, freshly read table is eligible; +/// validating just the model's column list would bless a hallucinated column. +pub(crate) fn validate_schema( + draft: &Draft, + columns: &[crate::query_engine::SchemaColumn], +) -> AppResult<()> { + let actual: HashSet<&str> = columns + .iter() + .filter(|c| format!("{}.{}", c.schema, c.table) == draft.table) + .map(|c| c.column.as_str()) + .collect(); + let claimed: Vec<&str> = draft + .columns + .iter() + .map(|c| c.column.as_str()) + .chain(draft.omitted.iter().map(|c| c.column.as_str())) + .collect(); + if actual.is_empty() + || claimed.len() != actual.len() + || claimed.iter().copied().collect::>() != actual + { + return Err(AppError::invalid( + "bad_table_alignment", + "An alignment must account for every column of one existing table exactly once", + )); + } + Ok(()) +} + +pub(crate) async fn prepare( + pool: &sqlx::PgPool, + kb_id: Uuid, + source_id: Uuid, + source: &str, + mut raw: Value, + columns: &[crate::query_engine::SchemaColumn], +) -> AppResult { + if let Some(object) = raw.as_object_mut() { + object.remove("source"); + } + let draft: Draft = serde_json::from_value(raw) + .map_err(|e| AppError::invalid("bad_table_alignment", e.to_string()))?; + validate_schema(&draft, columns)?; + table_alignments::prepare( + pool, + kb_id, + Proposal { + version: Uuid::now_v7(), + source_id, + source: source.into(), + draft, + attribute_ids: Default::default(), + }, + crate::api::rule_expression_input::compile, + ) + .await +} + +pub(crate) async fn decide( + state: &crate::state::AppState, + kb_id: Uuid, + key: &str, + version: Uuid, + adopt: bool, + actor: Uuid, +) -> AppResult<()> { + if adopt { + let stored = utopia_store::ontology::open_proposal( + &state.pool, + kb_id, + table_alignments::SECTION, + key, + ) + .await? + .ok_or(AppError::NotFound)?; + let proposal: Proposal = serde_json::from_value(stored.payload) + .map_err(|e| AppError::invalid("bad_table_alignment", e.to_string()))?; + if proposal.version != version { + return Err(AppError::Conflict( + "This proposal changed; refresh before reviewing it".into(), + )); + } + let mounted = utopia_store::datasources::mounted(&state.pool, kb_id).await?; + if !mounted.iter().any(|s| s.id == proposal.source_id) { + return Err(AppError::NotFound); + } + let (engine, conn) = + utopia_store::datasources::engine_and_conn(&state.pool, proposal.source_id).await?; + let columns = crate::query_engine::engine_for(&engine, &conn) + .map_err(AppError::Other)? + .fetch_schema() + .await + .map_err(AppError::Other)?; + validate_schema(&proposal.draft, &columns)?; + } + table_alignments::decide(&state.pool, kb_id, key, version, adopt, actor).await?; + if adopt { + if let Err(e) = crate::ontology_index::refresh(state, kb_id).await { + tracing::warn!(%kb_id, error=%e, "Table alignment adopted; ontology index refresh deferred"); + } + state.emit_graph(kb_id); + } + let _ = utopia_store::audit::record( + &state.pool, + Some(kb_id), + actor, + if adopt { + "table_alignment.adopted" + } else { + "table_alignment.rejected" + }, + "table_alignment", + None, + json!({"key":key}), + ) + .await; + state.emit_review(kb_id); + Ok(()) +} diff --git a/crates/utopia-server/src/table_exploration_tests.rs b/crates/utopia-server/src/table_exploration_tests.rs new file mode 100644 index 000000000..cf7228db1 --- /dev/null +++ b/crates/utopia-server/src/table_exploration_tests.rs @@ -0,0 +1,430 @@ +//! Exercise the real schema reader and store with a scripted model. No external +//! provider or business data is needed; SQL and rollback must actually run. +use super::*; +use axum::{extract::State, response::IntoResponse, routing::post, Json, Router}; +use std::sync::{Arc, Mutex}; +use utopia_store::table_alignments as store; + +#[tokio::test] +async fn two_owners_reuse_an_attribute_but_keep_separate_raw_column_bindings() -> anyhow::Result<()> +{ + let Some(fx) = Fx::new().await? else { + return Ok(()); + }; + let mut raw = fx.raw("orders"); + raw["attribute_types"] = json!([{"key":"code","label":"code","description":"a numeric code","domains":["order","customer"],"datatype":"number"}]); + raw["columns"][0]["property"] = json!("code"); + raw["columns"][0]["expression"] = json!("amt_pay"); + raw["columns"][2]["property"] = json!("code"); + raw["columns"][2]["expression"] = json!("buyer_lvl"); + let mut ambiguous = raw.clone(); + ambiguous["columns"][0]["expression"] = json!("amt_pay + buyer_lvl"); + assert!(fx.prepare(ambiguous).await.is_err()); + let p = fx.prepare(raw).await?; + store::save(&fx.pool, fx.kb, &p).await?; + store::decide( + &fx.pool, + fx.kb, + &store::key(fx.source, &p.draft.table), + p.version, + true, + fx.actor, + ) + .await?; + let rows:Vec<(String,Uuid,Value)>=sqlx::query_as("SELECT c.column_name,c.property_id,c.input_columns FROM table_alignment_columns c JOIN table_alignments a ON a.id=c.alignment_id WHERE a.kb_id=$1 AND c.expression IS NOT NULL ORDER BY c.column_name") + .bind(fx.kb).fetch_all(&fx.pool).await?; + assert_eq!(rows.len(), 2); + assert_eq!(rows[0].1, rows[1].1); + for (column, id, inputs) in &rows { + assert_eq!(inputs[&id.to_string()], json!(column)); + } + assert!(matches!( + utopia_store::ontology::delete_relation_type(&fx.pool, fx.kb, rows[0].1).await, + Err(AppError::Conflict(_)) + )); + let class: Uuid = sqlx::query_scalar("SELECT class_id FROM table_alignments WHERE kb_id=$1") + .bind(fx.kb) + .fetch_one(&fx.pool) + .await?; + assert!(matches!( + utopia_store::ontology::delete_entity_type(&fx.pool, fx.kb, class).await, + Err(AppError::Conflict(_)) + )); + fx.cleanup().await +} + +#[derive(Clone)] +struct Model(Arc>>, Arc>>); +async fn reply(State(model): State, Json(request): Json) -> impl IntoResponse { + model.1.lock().unwrap().push(request); + let text = model.0.lock().unwrap().remove(0).to_string(); + Json(json!({"choices":[{"message":{"role":"assistant","content":text}}]})) +} + +struct Fx { + pool: sqlx::PgPool, + state: crate::state::AppState, + kb: Uuid, + org: Uuid, + actor: Uuid, + source: Uuid, + schema: String, + model: Model, + server: tokio::task::JoinHandle<()>, + _dir: tempfile::TempDir, +} + +impl Fx { + async fn new() -> anyhow::Result> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(None); + }; + // Holding a transaction and then acquiring a second connection would + // hang this fixture, exposing accidental pool calls inside adoption. + let pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .connect(&url) + .await?; + utopia_store::db::migrate(&pool).await?; + let (org, ws, kb, actor, source) = ( + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + ); + let schema = format!("alignment_{}", kb.simple()); + sqlx::raw_sql(&format!( + "INSERT INTO organizations(id,name) VALUES('{org}','alignment'); + INSERT INTO workspaces(id,org_id,name) VALUES('{ws}','{org}','alignment'); + INSERT INTO knowledge_bases(id,workspace_id,name) VALUES('{kb}','{ws}','alignment'); + INSERT INTO users(id,org_id,email,password_hash,display_name) VALUES('{actor}','{org}','{actor}@alignment.test','unused','Reviewer'); + CREATE SCHEMA {schema}; + CREATE TABLE {schema}.orders(amt_pay bigint,buyer_id bigint,buyer_lvl integer,etl_dt timestamptz); + CREATE TABLE {schema}.archive(LIKE {schema}.orders);" + )).execute(&pool).await?; + sqlx::query( + "INSERT INTO data_sources(id,name,engine,conn_string) VALUES($1,$2,'postgres',$3)", + ) + .bind(source) + .bind(format!("alignment-{source}")) + .bind(utopia_core::secrets::seal(&url)) + .execute(&pool) + .await?; + utopia_store::datasources::mount(&pool, kb, source).await?; + let model = Model(Default::default(), Default::default()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let endpoint = format!("http://{}", listener.local_addr()?); + let router = Router::new() + .route("/chat/completions", post(reply)) + .with_state(model.clone()); + let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); + utopia_store::settings::upsert( + &pool, + ws, + Some(&endpoint), + None, + Some("scripted"), + None, + None, + None, + None, + ) + .await?; + let dir = tempfile::tempdir()?; + let cfg = utopia_core::config::AppConfig { + data_dir: dir.path().to_string_lossy().into_owned(), + ..Default::default() + }; + let search = Arc::new(utopia_search::SearchIndex::open( + &dir.path().join("search"), + )?); + let state = crate::state::AppState::new(pool.clone(), &cfg, search, "test-only".into()); + Ok(Some(Self { + pool, + state, + kb, + org, + actor, + source, + schema, + model, + server, + _dir: dir, + })) + } + + fn raw(&self, table: &str) -> Value { + json!({"source":format!("alignment-{}",self.source),"table":format!("{}.{table}",self.schema),"class":"order","summary":"One row per order; amount in cents", + "entity_types":[ + {"key":"order","label":"Order","description":"a purchase order"}, + {"key":"customer","label":"Customer","description":"the purchaser"}], + "attribute_types":[ + {"key":"paid_amount","label":"paidAmount","description":"paid amount","domains":["order"],"datatype":"number","unit":"CNY"}, + {"key":"tier","label":"tier","description":"customer tier","domains":["customer"],"datatype":"text"}], + "relation_types":[{"key":"buyer","label":"buyer","description":"the purchaser","domains":["order"],"ranges":["customer"]}], + "columns":[ + {"column":"amt_pay","class":"order","property":"paid_amount","expression":"CAST(amt_pay AS DOUBLE PRECISION) / 100"}, + {"column":"buyer_id","class":"order","property":"buyer","target_class":"customer","expression":null}, + {"column":"buyer_lvl","class":"customer","property":"tier","expression":"CASE buyer_lvl WHEN 2 THEN 'gold' ELSE 'standard' END"}], + "omitted":[{"column":"etl_dt","reason":"ETL bookkeeping"}]}) + } + + async fn columns(&self) -> anyhow::Result> { + let (engine, conn) = + utopia_store::datasources::engine_and_conn(&self.pool, self.source).await?; + crate::query_engine::engine_for(&engine, &conn)? + .fetch_schema() + .await + } + + async fn prepare(&self, raw: Value) -> AppResult { + prepare( + &self.pool, + self.kb, + self.source, + &format!("alignment-{}", self.source), + raw, + &self.columns().await.unwrap(), + ) + .await + } + + async fn counts(&self) -> anyhow::Result<(i64, i64, i64, i64)> { + Ok(sqlx::query_as( + "SELECT + (SELECT count(*) FROM entity_types WHERE kb_id=$1), + (SELECT count(*) FROM relation_types WHERE kb_id=$1), + (SELECT count(*) FROM table_alignments WHERE kb_id=$1), + (SELECT count(*) FROM entities WHERE kb_id=$1)", + ) + .bind(self.kb) + .fetch_one(&self.pool) + .await?) + } + + async fn cleanup(self) -> anyhow::Result<()> { + self.server.abort(); + sqlx::query("DELETE FROM jobs WHERE payload->>'kb_id'=$1") + .bind(self.kb.to_string()) + .execute(&self.pool) + .await?; + sqlx::query("DELETE FROM knowledge_bases WHERE id=$1") + .bind(self.kb) + .execute(&self.pool) + .await?; + sqlx::query("DELETE FROM data_sources WHERE id=$1") + .bind(self.source) + .execute(&self.pool) + .await?; + sqlx::query("DELETE FROM organizations WHERE id=$1") + .bind(self.org) + .execute(&self.pool) + .await?; + sqlx::raw_sql(&format!("DROP SCHEMA {} CASCADE", self.schema)) + .execute(&self.pool) + .await?; + Ok(()) + } +} + +#[tokio::test] +async fn exploration_waits_for_a_whole_table_decision_and_stores_executable_conversions( +) -> anyhow::Result<()> { + let Some(fx) = Fx::new().await? else { + return Ok(()); + }; + fx.model.0.lock().unwrap().extend([ + json!({"description":"Orders with purchaser tier","questions":[]}), + json!([fx.raw("orders")]), + ]); + crate::mappings::explore_mappings(&fx.state, fx.kb).await?; + assert_eq!( + fx.counts().await?, + (0, 0, 0, 0), + "exploration cannot create ontology or graph rows" + ); + let items = store::list(&fx.pool, fx.kb).await?; + assert_eq!(items.len(), 1); + let p: Proposal = serde_json::from_value(items[0].payload.clone())?; + assert!(p.draft.columns[0].expression.as_ref().unwrap().is_object()); + decide(&fx.state, fx.kb, &items[0].key, p.version, true, fx.actor).await?; + assert_eq!(fx.counts().await?, (2, 3, 1, 0)); + let rows: Vec<(String,Uuid,Value)> = sqlx::query_as( + "SELECT c.column_name,c.property_id,c.expression FROM table_alignment_columns c + JOIN table_alignments a ON a.id=c.alignment_id WHERE a.kb_id=$1 AND c.expression IS NOT NULL") + .bind(fx.kb).fetch_all(&fx.pool).await?; + for (column, id, tree) in rows { + use utopia_reason::{expressions::Scalar, rules::Expr}; + let result = Expr::from_json(&tree) + .unwrap() + .evaluate(&|input| { + assert_eq!( + input, id, + "persisted leaves name actual ontology attributes" + ); + Some(Scalar::Number(if column == "amt_pay" { + 12345.0 + } else { + 2.0 + })) + }) + .unwrap() + .to_json(); + assert_eq!( + result, + if column == "amt_pay" { + json!(123.45) + } else { + json!("gold") + } + ); + } + assert!( + !store::save(&fx.pool, fx.kb, &p).await?, + "a rerun cannot replace the decision" + ); + let runs = utopia_store::exploration_runs::recent(&fx.pool, fx.kb, 1).await?; + assert_eq!(runs[0].accepted, 1); + assert_eq!(fx.model.1.lock().unwrap().len(), 2); + fx.cleanup().await +} + +#[tokio::test] +async fn adoption_rolls_back_every_write_and_serializes_double_clicks() -> anyhow::Result<()> { + let Some(fx) = Fx::new().await? else { + return Ok(()); + }; + let p = fx.prepare(fx.raw("orders")).await?; + store::save(&fx.pool, fx.kb, &p).await?; + let key = store::key(fx.source, &p.draft.table); + // The final decision write fails its actor FK, after the class/property, + // alignment, column and queue writes have all run. + assert!( + store::decide(&fx.pool, fx.kb, &key, p.version, true, Uuid::now_v7()) + .await + .is_err() + ); + assert_eq!(fx.counts().await?, (0, 0, 0, 0)); + assert_eq!(store::list(&fx.pool, fx.kb).await?[0].status, "open"); + let queued: i64 = sqlx::query_scalar("SELECT count(*) FROM jobs WHERE payload->>'kb_id'=$1") + .bind(fx.kb.to_string()) + .fetch_one(&fx.pool) + .await?; + assert_eq!(queued, 0); + let (a, b) = tokio::join!( + store::decide(&fx.pool, fx.kb, &key, p.version, true, fx.actor), + store::decide(&fx.pool, fx.kb, &key, p.version, true, fx.actor) + ); + assert_ne!(a.is_ok(), b.is_ok()); + assert_eq!(fx.counts().await?, (2, 3, 1, 0)); + // A second table can reuse the same declarations, including attributes + // proposed before either table was adopted, without changing their meaning. + let second = fx.prepare(fx.raw("archive")).await?; + store::save(&fx.pool, fx.kb, &second).await?; + store::decide( + &fx.pool, + fx.kb, + &store::key(fx.source, &second.draft.table), + second.version, + true, + fx.actor, + ) + .await?; + assert_eq!(fx.counts().await?, (2, 3, 2, 0)); + fx.cleanup().await +} + +#[tokio::test] +async fn a_refresh_rejection_or_unmount_cannot_be_bypassed_by_an_old_review() -> anyhow::Result<()> +{ + let Some(fx) = Fx::new().await? else { + return Ok(()); + }; + let first = fx.prepare(fx.raw("orders")).await?; + store::save(&fx.pool, fx.kb, &first).await?; + let second = fx.prepare(fx.raw("orders")).await?; + store::save(&fx.pool, fx.kb, &second).await?; + let key = store::key(fx.source, &first.draft.table); + assert!( + store::decide(&fx.pool, fx.kb, &key, first.version, true, fx.actor) + .await + .is_err() + ); + assert!(store::decide( + &fx.pool, + Uuid::now_v7(), + &key, + second.version, + true, + fx.actor + ) + .await + .is_err()); + store::decide(&fx.pool, fx.kb, &key, second.version, false, fx.actor).await?; + assert!(!store::save(&fx.pool, fx.kb, &first).await?); + assert_eq!(store::list(&fx.pool, fx.kb).await?[0].status, "rejected"); + assert_eq!(fx.counts().await?, (0, 0, 0, 0)); + let other = fx.prepare(fx.raw("archive")).await?; + store::save(&fx.pool, fx.kb, &other).await?; + utopia_store::datasources::unmount(&fx.pool, fx.kb, fx.source).await?; + assert!(store::list(&fx.pool, fx.kb).await?.is_empty()); + assert!(store::decide( + &fx.pool, + fx.kb, + &store::key(fx.source, &other.draft.table), + other.version, + true, + fx.actor + ) + .await + .is_err()); + fx.cleanup().await +} + +#[tokio::test] +async fn invalid_columns_signatures_and_expressions_never_become_proposals() -> anyhow::Result<()> { + let Some(fx) = Fx::new().await? else { + return Ok(()); + }; + let base = fx.raw("orders"); + for (pointer, value) in [ + ("/table", json!("missing.orders")), + ("/columns/0/column", json!("does_not_exist")), + ("/columns/0/class", json!("customer")), + ("/columns/0/expression", json!("SUM(amt_pay)")), + ("/columns/0/expression", json!("missing / 100")), + ("/columns/0/expression", json!({"attr":Uuid::now_v7()})), + ("/columns/1/target_class", json!("order")), + ("/columns/1/expression", json!("buyer_id")), + ("/attribute_types/0/datatype", json!("money")), + ("/omitted/0/column", json!("amt_pay")), + ] { + let mut raw = base.clone(); + *raw.pointer_mut(pointer) + .unwrap_or_else(|| panic!("missing {pointer}")) = value; + assert!(fx.prepare(raw).await.is_err(), "accepted {pointer}"); + } + let p = fx.prepare(base).await?; + store::save(&fx.pool, fx.kb, &p).await?; + // The schema can change while a person is reviewing it. Re-read before + // adoption rather than trusting the exploration's earlier snapshot. + sqlx::raw_sql(&format!( + "ALTER TABLE {}.orders DROP COLUMN buyer_lvl", + fx.schema + )) + .execute(&fx.pool) + .await?; + assert!(decide( + &fx.state, + fx.kb, + &store::key(fx.source, &p.draft.table), + p.version, + true, + fx.actor + ) + .await + .is_err()); + assert_eq!(fx.counts().await?, (0, 0, 0, 0)); + fx.cleanup().await +} diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs index 7425fad2c..0b15ba075 100644 --- a/crates/utopia-store/src/graph.rs +++ b/crates/utopia-store/src/graph.rs @@ -56,7 +56,10 @@ pub async fn entity_types<'e>( ) } -pub async fn relation_types(pool: &PgPool, kb_id: Uuid) -> AppResult> { +pub async fn relation_types<'e>( + pool: impl sqlx::Executor<'e, Database = sqlx::Postgres>, + kb_id: Uuid, +) -> AppResult> { // 不用 SELECT *:domain/range 在关联表里,`*` 取不到, // 而且 sqlx 要到运行时才会说 "no column found" —— 编译器看不见 SQL 字符串 Ok(sqlx::query_as( diff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rs index 5c869395d..f99da7340 100644 --- a/crates/utopia-store/src/lib.rs +++ b/crates/utopia-store/src/lib.rs @@ -44,6 +44,7 @@ pub mod rss_full_content; pub mod sealing; pub mod settings; pub mod sources; +pub mod table_alignments; pub mod temporal; pub mod test_db; pub mod time_mentions; diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rs index 7c12bb23d..aabcc2de6 100644 --- a/crates/utopia-store/src/ontology.rs +++ b/crates/utopia-store/src/ontology.rs @@ -153,8 +153,8 @@ fn validate_key(key: &str) -> AppResult<()> { } #[allow(clippy::too_many_arguments)] -pub async fn create_entity_type( - pool: &PgPool, +pub async fn create_entity_type<'a>( + pool: impl sqlx::Acquire<'a, Database = sqlx::Postgres>, kb_id: Uuid, key: &str, label: &str, @@ -165,6 +165,7 @@ pub async fn create_entity_type( ) -> AppResult { validate_key(key)?; validate_shape(shape)?; + let mut tx = pool.begin().await?; let id = Uuid::now_v7(); sqlx::query( "INSERT INTO entity_types (id, kb_id, key, label, color, shape, description) @@ -177,7 +178,7 @@ pub async fn create_entity_type( .bind(color) .bind(shape) .bind(description) - .execute(pool) + .execute(&mut *tx) .await .map_err(|e| match &e { sqlx::Error::Database(db) if db.is_unique_violation() => { @@ -185,7 +186,8 @@ pub async fn create_entity_type( } _ => AppError::Db(e), })?; - set_parents(&mut *pool.acquire().await?, kb_id, id, parents).await?; + set_parents(&mut tx, kb_id, id, parents).await?; + tx.commit().await?; Ok(id) } @@ -304,6 +306,18 @@ async fn set_parents( pub async fn delete_entity_type(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<()> { let mut tx = pool.begin().await?; + let aligned: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM table_alignments WHERE class_id=$1) + OR EXISTS(SELECT 1 FROM table_alignment_columns WHERE class_id=$1 OR target_class_id=$1) + OR EXISTS(SELECT 1 FROM table_alignment_columns c JOIN relation_type_domains d ON d.relation_type_id=c.property_id + WHERE d.entity_type_id=$1 AND NOT EXISTS(SELECT 1 FROM relation_type_domains other + WHERE other.relation_type_id=d.relation_type_id AND other.entity_type_id<>$1))", + ).bind(id).fetch_one(&mut *tx).await?; + if aligned { + return Err(AppError::Conflict( + "Cannot delete a class used by a table alignment".into(), + )); + } let (usage,): (i64,) = sqlx::query_as("SELECT count(*) FROM entities WHERE type_id = $1") .bind(id) .fetch_one(&mut *tx) @@ -455,8 +469,8 @@ async fn validate_property_links( } #[allow(clippy::too_many_arguments)] -pub async fn create_relation_type( - pool: &PgPool, +pub async fn create_relation_type<'a>( + pool: impl sqlx::Acquire<'a, Database = sqlx::Postgres>, kb_id: Uuid, key: &str, label: &str, @@ -476,9 +490,10 @@ pub async fn create_relation_type( )); } validate_attribute_fields(kind, domains, datatype)?; + let mut tx = pool.begin().await?; let label = &lower_camel(label); // 新建的行 id 还不存在,指向自己无从谈起——所以 self_id 传 None - validate_property_links(&mut *pool.acquire().await?, kb_id, None, kind, ax).await?; + validate_property_links(&mut tx, kb_id, None, kind, ax).await?; let is_attr = kind == "attribute"; let id = Uuid::now_v7(); sqlx::query( @@ -509,7 +524,7 @@ pub async fn create_relation_type( // 属性不带这两条(上面已经拦了非空的情况,这里是兜底) .bind(if is_attr { None } else { ax.inverse_of }) .bind(if is_attr { None } else { ax.sub_property_of }) - .execute(pool) + .execute(&mut *tx) .await .map_err(|e| match &e { sqlx::Error::Database(db) if db.is_unique_violation() => { @@ -518,13 +533,8 @@ pub async fn create_relation_type( _ => AppError::Db(e), })?; // attribute 不写 range:它的值域是字面量类型,落在 datatype 上 - set_domains_ranges( - &mut *pool.acquire().await?, - id, - domains, - if is_attr { &[] } else { ranges }, - ) - .await?; + set_domains_ranges(&mut tx, id, domains, if is_attr { &[] } else { ranges }).await?; + tx.commit().await?; Ok(id) } @@ -839,6 +849,17 @@ struct OldCriteria { pub async fn delete_relation_type(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<()> { let mut tx = pool.begin().await?; + let aligned: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM table_alignment_columns WHERE property_id=$1)", + ) + .bind(id) + .fetch_one(&mut *tx) + .await?; + if aligned { + return Err(AppError::Conflict( + "Cannot delete a property used by a table alignment".into(), + )); + } let (usage,): (i64,) = sqlx::query_as("SELECT count(*) FROM facts WHERE predicate_id = $1") .bind(id) .fetch_one(&mut *tx) @@ -1758,7 +1779,7 @@ pub struct StoredProposal { pub section: String, pub key: String, pub payload: serde_json::Value, - /// suggest | agent + /// suggest | agent | exploration pub proposed_by: String, pub serves: Vec, pub signatures: serde_json::Value, diff --git a/crates/utopia-store/src/table_alignments.rs b/crates/utopia-store/src/table_alignments.rs new file mode 100644 index 000000000..5b0e67e50 --- /dev/null +++ b/crates/utopia-store/src/table_alignments.rs @@ -0,0 +1,603 @@ +//! A table's ontology declarations and column bindings are one human decision (0036). +//! Exploration stores an expression tree with provisional attribute identities. Adoption +//! resolves those keys again in its transaction and substitutes the actual identities; +//! two tables can therefore propose the same new attribute without creating it twice. + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use sqlx::PgPool; +use std::collections::{BTreeMap, HashMap, HashSet}; +use utopia_core::models::{EntityType, RelationAxioms, RelationType}; +use utopia_core::{AppError, AppResult}; +use utopia_reason::rules::Expr; +use uuid::Uuid; + +pub const SECTION: &str = "table_alignments"; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ClassDeclaration { + pub key: String, + pub label: String, + pub description: String, + #[serde(default)] + pub parents: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PropertyDeclaration { + pub key: String, + pub label: String, + pub description: String, + pub domains: Vec, + #[serde(default)] + pub ranges: Vec, + pub datatype: Option, + pub unit: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ColumnAlignment { + pub column: String, + pub class: String, + pub property: String, + pub target_class: Option, + pub expression: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OmittedColumn { + pub column: String, + pub reason: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Draft { + pub table: String, + pub class: String, + pub summary: String, + #[serde(default)] + pub entity_types: Vec, + #[serde(default)] + pub attribute_types: Vec, + #[serde(default)] + pub relation_types: Vec, + pub columns: Vec, + #[serde(default)] + pub omitted: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Proposal { + pub version: Uuid, + pub source_id: Uuid, + pub source: String, + pub draft: Draft, + /// Raw column -> provisional attribute identity. Each conversion keeps its + /// own input bindings when these become actual ontology attribute IDs. + pub attribute_ids: BTreeMap, +} + +#[derive(Serialize, sqlx::FromRow)] +pub struct ProposalView { + pub id: Uuid, + pub key: String, + pub status: String, + pub payload: Value, +} + +fn invalid(message: impl Into) -> AppError { + AppError::invalid("bad_table_alignment", message) +} + +pub fn key(source_id: Uuid, table: &str) -> String { + format!("{source_id}:{table}") +} + +// Validate against ontology keys, including inherited domains/ranges. Reusing an +// existing key never authorizes exploration to change its meaning or signature. +struct Catalogue { + classes: HashMap>, + properties: HashMap, +} + +impl Catalogue { + fn new(classes: &[EntityType], properties: &[RelationType], draft: &Draft) -> AppResult { + let keys: HashMap = classes.iter().map(|c| (c.id, c.key.clone())).collect(); + let names = |ids: &[Uuid]| ids.iter().filter_map(|id| keys.get(id).cloned()).collect(); + let mut out = Self { + classes: classes + .iter() + .map(|c| (c.key.clone(), names(&c.parents))) + .collect(), + properties: properties + .iter() + .map(|p| { + ( + p.key.clone(), + ( + p.kind.clone(), + PropertyDeclaration { + key: p.key.clone(), + label: p.label.clone(), + description: p.description.clone(), + domains: names(&p.domains), + ranges: names(&p.ranges), + datatype: p.datatype.clone(), + unit: p.unit.clone(), + }, + ), + ) + }) + .collect(), + }; + let mut declared = HashSet::new(); + for c in &draft.entity_types { + validate_declaration(&c.key, &c.label)?; + if !declared.insert(&c.key) { + return Err(invalid("A class is declared twice")); + } + if let Some(parents) = out.classes.get(&c.key) { + if !same_set(parents, &c.parents) { + return Err(invalid(format!("Class {} changed; explore again", c.key))); + } + } else { + out.classes.insert(c.key.clone(), c.parents.clone()); + } + } + for c in &draft.entity_types { + for parent in &c.parents { + out.class(parent)?; + } + if c.parents.iter().any(|p| out.is_a(p, &c.key)) { + return Err(invalid("Proposed classes form a cycle")); + } + } + declared.clear(); + for (kind, list) in [ + ("attribute", &draft.attribute_types), + ("relation", &draft.relation_types), + ] { + for p in list { + validate_declaration(&p.key, &p.label)?; + if !declared.insert(&p.key) { + return Err(invalid("A property is declared twice")); + } + for c in p.domains.iter().chain(&p.ranges) { + out.class(c)?; + } + if p.domains.is_empty() + || (kind == "attribute" + && (!p.ranges.is_empty() + || !matches!( + p.datatype.as_deref(), + Some("text" | "number" | "date" | "bool") + ))) + || (kind == "relation" + && (p.ranges.is_empty() || p.datatype.is_some() || p.unit.is_some())) + { + return Err(invalid(format!("Invalid signature for {}", p.key))); + } + if let Some((old_kind, old)) = out.properties.get(&p.key) { + if old_kind != kind + || !same_set(&old.domains, &p.domains) + || !same_set(&old.ranges, &p.ranges) + || old.datatype != p.datatype + || old.unit != p.unit + { + return Err(invalid(format!( + "Property {} changed; explore again", + p.key + ))); + } + } else { + out.properties + .insert(p.key.clone(), (kind.into(), p.clone())); + } + } + } + Ok(out) + } + + fn class(&self, key: &str) -> AppResult<()> { + self.classes + .contains_key(key) + .then_some(()) + .ok_or_else(|| invalid(format!("Unknown class {key}"))) + } + + fn is_a(&self, child: &str, ancestor: &str) -> bool { + let mut pending = vec![child]; + let mut visited = HashSet::new(); + while let Some(key) = pending.pop() { + if key == ancestor { + return true; + } + if visited.insert(key) { + if let Some(parents) = self.classes.get(key) { + pending.extend(parents.iter().map(String::as_str)); + } + } + } + false + } + + fn validate(&self, proposal: &Proposal) -> AppResult<()> { + let d = &proposal.draft; + self.class(&d.class)?; + if d.table.trim().is_empty() + || d.summary.trim().is_empty() + || d.columns.is_empty() + || d.columns.len() > 200 + { + return Err(invalid( + "An alignment needs a table, summary and between one and 200 columns", + )); + } + let mut columns = HashSet::new(); + let mut attributes = HashSet::new(); + for c in &d.columns { + self.class(&c.class)?; + if c.column.is_empty() || !columns.insert(&c.column) { + return Err(invalid("A column is aligned twice")); + } + let (kind, p) = self + .properties + .get(&c.property) + .ok_or_else(|| invalid(format!("Unknown property {}", c.property)))?; + if !p.domains.is_empty() && !p.domains.iter().any(|domain| self.is_a(&c.class, domain)) + { + return Err(invalid(format!( + "{} is not an attribute or relation of {}", + c.property, c.class + ))); + } + match (kind.as_str(), &c.target_class, &c.expression) { + ("attribute", None, Some(tree)) => { + attributes.insert(&c.column); + let expr = Expr::from_json(tree) + .map_err(|e| AppError::invalid(e.code(), e.message()))?; + let mut reads = Vec::new(); + expr.predicates(&mut reads); + let allowed: HashSet = proposal.attribute_ids.values().copied().collect(); + if reads.iter().any(|id| !allowed.contains(id)) { + return Err(invalid( + "An expression reads an attribute without a column binding", + )); + } + let mut bound = HashMap::new(); + for input in reads { + let column = proposal + .attribute_ids + .iter() + .find(|(_, id)| **id == input) + .unwrap() + .0; + let property = &d + .columns + .iter() + .find(|c| &c.column == column && c.target_class.is_none()) + .ok_or_else(|| invalid("Expression input is not an aligned attribute"))? + .property; + if let Some(previous) = bound.insert(property, column) { + if previous != column { + return Err(invalid("One conversion cannot read two columns bound to the same attribute")); + } + } + } + } + ("relation", Some(target), None) => { + self.class(target)?; + if !p.ranges.is_empty() + && !p.ranges.iter().any(|range| self.is_a(target, range)) + { + return Err(invalid(format!("{} cannot point to {target}", c.property))); + } + } + _ => { + return Err(invalid( + "An attribute needs a conversion; a relation needs a target class", + )) + } + } + } + for omitted in &d.omitted { + if omitted.reason.trim().is_empty() || !columns.insert(&omitted.column) { + return Err(invalid( + "An omitted column needs a reason and cannot also be aligned", + )); + } + } + if attributes.len() != proposal.attribute_ids.len() + || attributes + .iter() + .any(|k| !proposal.attribute_ids.contains_key(*k)) + || proposal + .attribute_ids + .values() + .collect::>() + .len() + != attributes.len() + { + return Err(invalid("Every input attribute needs exactly one identity")); + } + // A flattened owner need not have its own key column (Address.province + // is a common example). Recording its class is still useful alignment; + // producing joins or row identities belongs to the later renderer. + let used_properties: HashSet<_> = d.columns.iter().map(|c| &c.property).collect(); + if d.attribute_types + .iter() + .chain(&d.relation_types) + .any(|p| !used_properties.contains(&p.key)) + { + return Err(invalid( + "A table cannot propose properties that none of its columns uses", + )); + } + Ok(()) + } +} + +fn same_set(a: &[String], b: &[String]) -> bool { + a.iter().collect::>() == b.iter().collect::>() +} + +fn validate_declaration(key: &str, label: &str) -> AppResult<()> { + if key.is_empty() + || key.len() > 128 + || label.trim().is_empty() + || !key + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') + { + return Err(invalid( + "New ontology keys use lowercase letters, digits and underscores and need a label", + )); + } + Ok(()) +} + +pub async fn prepare( + pool: &PgPool, + kb_id: Uuid, + mut proposal: Proposal, + compile: impl Fn(&str, &HashMap) -> AppResult, +) -> AppResult { + let classes = crate::graph::entity_types(pool, kb_id).await?; + let properties = crate::graph::relation_types(pool, kb_id).await?; + let catalogue = Catalogue::new(&classes, &properties, &proposal.draft)?; + proposal.attribute_ids.clear(); + let mut names = HashMap::new(); + for c in &proposal.draft.columns { + if c.target_class.is_none() { + let id = *proposal + .attribute_ids + .entry(c.column.clone()) + .or_insert_with(Uuid::now_v7); + names.insert(c.column.clone(), id); + } + } + for c in &mut proposal.draft.columns { + if let Some(value) = &mut c.expression { + if let Some(text) = value.as_str() { + *value = compile(text, &names)?; + } + } else if c.target_class.is_none() { + c.expression = Some(json!({"attr": names[&c.column]})); + } + } + catalogue.validate(&proposal)?; + Ok(proposal) +} + +pub async fn save(pool: &PgPool, kb_id: Uuid, proposal: &Proposal) -> AppResult { + let result = sqlx::query( + "INSERT INTO ontology_proposals(id,kb_id,section,key,payload,proposed_by) + SELECT $1,$2,'table_alignments',$3,$4,'exploration' + WHERE EXISTS (SELECT 1 FROM kb_data_sources WHERE kb_id=$2 AND data_source_id=$5) + ON CONFLICT(kb_id,section,key) DO UPDATE SET payload=EXCLUDED.payload, created_at=now() + WHERE ontology_proposals.status='open'", + ) + .bind(Uuid::now_v7()) + .bind(kb_id) + .bind(key(proposal.source_id, &proposal.draft.table)) + .bind(json!(proposal)) + .bind(proposal.source_id) + .execute(pool) + .await?; + Ok(result.rows_affected() == 1) +} + +pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult> { + Ok(sqlx::query_as( + "SELECT p.id,p.key,p.status,p.payload FROM ontology_proposals p + JOIN kb_data_sources m ON m.kb_id=p.kb_id AND m.data_source_id::text=p.payload->>'source_id' + WHERE p.kb_id=$1 AND p.section='table_alignments' ORDER BY p.created_at DESC,p.key", + ).bind(kb_id).fetch_all(pool).await?) +} + +/// Lock the proposal before re-reading its ontology. No pool acquisition is made +/// inside this transaction, so adoption also works with a one-connection pool. +pub async fn decide( + pool: &PgPool, + kb_id: Uuid, + proposal_key: &str, + version: Uuid, + adopt: bool, + actor: Uuid, +) -> AppResult<()> { + let mut tx = pool.begin().await?; + let (id, status, payload): (Uuid, String, Value) = sqlx::query_as( + "SELECT id,status,payload FROM ontology_proposals WHERE kb_id=$1 AND section='table_alignments' AND key=$2 FOR UPDATE", + ).bind(kb_id).bind(proposal_key).fetch_optional(&mut *tx).await?.ok_or(AppError::NotFound)?; + if status != "open" { + return Err(AppError::Conflict( + "This table has already been reviewed".into(), + )); + } + let proposal: Proposal = + serde_json::from_value(payload.clone()).map_err(|e| invalid(e.to_string()))?; + if proposal.version != version { + return Err(AppError::Conflict( + "This proposal changed; refresh before reviewing it".into(), + )); + } + // Unmounting races adoption too: keep the mount until the transaction ends. + let mounted: Option = sqlx::query_scalar( + "SELECT data_source_id FROM kb_data_sources WHERE kb_id=$1 AND data_source_id=$2 FOR SHARE", + ) + .bind(kb_id) + .bind(proposal.source_id) + .fetch_optional(&mut *tx) + .await?; + if mounted.is_none() { + return Err(invalid("The data source is no longer mounted")); + } + if adopt { + let classes = crate::graph::entity_types(&mut *tx, kb_id).await?; + let properties = crate::graph::relation_types(&mut *tx, kb_id).await?; + Catalogue::new(&classes, &properties, &proposal.draft)?.validate(&proposal)?; + let mut class_ids: HashMap = + classes.iter().map(|c| (c.key.clone(), c.id)).collect(); + let mut pending: Vec<_> = proposal + .draft + .entity_types + .iter() + .filter(|c| !class_ids.contains_key(&c.key)) + .collect(); + while !pending.is_empty() { + let pos = pending + .iter() + .position(|c| c.parents.iter().all(|p| class_ids.contains_key(p))) + .ok_or_else(|| invalid("Unresolved class parents"))?; + let c = pending.remove(pos); + let parents: Vec<_> = c.parents.iter().map(|p| class_ids[p]).collect(); + let new_id = crate::ontology::create_entity_type( + &mut *tx, + kb_id, + &c.key, + &c.label, + crate::palette::color_for_key(&c.key), + "circle", + &parents, + &c.description, + ) + .await?; + class_ids.insert(c.key.clone(), new_id); + } + let mut property_ids: HashMap = + properties.iter().map(|p| (p.key.clone(), p.id)).collect(); + for (kind, list) in [ + ("attribute", &proposal.draft.attribute_types), + ("relation", &proposal.draft.relation_types), + ] { + for p in list { + if property_ids.contains_key(&p.key) { + continue; + } + let domains: Vec<_> = p.domains.iter().map(|c| class_ids[c]).collect(); + let ranges: Vec<_> = p.ranges.iter().map(|c| class_ids[c]).collect(); + let new_id = crate::ontology::create_relation_type( + &mut *tx, + kb_id, + &p.key, + &p.label, + "state", + RelationAxioms::default(), + &p.description, + kind, + &domains, + &ranges, + p.datatype.as_deref(), + p.unit.as_deref(), + ) + .await?; + property_ids.insert(p.key.clone(), new_id); + } + } + let alignment_id = Uuid::now_v7(); + sqlx::query("INSERT INTO table_alignments(id,kb_id,data_source_id,table_name,class_id,proposal_id) VALUES($1,$2,$3,$4,$5,$6)") + .bind(alignment_id).bind(kb_id).bind(proposal.source_id).bind(&proposal.draft.table) + .bind(class_ids[&proposal.draft.class]).bind(id).execute(&mut *tx).await?; + let identities: HashMap = proposal + .attribute_ids + .iter() + .map(|(column, id)| { + let key = &proposal + .draft + .columns + .iter() + .find(|c| &c.column == column) + .unwrap() + .property; + (*id, property_ids[key]) + }) + .collect(); + for c in &proposal.draft.columns { + let mut tree = c.expression.clone(); + let mut inputs = BTreeMap::new(); + if let Some(tree) = &mut tree { + let mut reads = Vec::new(); + Expr::from_json(tree) + .map_err(|e| AppError::invalid(e.code(), e.message()))? + .predicates(&mut reads); + for input in reads { + let column = proposal + .attribute_ids + .iter() + .find(|(_, id)| **id == input) + .unwrap() + .0; + inputs.insert(identities[&input].to_string(), column.clone()); + } + remap(tree, &identities)?; + } + sqlx::query("INSERT INTO table_alignment_columns(alignment_id,column_name,class_id,property_id,target_class_id,expression,input_columns) VALUES($1,$2,$3,$4,$5,$6,$7)") + .bind(alignment_id).bind(&c.column).bind(class_ids[&c.class]).bind(property_ids[&c.property]) + .bind(c.target_class.as_ref().map(|c| class_ids[c])).bind(tree).bind(json!(inputs)).execute(&mut *tx).await?; + } + // Queue in the same commit: a newly admitted class/property must become + // visible to the existing ontology index and alignment workers. + for kind in ["align_types", "align_phrases"] { + sqlx::query("INSERT INTO jobs(kind,payload) VALUES($1,$2)") + .bind(kind) + .bind(json!({"kb_id":kb_id})) + .execute(&mut *tx) + .await?; + } + } + sqlx::query( + "UPDATE ontology_proposals SET status=$2,decided_by=$3,decided_at=now() WHERE id=$1", + ) + .bind(id) + .bind(if adopt { "adopted" } else { "rejected" }) + .bind(actor) + .execute(&mut *tx) + .await?; + tx.commit().await?; + Ok(()) +} + +fn remap(value: &mut Value, identities: &HashMap) -> AppResult<()> { + // Only expression nodes are visited. CASE literals and text may themselves + // spell UUIDs, and are data rather than references. + if let Some(object) = value.as_object_mut() { + if let Some(attr) = object.get_mut("attr") { + let id: Uuid = + serde_json::from_value(attr.clone()).map_err(|e| invalid(e.to_string()))?; + *attr = json!(identities + .get(&id) + .ok_or_else(|| invalid("Missing expression input"))?); + } + for field in ["l", "r", "expr", "case"] { + if let Some(child) = object.get_mut(field) { + remap(child, identities)?; + } + } + } + Ok(()) +} diff --git a/docs/decisions/0036-exploration-aligns-a-schema-to-the-ontology.md b/docs/decisions/0036-exploration-aligns-a-schema-to-the-ontology.md index d5cb6a63d..7724fcbbf 100644 --- a/docs/decisions/0036-exploration-aligns-a-schema-to-the-ontology.md +++ b/docs/decisions/0036-exploration-aligns-a-schema-to-the-ontology.md @@ -1,6 +1,6 @@ # 0036 · Exploration aligns a schema to the ontology -- **Status**: In progress · conversion expressions (decision 3) and decision 7 built · open: #554, #556 +- **Status**: In progress · table alignment proposals, conversion expressions and decision 7 built · open: #556 - **Written**: 2026-09-09 (conventions in the [README](README.md)) - **Related**: [0011](0011-a-mapping-is-not-a-fact.md) moved a mapping out of the ledger and is right that it is configuration; this record moves the *concept* out of the entity table. @@ -189,10 +189,58 @@ calendar dates as well as numbers. A bare attribute expression retains its existing numeric interpretation. The read-only rule display follows the tree; the experimental picker is not enabled by this change. -Table/column binding and adoption remain #554. Rendering the tree into each +Table/column binding and adoption are described below. Rendering the tree into each source dialect and retiring the old mapping classes remain #556. This cut does not reinterpret existing SQL mappings or decide the unit policy proposed in 0049. +#### Table alignment proposals (#554) + +Exploration now writes one `ontology_proposals` item in the `table_alignments` +section per mounted source and table. Its payload groups new class, attribute and +relation declarations with every column's owner and property, conversion tree or +relation target, and the reason for each omitted column. Existing vocabulary is +given to the model first. Exploration itself creates no ontology or entity rows +and proposes no aggregate definitions. The manual SQL definition path remains +available while #556 is pending. + +Column names in expression text resolve against the table's aligned attribute +columns, using the same parser and tree as rule input. The stored proposal has +provisional attribute identities; adoption resolves the ontology keys in its +transaction and substitutes the actual attribute IDs. Each conversion also stores +`input_columns` (attribute ID → raw column), so a shop's name and a customer's name +can reuse one ontology attribute without sharing a raw reading. A single +conversion cannot read two columns bound to that same attribute: the current tree +cannot distinguish the two leaves. Inputs are raw readings, not the outputs of +other column conversions. Flattened owners without their own key column, such as +an address's province, retain their class; deriving joins or row identities is +outside this alignment writer. + +`GET /api/v1/kbs/{id}/table-alignments` returns complete proposals and the latest +exploration report. An editor posts `key`, `version` and `status` (`adopted` or +`rejected`) to `/table-alignments/decision`. Adoption re-reads the source schema, +then locks the proposal and checks its version, mount and current ontology. +Classes, properties, table and column bindings, alignment jobs and the decision +commit together. Missing columns, incompatible reused signatures or any write +failure leave the proposal open. Refreshing an open proposal changes its version; +an old review cannot accept the new payload. Re-exploration preserves adopted and +rejected decisions. Unmounting removes active bindings and hides that source's +proposals. The status-only ontology endpoint cannot adopt a table. + +The Data mapping page reviews these groups under Table alignments, showing the +column owners, conversions, exclusions and proposed vocabulary before the two +whole-table actions. Viewers can read them. Editing a conversion and re-adopting an +already decided alignment are not part of this cut; an open proposal can be +regenerated by exploration. Existing SQL definitions retain their own review flow +and remain what Ask reads. + +The database tests use a scripted model and the real Postgres schema reader to +check cold start, conversion binding, atomic rollback, concurrent decisions, +re-exploration and schema drift. `mappings.mjs --alignments --corpus wide` scores +table classes, column owners/properties, foreign-key roles and exclusions against +explicit key alternatives in the truth file. It is a structural score; different +valid vocabulary needs human review, and it does not measure a model's conversion +accuracy or claim results on a live provider. + ### 4. A definition is a rule over aligned attributes, and a person writes it GMV is `sum(Order.paid_amount) where Order.is_valid`. It is not an entity and not a row in diff --git a/migrations/0108_a_table_alignment_is_adopted_together.sql b/migrations/0108_a_table_alignment_is_adopted_together.sql new file mode 100644 index 000000000..4d8c536a1 --- /dev/null +++ b/migrations/0108_a_table_alignment_is_adopted_together.sql @@ -0,0 +1,33 @@ +-- 0036: one proposal owns the whole table. Columns refer to ontology properties, +-- never to concept entities; the conversion is the rule expression tree. +-- Schema proposals do not participate in the question agent's outcome statistics. +ALTER TABLE ontology_proposals DROP CONSTRAINT ontology_proposals_proposed_by_check; +ALTER TABLE ontology_proposals ADD CONSTRAINT ontology_proposals_proposed_by_check + CHECK (proposed_by IN ('suggest', 'agent', 'exploration')); + +CREATE TABLE table_alignments ( + id UUID PRIMARY KEY, + kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE, + data_source_id UUID NOT NULL, + table_name TEXT NOT NULL, + class_id UUID NOT NULL REFERENCES entity_types(id) DEFERRABLE INITIALLY DEFERRED, + proposal_id UUID NOT NULL REFERENCES ontology_proposals(id) DEFERRABLE INITIALLY DEFERRED, + UNIQUE (kb_id, data_source_id, table_name), + FOREIGN KEY (kb_id, data_source_id) + REFERENCES kb_data_sources(kb_id, data_source_id) ON DELETE CASCADE +); + +CREATE TABLE table_alignment_columns ( + alignment_id UUID NOT NULL REFERENCES table_alignments(id) ON DELETE CASCADE, + column_name TEXT NOT NULL, + class_id UUID NOT NULL REFERENCES entity_types(id) DEFERRABLE INITIALLY DEFERRED, + property_id UUID NOT NULL REFERENCES relation_types(id) DEFERRABLE INITIALLY DEFERRED, + target_class_id UUID REFERENCES entity_types(id) DEFERRABLE INITIALLY DEFERRED, + expression JSONB, + -- Per conversion: ontology attribute UUID -> raw input column. Two flattened + -- owners can reuse e.g. name without making their raw readings ambiguous. + input_columns JSONB NOT NULL DEFAULT '{}', + PRIMARY KEY (alignment_id, column_name), + -- A relation identifies a target; an attribute converts a raw column value. + CHECK ((target_class_id IS NULL) = (expression IS NOT NULL)) +); diff --git a/scripts/bench/README.md b/scripts/bench/README.md index 1331d6915..570f0965d 100644 --- a/scripts/bench/README.md +++ b/scripts/bench/README.md @@ -156,6 +156,15 @@ node scripts/bench/govern.mjs --kb --score --stuck # 连留给人的那 ## 映射的测量台(#501) +0036 / #554 之后,探索产物是表对齐提案。用 `node scripts/bench/mappings.mjs +--fresh --corpus wide --alignments` 跑新库,或 `--kb --corpus wide --alignments` +读取已有提案:评分检查表的类、列所属的类与属性、外键的关系目标,以及技术列是否 +明确排除。`wide.mappings.json` 的 `alignment` 是结构真值;允许的 key 别名逐项列出, +未列出的同义词要人工检查,分数不代表转换精度或真实模型质量。 + +下面的数值评分仍用于既有或手写的 SQL 口径;省略 `--alignments` 可复测这些历史行, +新探索不再生成它们。`--conventions` 仍可为问数写入业务约定,表对齐不据此发明业务规则。 + `mappings.mjs` 量的是探索从数据库 schema 提议的口径,对不对、漏了多少。 ``` diff --git a/scripts/bench/alignment-score.mjs b/scripts/bench/alignment-score.mjs new file mode 100644 index 000000000..62173e357 --- /dev/null +++ b/scripts/bench/alignment-score.mjs @@ -0,0 +1,24 @@ +// 0036 changes the question: score where each column lands, not aggregate SQL. +// Keys are compared against explicit alternatives in the truth file. This is a +// structural score, not a semantic judge or a claim of conversion correctness. +const matches = (got, expected) => (Array.isArray(expected) ? expected : [expected]) + .some((key) => typeof got === "string" && got.toLowerCase() === key.toLowerCase()); + +export function scoreAlignments(proposals, truth) { + const results = []; + for (const table of truth) { + const candidates = proposals.filter((p) => p.payload.draft.table === table.table); + const draft = candidates[0]?.payload.draft; + results.push({ table: table.table, column: null, right: candidates.length === 1 && matches(draft?.class, table.class) }); + for (const expected of table.columns) { + const columns = draft?.columns.filter((c) => c.column === expected.column) ?? []; + const column = columns[0]; + const right = expected.omitted + ? columns.length === 0 && draft?.omitted.some((c) => c.column === expected.column && c.reason.trim()) === true + : columns.length === 1 && matches(column.class, expected.class) && matches(column.property, expected.property) + && (expected.target_class ? matches(column.target_class, expected.target_class) : column.target_class == null && column.expression != null); + results.push({ table: table.table, column: expected.column, right }); + } + } + return { checks: results.length, right: results.filter((r) => r.right).length, missed: results.filter((r) => !r.right) }; +} diff --git a/scripts/bench/alignment-score.test.mjs b/scripts/bench/alignment-score.test.mjs new file mode 100644 index 000000000..f42fd8d54 --- /dev/null +++ b/scripts/bench/alignment-score.test.mjs @@ -0,0 +1,24 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { scoreAlignments } from "./alignment-score.mjs"; + +test("a key misread as a number and a flattened field on the wrong owner lose separate checks", () => { + const truth = [{ table: "dw.orders", class: "order", columns: [ + { column: "buyer_id", class: "order", property: "buyer", target_class: "customer" }, + { column: "tier", class: "customer", property: "tier" }, + { column: "etl", omitted: true }, + ] }]; + const proposals = [{ payload: { draft: { table: "dw.orders", class: "order", columns: [ + { column: "buyer_id", class: "order", property: "buyer", expression: {const: 1} }, + { column: "tier", class: "order", property: "tier", expression: {const: 1} }, + { column: "etl", class: "order", property: "etl", expression: {const: 1} }, + ], omitted: [] } } }]; + assert.equal(scoreAlignments(proposals, truth).right, 1); + proposals[0].payload.draft.columns = [ + { column: "buyer_id", class: "order", property: "buyer", target_class: "customer" }, + { column: "tier", class: "customer", property: "tier", expression: {const: 1} }, + ]; + proposals[0].payload.draft.omitted = [{column: "etl", reason: "bookkeeping"}]; + assert.equal(scoreAlignments(proposals, truth).right, 4); + assert.equal(scoreAlignments([], truth).right, 0); +}); diff --git a/scripts/bench/mappings.mjs b/scripts/bench/mappings.mjs index b2b44ff0c..6d2bed166 100644 --- a/scripts/bench/mappings.mjs +++ b/scripts/bench/mappings.mjs @@ -31,6 +31,7 @@ import { fileURLToPath } from "node:url"; // 迟早漂移,而一旦漂移,「提议对了几条」与「答案对了几条」就不是同一把尺子 // 量出来的(#520) import { api, login, psql, onDb, num, value, same, log, until, sleep, parseArgs } from "./lib.mjs"; +import { scoreAlignments } from "./alignment-score.mjs"; const HERE = path.dirname(fileURLToPath(import.meta.url)); const args = parseArgs(process.argv); @@ -124,7 +125,8 @@ async function fresh() { // 而真正该看见的是「模型密钥解不开」——它第一次失败时就已经写在 last_error 里了 if (err && err !== said) { said = err; log(` 第 ${attempts} 次失败:${err}`); } if (status === "done" || status === "failed") return true; - return num(`SELECT count(*) FROM concept_mappings WHERE kb_id='${kb}'`); + // Wait for the run to finish: an early table is not the complete result. + return false; }, 5000, 600000); return kb; } @@ -240,6 +242,12 @@ function score(kb) { const main = async () => { await login(); const kb = args.kb && args.kb !== true ? args.kb : await fresh(); - score(kb); + if (args.alignments) { + if (!truth.alignment) throw new Error(`No alignment truth for ${corpusName}; use --corpus wide`); + const { items } = await api("GET", `/api/v1/kbs/${kb}/table-alignments`); + console.log(JSON.stringify({ kb, corpus: corpusName, ...scoreAlignments(items, truth.alignment) }, null, 2)); + } else { + score(kb); // Historical SQL definitions still have the #501 numeric score. + } }; main().catch((e) => { console.error(e); process.exit(1); }); diff --git a/scripts/bench/truth/wide.mappings.json b/scripts/bench/truth/wide.mappings.json index 17d2aaea1..756c8ad89 100644 --- a/scripts/bench/truth/wide.mappings.json +++ b/scripts/bench/truth/wide.mappings.json @@ -296,5 +296,151 @@ "as": "both", "why": "when the ETL ran, not when anything happened — a time axis built on it is meaningless" } + ], + "alignment": [ + { + "table": "dw.dwd_ord_dtl", + "class": [ + "order", + "order_line", + "order_item" + ], + "columns": [ + { + "column": "amt_pay", + "class": [ + "order", + "order_line", + "order_item" + ], + "property": [ + "paid_amount", + "paid_price" + ] + }, + { + "column": "qty", + "class": [ + "order", + "order_line", + "order_item" + ], + "property": [ + "quantity", + "qty", + "order_quantity" + ] + }, + { + "column": "ord_st", + "class": [ + "order", + "order_line", + "order_item" + ], + "property": [ + "status", + "order_status" + ] + }, + { + "column": "dt_crt", + "class": [ + "order", + "order_line", + "order_item" + ], + "property": [ + "created_at", + "order_date", + "date_created" + ] + }, + { + "column": "buyer_id", + "class": [ + "order", + "order_line", + "order_item" + ], + "property": [ + "buyer", + "customer", + "ordered_by" + ], + "target_class": [ + "customer", + "person" + ] + }, + { + "column": "shop_id", + "class": [ + "order", + "order_line", + "order_item" + ], + "property": [ + "shop", + "seller", + "sold_by" + ], + "target_class": [ + "shop", + "store" + ] + }, + { + "column": "shop_nm", + "class": [ + "shop", + "store" + ], + "property": [ + "name", + "shop_name" + ] + }, + { + "column": "prov", + "class": [ + "address", + "postal_address" + ], + "property": [ + "province", + "address_region" + ] + }, + { + "column": "buyer_lvl", + "class": [ + "customer", + "person" + ], + "property": [ + "tier", + "customer_tier", + "buyer_level" + ] + }, + { + "column": "ver", + "omitted": true + }, + { + "column": "etl_dt", + "omitted": true + }, + { + "column": "rmk", + "omitted": true + }, + { + "column": "price_old", + "omitted": true + } + ] + } ] } diff --git a/web/src/api.ts b/web/src/api.ts index 614de938c..6b7e4c6c2 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -726,6 +726,51 @@ export interface MappingRevision { changed_by_name: string | null; changed_at: string; } +export interface TableAlignmentProposal { + id: string; + key: string; + status: "open" | "adopted" | "rejected"; + payload: { + version: string; + source_id: string; + source: string; + attribute_ids: Record; + draft: { + table: string; + class: string; + summary: string; + entity_types: { key: string; label: string; description: string; parents: string[] }[]; + attribute_types: AlignmentProperty[]; + relation_types: AlignmentProperty[]; + columns: { column: string; class: string; property: string; target_class: string | null; expression: unknown }[]; + omitted: { column: string; reason: string }[]; + }; + }; +} +export interface AlignmentProperty { + key: string; + label: string; + description: string; + domains: string[]; + ranges: string[]; + datatype: string | null; + unit: string | null; +} +export interface ExplorationRun { + id: string; + started_at: string; + finished_at: string | null; + sources: string[]; + tables_scanned: number; + columns_scanned: number; + schema_truncated: boolean; + cap: number; + returned: number; + accepted: number; + dropped: Record; + tables_covered: string[]; + error: string | null; +} /** 一处公理违规(0002 R0)。判据来自本体自己声明的公理,没声明就不报 */ /** derived_contradiction 独有(0017):推出来的那条三元组——它没有落库, * 只能在这里写出来。其它种类是 `{}` */ @@ -1933,6 +1978,12 @@ export const api = { request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/data-sources/explore`, { method: "POST", }), + tableAlignments: (kbId: string) => + request<{ items: TableAlignmentProposal[]; last_run: ExplorationRun | null }>(`/api/v1/kbs/${kbId}/table-alignments`), + decideTableAlignment: (kbId: string, proposal: TableAlignmentProposal, status: "adopted" | "rejected") => + request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/table-alignments/decision`, { + method: "POST", body: JSON.stringify({ key: proposal.key, version: proposal.payload.version, status }), + }), syncDataSourceSchema: (kbId: string, dsId: string) => request<{ ok: boolean; schema_tables: number }>( `/api/v1/kbs/${kbId}/data-sources/${dsId}/sync-schema`, diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts index 83c780f93..6f5cf092a 100644 --- a/web/src/i18n/en.ts +++ b/web/src/i18n/en.ts @@ -1848,6 +1848,18 @@ export const en = { hint: "Which tables and columns each business concept points at, and how it is computed. Ask answers only from confirmed definitions.", tabDefinitions: "Definitions", tabSources: "Data sources", + tabAlignments: "Table alignments", + alignmentHint: "Review what each table represents, the owner of each column and its conversion. Adopt or reject the whole table. Alignments do not yet generate SQL definitions for Ask.", + alignmentEmpty: "No table alignments in this view. Explore your mounted data sources to propose alignments.", + alignmentAdopted: "Adopted", + alignmentColumn: "Column", + alignmentOwner: "Owner class", + alignmentProperty: "Property", + alignmentConversion: "Conversion / target", + alignmentOmitted: "Left out", + alignmentNewVocabulary: "Vocabulary created on adoption", + alignmentAdopt: "Adopt table", + alignmentReject: "Reject table", filterAll: "All", filterProposed: "Pending", filterConfirmed: "Confirmed", @@ -1859,7 +1871,7 @@ export const en = { prev: "Previous", next: "Next", empty: - "No definitions yet. Mount a data source, then run Explore to have an agent propose a first batch.", + "No definitions yet. Write a definition using the data source's tables and columns.", emptyFiltered: "No definitions match.", rejectedHint: "Rejected ones are listed too — otherwise “why was this concept never mapped?” has no answer.", @@ -1904,9 +1916,9 @@ export const en = { "This is in the alert centre; check the connection, then use Refresh schema.", explore: "Explore mappings", exploreHint: - "An agent reads these schemas and proposes metric and dimension definitions. Proposals land in Pending; Ask uses them only once confirmed.", + "An agent reads these schemas and proposes one alignment per table, reusing the ontology. Review the complete proposals under Table alignments.", exploreQueued: - "Exploration queued — proposals will appear under Pending. If nothing can be proposed, the alert bell will say so.", + "Exploration queued — proposals will appear under Table alignments. If nothing can be proposed, the alert bell will say so.", // **最近一轮探索的账**——单看列表答不了「漏了多少」(#503): // 十二条提议对着八十列的宽表与刚好覆盖完一个小库长得一样。这条贴出来人 // 才能从「等量提议」里看出覆盖范围。 diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts index c804902d1..787913464 100644 --- a/web/src/i18n/zh.ts +++ b/web/src/i18n/zh.ts @@ -1604,6 +1604,18 @@ export const zh: Strings = { hint: "每个业务概念对应库里的哪张表、哪一列,以及怎么算。对话只用已确认的定义作答。", tabDefinitions: "口径", tabSources: "数据源", + tabAlignments: "表对齐", + alignmentHint: "审核表代表的类、每列所属的类及其转换,整表采纳或拒绝。表对齐目前还不会生成问数使用的 SQL 口径。", + alignmentEmpty: "当前视图没有表对齐提案。可在数据源中运行探索来生成提案。", + alignmentAdopted: "已采纳", + alignmentColumn: "列", + alignmentOwner: "所属类", + alignmentProperty: "属性或关系", + alignmentConversion: "转换或目标类", + alignmentOmitted: "不对齐的列", + alignmentNewVocabulary: "采纳时创建的本体元素", + alignmentAdopt: "采纳整表", + alignmentReject: "拒绝整表", filterAll: "全部", filterProposed: "待审批", filterConfirmed: "已确认", @@ -1614,7 +1626,7 @@ export const zh: Strings = { `第 ${from}–${to} 条,共 ${total} 条`, prev: "上一页", next: "下一页", - empty: "还没有口径。挂上数据源后点「探查映射」,让智能体先提一批。", + empty: "还没有口径。可使用数据源中的表和列编写一条口径。", emptyFiltered: "没有符合条件的口径。", rejectedHint: "拒绝过的也列在这里——否则「这个概念为什么没被映射」永远答不上来。", @@ -1658,8 +1670,8 @@ export const zh: Strings = { "检查连接串后点「刷新结构」重试。", explore: "探查映射", exploreHint: - "一个智能体读这些库表结构,提出指标/维度的口径。提出来的落在「待审批」,确认之后问数才会用。", - exploreQueued: "探索已排队,提议会出现在「待确认」里;一条都提不出来时,铃铛会告诉你。", + "智能体读取库表结构,复用已有本体,按整张表提出对齐方案。请在「表对齐」中审核完整提案。", + exploreQueued: "探索已排队,提案会出现在「表对齐」里;一条都提不出来时,铃铛会告诉你。", // **最近一轮探索的账**——光看列表答不了「漏了多少」(#503): // 十二条提议对着八十列的宽表与刚好覆盖完一个小库长得一样。这条贴出来人 // 才能从「等量提议」里看出覆盖范围。 diff --git a/web/src/pages/Mappings.tsx b/web/src/pages/Mappings.tsx index 90496b198..a59bf5f3f 100644 --- a/web/src/pages/Mappings.tsx +++ b/web/src/pages/Mappings.tsx @@ -14,6 +14,7 @@ import { api, type ConceptMapping } from "../api"; import { S } from "../i18n"; import { useKb } from "../kb"; import { toast } from "../toast"; +import { TableAlignments } from "./TableAlignments"; import { Button, Checkbox, @@ -86,7 +87,7 @@ const statusLabel = (s: string) => export function Mappings() { const { kb } = useKb(); const queryClient = useQueryClient(); - const [tab, setTab] = useState<"definitions" | "sources">("definitions"); + const [tab, setTab] = useState<"alignments" | "definitions" | "sources">("alignments"); const [status, setStatus] = useState("all"); const [q, setQ] = useState(""); const [page, setPage] = useState(0); @@ -149,15 +150,15 @@ export function Mappings() { 内容区也从设置页那套居中限宽(max-w-4xl)改成内容页的铺满(px-8 py-6)。 */
@@ -169,7 +170,9 @@ export function Mappings() { className="mb-4" /> - {tab === "sources" ? ( + {tab === "alignments" ? ( + + ) : tab === "sources" ? ( ) : (
diff --git a/web/src/pages/TableAlignments.tsx b/web/src/pages/TableAlignments.tsx new file mode 100644 index 000000000..b0cf862ac --- /dev/null +++ b/web/src/pages/TableAlignments.tsx @@ -0,0 +1,88 @@ +import { useState } from "react"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { Database } from "lucide-react"; +import { api, type TableAlignmentProposal } from "../api"; +import { S } from "../i18n"; +import { toast } from "../toast"; +import { Button, CARD_ACTIONS, Dropdown, EmptyState, ErrorText, Loading, Status, Table, Th, Td } from "../ui"; +import { expressionText } from "./ruleExpressions"; + +export function TableAlignments({ kbId }: { kbId: string }) { + const client = useQueryClient(); + const [status, setStatus] = useState("open"); + const detail = useQuery({ queryKey: ["kb", kbId], queryFn: () => api.kbDetail(kbId) }); + const role = detail.data?.my_role; + const canEdit = role === "editor" || role === "admin" || role === "owner"; + const data = useQuery({ queryKey: ["table-alignments", kbId], queryFn: () => api.tableAlignments(kbId) }); + const decide = useMutation({ + mutationFn: ({ proposal, status }: { proposal: TableAlignmentProposal; status: "adopted" | "rejected" }) => + api.decideTableAlignment(kbId, proposal, status), + onError: (error: Error) => toast.error(error.message), + onSettled: () => { + client.invalidateQueries({ queryKey: ["table-alignments", kbId] }); + client.invalidateQueries({ queryKey: ["ontology", kbId] }); + }, + }); + const items = data.data?.items.filter((p) => status === "all" || p.status === status) ?? []; + const run = data.data?.last_run; + return
+

{S.mapping.alignmentHint}

+ + {run &&

{S.mapping.lastRun({ + tables: run.tables_scanned, columns: run.columns_scanned, + returned: run.returned, accepted: run.accepted, truncated: run.schema_truncated, + })}

} + {data.isError ? {data.error.message} : data.isPending ? {S.nav.loading} : + items.length === 0 ? }>{S.mapping.alignmentEmpty} : + items.map((p) => { + const d = p.payload.draft; + const attributes = Object.entries(p.payload.attribute_ids).map(([key, id]) => ({ + id, key, label: key, + })); + const declarations = [...d.attribute_types, ...d.relation_types]; + return
+
+
+

{d.table} → {d.class}

+

{p.payload.source}

+
+ + {p.status === "open" ? S.mapping.filterProposed : p.status === "adopted" ? S.mapping.alignmentAdopted : S.mapping.filterRejected} + +
+

{d.summary}

+
+ + + {d.columns.map((c) => + + + + )} +
{S.mapping.alignmentColumn}{S.mapping.alignmentOwner}{S.mapping.alignmentProperty}{S.mapping.alignmentConversion}
{c.column}{c.class}{c.property}{c.target_class ? `→ ${c.target_class}` : expressionText(c.expression, attributes, S.mapping.noDefinition)}
+
+ {d.omitted.length > 0 &&
+

{S.mapping.alignmentOmitted}

+
{d.omitted.map((c) =>
{c.column}
{c.reason}
)}
+
} + {(d.entity_types.length > 0 || declarations.length > 0) &&
+

{S.mapping.alignmentNewVocabulary}

+
    {d.entity_types.map((c) =>
  • + {c.label} ({c.key}){c.parents.length > 0 && ` → ${c.parents.join(", ")}`} — {c.description} +
  • )}{declarations.map((p) =>
  • + {p.label} ({p.key}) — {p.domains.join(", ")} → {p.datatype ?? p.ranges.join(", ")}{p.unit && ` (${p.unit})`}: {p.description} +
  • )}
+
} + {p.status === "open" && canEdit &&
+ + +
} +
; + })} +
; +} diff --git a/web/src/queryDefaults.ts b/web/src/queryDefaults.ts index 0a30399b9..aa935443b 100644 --- a/web/src/queryDefaults.ts +++ b/web/src/queryDefaults.ts @@ -34,6 +34,7 @@ export const STREAM_KEYS = [ "pending", "sources", "mappings", + "table-alignments", ] as const; /** 一次会话内不变的键头;换人靠清空缓存 */ export const SESSION_KEYS = ["me", "health", "deployment"] as const; diff --git a/web/src/useKbEvents.ts b/web/src/useKbEvents.ts index 07de914fa..c7726638e 100644 --- a/web/src/useKbEvents.ts +++ b/web/src/useKbEvents.ts @@ -66,7 +66,7 @@ export function useKbEvents(kbId: string | undefined) { document: () => push(["documents", kbId], ["graph"]), graph: () => push(["graph"]), // 映射探索跑完发的也是 review:Pending 那一栏得跟着刷新 - review: () => push(["review", kbId], ["mappings", kbId]), + review: () => push(["review", kbId], ["mappings", kbId], ["table-alignments", kbId]), // 一句记忆抽出了等人点头的事实(0015):对话里那张确认卡跟着长出来 pending: () => push(["pending", kbId], ["review", kbId]), source: () => push(["sources", kbId], ["documents", kbId]),