World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Keep post-0070 provenance references inside the knowledge base (#901) (#938)
Ansonnmad4eb2bcc955
diff --git a/crates/utopia-cli/src/main.rs b/crates/utopia-cli/src/main.rsindex 9f2f490c..1f08263d 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 = 78;+const CURRENT_SCHEMA_VERSION: u32 = 79;fn main() -> anyhow::Result<()> {dotenvy::dotenv().ok();diff --git a/crates/utopia-store/src/export.rs b/crates/utopia-store/src/export.rsindex fd024628..8e688ece 100644--- a/crates/utopia-store/src/export.rs+++ b/crates/utopia-store/src/export.rs@@ -19,7 +19,7 @@//! kb_id 与行本体**原子地一并选出**,校验在内存里跑。不能「先取一页、再去库里//! 问一次」——第二次问的是另一个时刻的状态,留下的行早已不是它。//!-//! 体检范围覆盖 **0070 保护的每一条结构引用边**——不只这份导出真正解析的+//! 体检范围覆盖 **0070/0091 保护的每一条结构引用边**——不只这份导出真正解析的//! 那些。导出还没读的边(规则表自身、陈述属性、时间提及等)也在同一个快照里//! 先查:catalog 守卫(migration_0070_runs_under_any_search_path.rs)核对//! export_provenance_integrity.sql 的每条扫描分支都对应一条受保护的@@ -101,7 +101,7 @@ fn foreign(ref_kb: Option<Uuid>, kb_id: Uuid) -> bool {/// (`unexported`——合并掉的实体)。只报哪条边坏了、坏了几行——具体哪些行/// 坏是库里的事,不进面向导出的报错///-/// 扫的边 = **0070 保护的全部结构引用边**(export_provenance_integrity.sql,+/// 扫的边 = **0070/0091 保护的全部结构引用边**(export_provenance_integrity.sql,/// 每条分支带一条 `@edge`/`@filter` 标记给 catalog 守卫核对)——连导出尚未/// 序列化的边也算:一份账本上任何一条受保护的同库引用断了,这份导出都不可信,/// 宁可整份拒。**必须在导出用的那条事务里跑**(REPEATABLE READ):diff --git a/crates/utopia-store/src/export_provenance_integrity.sql b/crates/utopia-store/src/export_provenance_integrity.sqlindex 5306dbe0..03c34517 100644--- a/crates/utopia-store/src/export_provenance_integrity.sql+++ b/crates/utopia-store/src/export_provenance_integrity.sql@@ -1,6 +1,6 @@-- 导出前的出处体检(export::provenance_integrity 的唯一查询)。----- 覆盖面 = 0070 保护的全部结构引用边:catalog 守卫+-- 覆盖面 = 0070/0091 保护的全部结构引用边:catalog 守卫-- (migration_0070_runs_under_any_search_path.rs)从 pg_catalog 数出每一条-- 受保护的列级引用,再回来核对这份文件里的扫描分支——一边漏登记都是 CI 红。-- 所以每条边不是「导出会解析才查」,而是「schema 保护了就必须在发出第一个@@ -302,4 +302,129 @@ SELECT edge, kind, COUNT(*) AS rows FROM (FROM phrase_bindings bLEFT JOIN relation_types r ON r.id = b.relation_type_idWHERE b.kb_id = $1 AND b.relation_type_id IS NOT NULL+ UNION ALL+ -- @edge attribute_rules.join_predicate_id -> relation_types.id+ -- 0071 出生就有复合键,但体检一直没跟到+ SELECT 'arule.join_predicate', 'cross_kb', p.kb_id IS DISTINCT FROM a.kb_id+ FROM attribute_rules a+ LEFT JOIN relation_types p ON p.id = a.join_predicate_id+ WHERE a.kb_id = $1 AND a.join_predicate_id IS NOT NULL+ UNION ALL+ -- @edge implication_rules.subject_type_id -> entity_types.id+ -- 蕴含规则本体:签名两端的类与结论属性都进本库词汇表按 id 查+ SELECT 'irule.subject_type', 'cross_kb', t.kb_id IS DISTINCT FROM r.kb_id+ FROM implication_rules r+ LEFT JOIN entity_types t ON t.id = r.subject_type_id+ WHERE r.kb_id = $1 AND r.subject_type_id IS NOT NULL+ UNION ALL+ -- @edge implication_rules.object_type_id -> entity_types.id+ SELECT 'irule.object_type', 'cross_kb', t.kb_id IS DISTINCT FROM r.kb_id+ FROM implication_rules r+ LEFT JOIN entity_types t ON t.id = r.object_type_id+ WHERE r.kb_id = $1 AND r.object_type_id IS NOT NULL+ UNION ALL+ -- @edge implication_rules.conclude_property_id -> relation_types.id+ SELECT 'irule.conclude_property', 'cross_kb', p.kb_id IS DISTINCT FROM r.kb_id+ FROM implication_rules r+ LEFT JOIN relation_types p ON p.id = r.conclude_property_id+ WHERE r.kb_id = $1+ UNION ALL+ -- @edge phrase_readings.entity_id -> entities.id+ -- 读数缓存:答出的实体喂给蕴含——别库的实体等于把别库语义读进本库+ SELECT 'reading.entity', 'cross_kb', e.kb_id IS DISTINCT FROM pr.kb_id+ FROM phrase_readings pr+ LEFT JOIN entities e ON e.id = pr.entity_id+ WHERE pr.kb_id = $1 AND pr.entity_id IS NOT NULL+ UNION ALL+ -- @edge implied_fact_sources.rule_id -> implication_rules.id+ -- 隐含事实的出处:行自己没有 kb 列,归属按所属 fact 的库判+ SELECT 'implied.rule', 'cross_kb', r.kb_id IS DISTINCT FROM f.kb_id+ FROM implied_fact_sources i+ JOIN facts f ON f.id = i.fact_id+ LEFT JOIN implication_rules r ON r.id = i.rule_id+ WHERE f.kb_id = $1+ UNION ALL+ -- @edge implied_fact_sources.statement_id -> facts.id+ SELECT 'implied.statement', 'cross_kb', s.kb_id IS DISTINCT FROM f.kb_id+ FROM implied_fact_sources i+ JOIN facts f ON f.id = i.fact_id+ LEFT JOIN facts s ON s.id = i.statement_id+ WHERE f.kb_id = $1 AND i.statement_id IS NOT NULL+ UNION ALL+ -- @edge implied_fact_sources.entity_id -> entities.id+ SELECT 'implied.entity', 'cross_kb', e.kb_id IS DISTINCT FROM f.kb_id+ FROM implied_fact_sources i+ JOIN facts f ON f.id = i.fact_id+ LEFT JOIN entities e ON e.id = i.entity_id+ WHERE f.kb_id = $1 AND i.entity_id IS NOT NULL+ UNION ALL+ -- @edge attribute_rule_versions.rule_id -> attribute_rules.id+ -- 定义史:版本行自己有 kb_id,且必须等于所属规则的库+ SELECT 'arversion.rule', 'cross_kb', r.kb_id IS DISTINCT FROM v.kb_id+ FROM attribute_rule_versions v+ LEFT JOIN attribute_rules r ON r.id = v.rule_id+ WHERE v.kb_id = $1+ UNION ALL+ -- @edge derived_facts.attribute_rule_version_id -> attribute_rule_versions.id+ -- 派生记下凭哪一版定义推出:那版定义不许在别库+ SELECT 'derived.attribute_rule_version', 'cross_kb', v.kb_id IS DISTINCT FROM d.kb_id+ FROM derived_facts d+ LEFT JOIN attribute_rule_versions v ON v.id = d.attribute_rule_version_id+ WHERE d.kb_id = $1 AND d.attribute_rule_version_id IS NOT NULL+ UNION ALL+ -- @edge errata_runs.document_id -> documents.id+ -- 勘误账:复审的是本库的文档;撤销键物化每轮都要读+ SELECT 'erratarun.document', 'cross_kb', d.kb_id IS DISTINCT FROM r.kb_id+ FROM errata_runs r+ LEFT JOIN documents d ON d.id = r.document_id+ WHERE r.kb_id = $1+ UNION ALL+ -- @edge errata_actions.run_id -> errata_runs.id+ SELECT 'errata.run', 'cross_kb', r.kb_id IS DISTINCT FROM a.kb_id+ FROM errata_actions a+ LEFT JOIN errata_runs r ON r.id = a.run_id+ WHERE a.kb_id = $1+ UNION ALL+ -- @edge errata_actions.document_id -> documents.id+ SELECT 'errata.document', 'cross_kb', d.kb_id IS DISTINCT FROM a.kb_id+ FROM errata_actions a+ LEFT JOIN documents d ON d.id = a.document_id+ WHERE a.kb_id = $1+ UNION ALL+ -- @edge errata_actions.fact_id -> facts.id+ SELECT 'errata.fact', 'cross_kb', f.kb_id IS DISTINCT FROM a.kb_id+ FROM errata_actions a+ LEFT JOIN facts f ON f.id = a.fact_id+ WHERE a.kb_id = $1 AND a.fact_id IS NOT NULL+ UNION ALL+ -- @edge errata_actions.statement_id -> facts.id+ SELECT 'errata.statement', 'cross_kb', f.kb_id IS DISTINCT FROM a.kb_id+ FROM errata_actions a+ LEFT JOIN facts f ON f.id = a.statement_id+ WHERE a.kb_id = $1 AND a.statement_id IS NOT NULL+ UNION ALL+ -- @edge errata_actions.predicate_id -> relation_types.id+ SELECT 'errata.predicate', 'cross_kb', p.kb_id IS DISTINCT FROM a.kb_id+ FROM errata_actions a+ LEFT JOIN relation_types p ON p.id = a.predicate_id+ WHERE a.kb_id = $1 AND a.predicate_id IS NOT NULL+ UNION ALL+ -- @edge errata_actions.new_fact_id -> facts.id+ SELECT 'errata.new_fact', 'cross_kb', f.kb_id IS DISTINCT FROM a.kb_id+ FROM errata_actions a+ LEFT JOIN facts f ON f.id = a.new_fact_id+ WHERE a.kb_id = $1 AND a.new_fact_id IS NOT NULL+ UNION ALL+ -- @edge name_vectors.fact_id -> facts.id+ -- 名字向量:召回通道按本库事实/实体取——复合键 0080 就装了,体检补上+ SELECT 'namevector.fact', 'cross_kb', f.kb_id IS DISTINCT FROM n.kb_id+ FROM name_vectors n+ LEFT JOIN facts f ON f.id = n.fact_id+ WHERE n.kb_id = $1+ UNION ALL+ -- @edge name_vectors.entity_id -> entities.id+ SELECT 'namevector.entity', 'cross_kb', e.kb_id IS DISTINCT FROM n.kb_id+ FROM name_vectors n+ LEFT JOIN entities e ON e.id = n.entity_id+ WHERE n.kb_id = $1) refs WHERE bad GROUP BY edge, kinddiff --git a/crates/utopia-store/tests/store/exported_references_never_cross_a_kb.rs b/crates/utopia-store/tests/store/exported_references_never_cross_a_kb.rsindex 3f3c3590..281a1c1a 100644--- a/crates/utopia-store/tests/store/exported_references_never_cross_a_kb.rs+++ b/crates/utopia-store/tests/store/exported_references_never_cross_a_kb.rs@@ -35,6 +35,13 @@ struct Fixture {arule_b: Uuid,der_a: Uuid,der_b: Uuid,+ irule_a: Uuid,+ irule_b: Uuid,+ arv_a: Uuid,+ arv_b: Uuid,+ erun_a: Uuid,+ erun_b: Uuid,+ eact_a: Uuid,}/// 两库,每库一套能被引用的零件:文档/段落/实体/事实/谓词/类/公理规则/业务规则/派生@@ -54,6 +61,10 @@ async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {let (rule_a, rule_b) = (Uuid::now_v7(), Uuid::now_v7());let (arule_a, arule_b) = (Uuid::now_v7(), Uuid::now_v7());let (der_a, der_b) = (Uuid::now_v7(), Uuid::now_v7());+ let (irule_a, irule_b) = (Uuid::now_v7(), Uuid::now_v7());+ let (arv_a, arv_b) = (Uuid::now_v7(), Uuid::now_v7());+ let (erun_a, erun_b) = (Uuid::now_v7(), Uuid::now_v7());+ let eact_a = Uuid::now_v7();sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'xkb-ref-test')").bind(org)@@ -181,6 +192,62 @@ async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {.execute(pool).await?;}+ // 0073 之后进库的同库家族成员:蕴含规则、读数缓存、勘误账、定义史——+ // 每库一套,供越库断言取用+ for (id, kb, pred) in [(irule_a, a, rel_a), (irule_b, b, rel_b)] {+ sqlx::query(+ "INSERT INTO implication_rules (id, kb_id, trigger, phrase,+ conclude_property_id, status)+ VALUES ($1, $2, 'phrase', 'p', $3, 'approved')",+ )+ .bind(id)+ .bind(kb)+ .bind(pred)+ .execute(pool)+ .await?;+ }+ for (id, kb, rule) in [(arv_a, a, arule_a), (arv_b, b, arule_b)] {+ sqlx::query(+ "INSERT INTO attribute_rule_versions (id, kb_id, rule_id, seq, definition)+ VALUES ($1, $2, $3, 1, '{}'::jsonb)",+ )+ .bind(id)+ .bind(kb)+ .bind(rule)+ .execute(pool)+ .await?;+ }+ for (id, kb, doc) in [(erun_a, a, doc_a), (erun_b, b, doc_b)] {+ sqlx::query("INSERT INTO errata_runs (id, kb_id, document_id) VALUES ($1, $2, $3)")+ .bind(id)+ .bind(kb)+ .bind(doc)+ .execute(pool)+ .await?;+ }+ for (id, kb, run, doc) in [(eact_a, a, erun_a, doc_a)] {+ sqlx::query(+ "INSERT INTO errata_actions (id, kb_id, run_id, document_id, action, status)+ VALUES ($1, $2, $3, $4, 'keep', 'held')",+ )+ .bind(id)+ .bind(kb)+ .bind(run)+ .bind(doc)+ .execute(pool)+ .await?;+ }+ // 读数缓存没有 id 列——键是 (kb_id, reading, phrase)+ for (kb, ent) in [(a, ent_a), (b, ent_b)] {+ sqlx::query(+ "INSERT INTO phrase_readings (kb_id, reading, phrase, entity_id)+ VALUES ($1, 'nationality', 'r', $2)",+ )+ .bind(kb)+ .bind(ent)+ .execute(pool)+ .await?;+ }Ok(Fixture {org,a,@@ -203,6 +270,13 @@ async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {arule_b,der_a,der_b,+ irule_a,+ irule_b,+ arv_a,+ arv_b,+ erun_a,+ erun_b,+ eact_a,})}@@ -537,6 +611,206 @@ async fn new_cross_kb_writes_are_rejected_on_every_exported_edge() -> anyhow::Re.await;assert!(err.is_err(), "arule.conclude_predicate→foreign 必须被拒");+ // —— #901:0070 之后进库的表也归同一条不变量 ——+ // 蕴含规则本体的三个引用列(复合外键)+ for (col, foreign_id, what) in [+ ("subject_type_id", f.cls_b, "irule.subject_type"),+ ("object_type_id", f.cls_b, "irule.object_type"),+ ] {+ let err = sqlx::query(&format!(+ "INSERT INTO implication_rules (id, kb_id, trigger, phrase,+ conclude_property_id, status, {col})+ VALUES ($1, $2, 'phrase', 'p', $3, 'approved', $4)",+ ))+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.rel_a)+ .bind(foreign_id)+ .execute(&pool)+ .await;+ assert!(err.is_err(), "{what}→foreign 必须被拒");+ }+ let err = sqlx::query(+ "INSERT INTO implication_rules (id, kb_id, trigger, phrase,+ conclude_property_id, status)+ VALUES ($1, $2, 'phrase', 'p', $3, 'approved')",+ )+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.rel_b)+ .execute(&pool)+ .await;+ assert!(err.is_err(), "irule.conclude_property→foreign 必须被拒");++ // 读数缓存答出的实体(复合外键);UPDATE 路径同样拦+ let err = sqlx::query(+ "INSERT INTO phrase_readings (kb_id, reading, phrase, entity_id)+ VALUES ($1, 'nationality', 'x', $2)",+ )+ .bind(f.a)+ .bind(f.ent_b)+ .execute(&pool)+ .await;+ assert!(err.is_err(), "reading.entity→foreign 必须被拒");+ let err =+ sqlx::query("UPDATE phrase_readings SET entity_id = $1 WHERE kb_id = $2 AND phrase = 'r'")+ .bind(f.ent_b)+ .bind(f.a)+ .execute(&pool)+ .await;+ assert!(err.is_err(), "reading.entity 改成别库也必须被拒");++ // 隐含事实的出处(owner-derived 触发器):规则、触发的陈述、触发的实体+ // 都按所属 fact 的库判;CHECK 要求 statement/entity 恰好一个非空+ let err = sqlx::query(+ "INSERT INTO implied_fact_sources (fact_id, rule_id, statement_id)+ VALUES ($1, $2, $3)",+ )+ .bind(f.fact_a)+ .bind(f.irule_b)+ .bind(f.fact_a)+ .execute(&pool)+ .await;+ assert!(err.is_err(), "implied.rule→foreign 必须被拒");+ let err = sqlx::query(+ "INSERT INTO implied_fact_sources (fact_id, rule_id, statement_id)+ VALUES ($1, $2, $3)",+ )+ .bind(f.fact_a)+ .bind(f.irule_a)+ .bind(f.fact_b)+ .execute(&pool)+ .await;+ assert!(err.is_err(), "implied.statement→foreign 必须被拒");+ let err = sqlx::query(+ "INSERT INTO implied_fact_sources (fact_id, rule_id, entity_id)+ VALUES ($1, $2, $3)",+ )+ .bind(f.fact_a)+ .bind(f.irule_a)+ .bind(f.ent_b)+ .execute(&pool)+ .await;+ assert!(err.is_err(), "implied.entity→foreign 必须被拒");+ // UPDATE 路径:先落合法行,再把 rule 改成别库的——UPDATE OF 盯得住+ sqlx::query(+ "INSERT INTO implied_fact_sources (fact_id, rule_id, entity_id)+ VALUES ($1, $2, $3)",+ )+ .bind(f.fact_b)+ .bind(f.irule_b)+ .bind(f.ent_b)+ .execute(&pool)+ .await?;+ let err = sqlx::query("UPDATE implied_fact_sources SET rule_id = $1 WHERE fact_id = $2")+ .bind(f.irule_a)+ .bind(f.fact_b)+ .execute(&pool)+ .await;+ assert!(err.is_err(), "implied.rule 改成别库也必须被拒");++ // 勘误账:run 盯的文档、action 上的六个引用列全是复合外键+ let err = sqlx::query("INSERT INTO errata_runs (id, kb_id, document_id) VALUES ($1, $2, $3)")+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.doc_b)+ .execute(&pool)+ .await;+ assert!(err.is_err(), "erratarun.document→foreign 必须被拒");+ for (col, foreign_id, what) in [+ ("fact_id", f.fact_b, "errata.fact"),+ ("statement_id", f.fact_b, "errata.statement"),+ ("predicate_id", f.rel_b, "errata.predicate"),+ ("new_fact_id", f.fact_b, "errata.new_fact"),+ ] {+ let err = sqlx::query(&format!(+ "INSERT INTO errata_actions (id, kb_id, run_id, document_id, action, status, {col})+ VALUES ($1, $2, $3, $4, 'keep', 'held', $5)",+ ))+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.erun_a)+ .bind(f.doc_a)+ .bind(foreign_id)+ .execute(&pool)+ .await;+ assert!(err.is_err(), "{what}→foreign 必须被拒");+ }+ // run/document 两列走 UPDATE 路径验:把已有 action 挪到别库的+ // run 或文档上,复合外键照样当场拒+ for (col, foreign_id, what) in [+ ("run_id", f.erun_b, "errata.run"),+ ("document_id", f.doc_b, "errata.document"),+ ] {+ let err = sqlx::query(&format!(+ "UPDATE errata_actions SET {col} = $1 WHERE id = $2",+ ))+ .bind(foreign_id)+ .bind(f.eact_a)+ .execute(&pool)+ .await;+ assert!(err.is_err(), "{what} 改成别库也必须被拒");+ }++ // 规则定义史与凭它推出的派生(#913 的表也在面内)+ // superseded 的版本不占「每规则一条 current」的唯一索引——让行只剩+ // 跨库这一个毛病,拒它的才是那条复合外键+ let err = sqlx::query(+ "INSERT INTO attribute_rule_versions (id, kb_id, rule_id, seq, definition,+ superseded_at)+ VALUES ($1, $2, $3, 9, '{}'::jsonb, now())",+ )+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.arule_b)+ .execute(&pool)+ .await;+ assert!(err.is_err(), "arversion.rule→foreign 必须被拒");+ // 派生的「凭哪一版定义推出」不许指别库(identity 键不含规则列,+ // object_value 换个值躲开与已落派生的身份撞车)+ let err = sqlx::query(+ "INSERT INTO derived_facts (id, kb_id, subject_id, predicate_id, object_value,+ attribute_rule_id, attribute_rule_version_id)+ VALUES ($1, $2, $3, $4, '\"v\"'::jsonb, $5, $6)",+ )+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.ent_a)+ .bind(f.rel_a)+ .bind(f.arule_a)+ .bind(f.arv_b)+ .execute(&pool)+ .await;+ assert!(+ err.is_err(),+ "derived.attribute_rule_version→foreign 必须被拒"+ );++ // 0071/0080 出生就带复合键、却一直不在体检里的两条边+ let err = sqlx::query(+ "INSERT INTO attribute_rules (id, kb_id, name, subject_type_id, conclusion,+ conclude_predicate_id, join_predicate_id)+ VALUES ($1, $2, 'ar-r', $3, 'relation', $4, $5)",+ )+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.cls_a)+ .bind(f.rel_a)+ .bind(f.rel_b)+ .execute(&pool)+ .await;+ assert!(err.is_err(), "arule.join_predicate→foreign 必须被拒");+ let err = sqlx::query(+ "INSERT INTO name_vectors (fact_id, kb_id, entity_id, embedding)+ VALUES ($1, $2, $3, '[0]'::vector)",+ )+ .bind(f.fact_b)+ .bind(f.a)+ .bind(f.ent_a)+ .execute(&pool)+ .await;+ assert!(err.is_err(), "namevector.fact→foreign 必须被拒");+// —— kb 过户:把已被引用的行挪到别的库,等于把指着它的行一次全变坏行for (table, id, what) in [("entities", f.ent_a, "entities.kb_id"),@@ -545,6 +819,14 @@ async fn new_cross_kb_writes_are_rejected_on_every_exported_edge() -> anyhow::Re("derived_facts", f.der_a, "derived_facts.kb_id"),("rules", f.rule_a, "rules.kb_id"),("attribute_rules", f.arule_a, "attribute_rules.kb_id"),+ ("implication_rules", f.irule_a, "implication_rules.kb_id"),+ ("errata_runs", f.erun_a, "errata_runs.kb_id"),+ ("errata_actions", f.eact_a, "errata_actions.kb_id"),+ (+ "attribute_rule_versions",+ f.arv_a,+ "attribute_rule_versions.kb_id",+ ),] {let err = sqlx::query(&format!("UPDATE {table} SET kb_id = $2 WHERE id = $1")).bind(id)@@ -553,6 +835,14 @@ async fn new_cross_kb_writes_are_rejected_on_every_exported_edge() -> anyhow::Re.await;assert!(err.is_err(), "{what} 过户必须被拒");}+ // 读数缓存的键不是 id——按 (kb_id, reading, phrase) 挪库同样不许+ let err =+ sqlx::query("UPDATE phrase_readings SET kb_id = $1 WHERE kb_id = $2 AND phrase = 'r'")+ .bind(f.b)+ .bind(f.a)+ .execute(&pool)+ .await;+ assert!(err.is_err(), "phrase_readings.kb_id 过户必须被拒");// —— 防误伤:同库的合法写入照常sqlx::query(@@ -572,6 +862,62 @@ async fn new_cross_kb_writes_are_rejected_on_every_exported_edge() -> anyhow::Re.bind(f.ent_a).execute(&pool).await?;+ // 新家族同库写入也要照常:出处、读数、勘误、定义史、名字向量+ sqlx::query(+ "INSERT INTO implied_fact_sources (fact_id, rule_id, statement_id)+ VALUES ($1, $2, $3)",+ )+ .bind(f.fact_a)+ .bind(f.irule_a)+ .bind(f.fact_a)+ .execute(&pool)+ .await?;+ sqlx::query(+ "INSERT INTO phrase_readings (kb_id, reading, phrase, entity_id)+ VALUES ($1, 'nationality', 'y', $2)",+ )+ .bind(f.a)+ .bind(f.ent_a)+ .execute(&pool)+ .await?;+ sqlx::query(+ "INSERT INTO errata_actions (id, kb_id, run_id, document_id, fact_id,+ statement_id, predicate_id, new_fact_id,+ action, status)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'revise', 'held')",+ )+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.erun_a)+ .bind(f.doc_a)+ .bind(f.fact_a)+ .bind(f.fact_a)+ .bind(f.rel_a)+ .bind(f.fact_a)+ .execute(&pool)+ .await?;+ sqlx::query(+ "INSERT INTO derived_facts (id, kb_id, subject_id, predicate_id, object_value,+ attribute_rule_id, attribute_rule_version_id)+ VALUES ($1, $2, $3, $4, '\"ok\"'::jsonb, $5, $6)",+ )+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.ent_a)+ .bind(f.rel_a)+ .bind(f.arule_a)+ .bind(f.arv_a)+ .execute(&pool)+ .await?;+ sqlx::query(+ "INSERT INTO name_vectors (fact_id, kb_id, entity_id, embedding)+ VALUES ($1, $2, $3, '[0]'::vector)",+ )+ .bind(f.fact_a)+ .bind(f.a)+ .bind(f.ent_a)+ .execute(&pool)+ .await?;cleanup(&pool, &f).await}@@ -872,15 +1218,217 @@ async fn malformed_rows_fail_every_exported_edge_closed() -> anyhow::Result<()>.bind(f.cls_b).execute(&mut *tx).await?;++ // —— #901 新家族的坏行:0091 保护的 15 条新边 + 两条早就带复合键、+ // 却一直没人登记体检的边(join_predicate、name_vectors) ——+ // 蕴含规则本体的三个引用列+ sqlx::query(+ "INSERT INTO implication_rules (id, kb_id, trigger, phrase, conclude_property_id,+ status, subject_type_id)+ VALUES ($1, $2, 'phrase', 'p', $3, 'approved', $4)",+ )+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.rel_a)+ .bind(f.cls_b)+ .execute(&mut *tx)+ .await?;+ sqlx::query(+ "INSERT INTO implication_rules (id, kb_id, trigger, phrase, conclude_property_id,+ status, object_type_id)+ VALUES ($1, $2, 'phrase', 'p', $3, 'approved', $4)",+ )+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.rel_a)+ .bind(f.cls_b)+ .execute(&mut *tx)+ .await?;+ sqlx::query(+ "INSERT INTO implication_rules (id, kb_id, trigger, phrase, conclude_property_id,+ status)+ VALUES ($1, $2, 'phrase', 'p', $3, 'approved')",+ )+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.rel_b)+ .execute(&mut *tx)+ .await?;+ // 读数缓存答了别库的实体+ sqlx::query(+ "INSERT INTO phrase_readings (kb_id, reading, phrase, entity_id)+ VALUES ($1, 'nationality', 'bad', $2)",+ )+ .bind(f.a)+ .bind(f.ent_b)+ .execute(&mut *tx)+ .await?;+ // 隐含事实的出处三种坏法(CHECK:statement/entity 恰好一个;+ // 主键是 (fact_id, rule_id),再落一条同库事实把三行错开)+ sqlx::query(+ "INSERT INTO facts (id, kb_id, subject_id, object_id, confidence)+ VALUES ($1, $2, $3, $3, 0.9)",+ )+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.ent_a)+ .execute(&mut *tx)+ .await?;+ let fact_a2: Uuid = sqlx::query_scalar(+ "SELECT id FROM facts WHERE kb_id = $1 AND id <> $2 ORDER BY id DESC LIMIT 1",+ )+ .bind(f.a)+ .bind(f.fact_a)+ .fetch_one(&mut *tx)+ .await?;+ // 再落一条本库规则:三行各占一个 (fact_id, rule_id) 主键+ let irule_a2 = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO implication_rules (id, kb_id, trigger, phrase,+ conclude_property_id, status)+ VALUES ($1, $2, 'phrase', 'q', $3, 'approved')",+ )+ .bind(irule_a2)+ .bind(f.a)+ .bind(f.rel_a)+ .execute(&mut *tx)+ .await?;+ sqlx::query(+ "INSERT INTO implied_fact_sources (fact_id, rule_id, statement_id)+ VALUES ($1, $2, $3)",+ )+ .bind(f.fact_a)+ .bind(f.irule_b)+ .bind(f.fact_a)+ .execute(&mut *tx)+ .await?;+ sqlx::query(+ "INSERT INTO implied_fact_sources (fact_id, rule_id, statement_id)+ VALUES ($1, $2, $3)",+ )+ .bind(fact_a2)+ .bind(f.irule_a)+ .bind(f.fact_b)+ .execute(&mut *tx)+ .await?;+ sqlx::query(+ "INSERT INTO implied_fact_sources (fact_id, rule_id, entity_id)+ VALUES ($1, $2, $3)",+ )+ .bind(fact_a2)+ .bind(irule_a2)+ .bind(f.ent_b)+ .execute(&mut *tx)+ .await?;+ // 定义史挂到别库规则;派生记下别库的版本(版本行标 superseded,+ // 不与种子里那条 current 撞「每规则一条」的唯一索引)+ sqlx::query(+ "INSERT INTO attribute_rule_versions (id, kb_id, rule_id, seq, definition,+ superseded_at)+ VALUES ($1, $2, $3, 9, '{}'::jsonb, now())",+ )+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.arule_b)+ .execute(&mut *tx)+ .await?;+ sqlx::query(+ "INSERT INTO derived_facts (id, kb_id, subject_id, predicate_id, object_value,+ attribute_rule_id, attribute_rule_version_id)+ VALUES ($1, $2, $3, $4, '\"bad\"'::jsonb, $5, $6)",+ )+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.ent_a)+ .bind(f.rel_a)+ .bind(f.arule_a)+ .bind(f.arv_b)+ .execute(&mut *tx)+ .await?;+ // 勘误账:run 盯别库文档一行;action 上的 run/document 各坏一行,+ // 其余四列塞进同一行+ sqlx::query("INSERT INTO errata_runs (id, kb_id, document_id) VALUES ($1, $2, $3)")+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.doc_b)+ .execute(&mut *tx)+ .await?;+ sqlx::query(+ "INSERT INTO errata_actions (id, kb_id, run_id, document_id, action, status)+ VALUES ($1, $2, $3, $4, 'keep', 'held')",+ )+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.erun_b)+ .bind(f.doc_a)+ .execute(&mut *tx)+ .await?;+ sqlx::query(+ "INSERT INTO errata_actions (id, kb_id, run_id, document_id, action, status)+ VALUES ($1, $2, $3, $4, 'keep', 'held')",+ )+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.erun_a)+ .bind(f.doc_b)+ .execute(&mut *tx)+ .await?;+ sqlx::query(+ "INSERT INTO errata_actions (id, kb_id, run_id, document_id, fact_id,+ statement_id, predicate_id, new_fact_id,+ action, status)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'revise', 'held')",+ )+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.erun_a)+ .bind(f.doc_a)+ .bind(f.fact_b)+ .bind(f.fact_b)+ .bind(f.rel_b)+ .bind(f.fact_b)+ .execute(&mut *tx)+ .await?;+ // relation 形状的 join 谓词指别库;名字向量两头各坏一行+ sqlx::query(+ "INSERT INTO attribute_rules (id, kb_id, name, subject_type_id, conclusion,+ conclude_predicate_id, join_predicate_id)+ VALUES ($1, $2, 'ar-j', $3, 'relation', $4, $5)",+ )+ .bind(Uuid::now_v7())+ .bind(f.a)+ .bind(f.cls_a)+ .bind(f.rel_a)+ .bind(f.rel_b)+ .execute(&mut *tx)+ .await?;+ sqlx::query(+ "INSERT INTO name_vectors (fact_id, kb_id, entity_id, embedding)+ VALUES ($1, $2, $3, '[0]'::vector)",+ )+ .bind(f.fact_b)+ .bind(f.a)+ .bind(f.ent_a)+ .execute(&mut *tx)+ .await?;+ sqlx::query(+ "INSERT INTO name_vectors (fact_id, kb_id, entity_id, embedding)+ VALUES ($1, $2, $3, '[0]'::vector)",+ )+ .bind(f.fact_a)+ .bind(f.a)+ .bind(f.ent_b)+ .execute(&mut *tx)+ .await?;tx.commit().await?;drop(conn);let err = utopia_store::export::provenance_integrity(&mut pool.begin().await?, f.a).await;let msg = format!("{err:?}");assert!(err.is_err(), "库 A 的体检必须拒导");- // 体检覆盖 0070 保护的全部结构边——埋下去的每一类坏行都要被点名,+ // 体检覆盖 0070/0091 保护的全部结构边——埋下去的每一类坏行都要被点名,// 导出还没序列化的边(规则、绑定、时间提及、条件)也一样:受保护的- // 同库引用断在账本上,这份导出就不可信。38 个报错 label 对应 39 条+ // 同库引用断在账本上,这份导出就不可信。57 个报错 label 对应 58 条// 结构边(class.disjoint 的 a_id/b_id 共用一个 label)for edge in ["evidence.chunk",@@ -900,6 +1448,7 @@ async fn malformed_rows_fail_every_exported_edge_closed() -> anyhow::Result<()>"derived.predicate","derived.rule","derived.attribute_rule",+ "derived.attribute_rule_version","entity.type","class.parent","class.disjoint",@@ -912,6 +1461,8 @@ async fn malformed_rows_fail_every_exported_edge_closed() -> anyhow::Result<()>"arule.subject_type","arule.conclude_type","arule.conclude_predicate",+ "arule.join_predicate",+ "arversion.rule","condition.predicate","factsource.statement","squalifier.entity",@@ -921,6 +1472,22 @@ async fn malformed_rows_fail_every_exported_edge_closed() -> anyhow::Result<()>"pbinding.subject_type","pbinding.object_type","pbinding.relation",+ "irule.subject_type",+ "irule.object_type",+ "irule.conclude_property",+ "reading.entity",+ "implied.rule",+ "implied.statement",+ "implied.entity",+ "erratarun.document",+ "errata.run",+ "errata.document",+ "errata.fact",+ "errata.statement",+ "errata.predicate",+ "errata.new_fact",+ "namevector.fact",+ "namevector.entity",] {assert!(msg.contains(edge), "体检该报 {edge}: {msg}");}diff --git a/crates/utopia-store/tests/store/migration_0070_runs_under_any_search_path.rs b/crates/utopia-store/tests/store/migration_0070_runs_under_any_search_path.rsindex 953c7d12..296dece3 100644--- a/crates/utopia-store/tests/store/migration_0070_runs_under_any_search_path.rs+++ b/crates/utopia-store/tests/store/migration_0070_runs_under_any_search_path.rs@@ -1,14 +1,18 @@-//! 0070 的 DDL 不许依赖会话的 search_path:`CREATE FUNCTION`、+//! 不变量家族(0070、0091)的 DDL 不许依赖会话的 search_path:`CREATE FUNCTION`、//! `CREATE TRIGGER ... ON`、`EXECUTE FUNCTION` 全部限定到 `public.*`——//! pg_restore 会把会话 search_path 置空再灌数据,首位被占住的会话也不能//! 把函数建到别的 schema 去。落在别处的触发器等于没有触发器。//!-//! 三种会话下逐个验证:+//! 三种会话下逐个验证(0070 与 0091 各跑一遍)://! - 正常 search_path(默认)→ 装上;//! - `SET LOCAL search_path = ''` → 同样装上,函数落在 public;//! - `SET LOCAL search_path = 'decoy'`(先在首位摆上同名干扰物)→//! 照样装进 public,干扰物一个不被调用。//!+//! 完备性守卫的 scratch 库迁到**当前链尾**,不停在 0070:链停在哪,责任面+//! 就停在哪——0073 之后进库的表对停在 0070 的守卫结构性不可见(#901 的+//! 盲区就是这么来的)。+//!//! 没有 `UTOPIA_DATABASE_URL` 时跳过;设了地址却连不上、或建不了库——**失败**,//! 不是跳过:地址都给了还说「没库」是假话,那个绿色等于这条检查没跑过。@@ -22,11 +26,15 @@ fn admin_url() -> Option<String> {Some(format!("{head}/postgres"))}-/// 按文件顺序跑 ≤ `through` 的迁移,各自一个事务(与 sqlx::migrate 同一形状)-async fn migrate_to(pool: &PgPool, through: i64) -> anyhow::Result<()> {+/// 按文件顺序跑 `after < version <= through` 的迁移,各自一个事务+/// (与 sqlx::migrate 同一形状)+async fn migrate_range(pool: &PgPool, after: i64, through: i64) -> anyhow::Result<()> {let migrator = sqlx::migrate!("../../migrations");let mut conn = pool.acquire().await?;- for m in migrator.iter().filter(|m| m.version <= through) {+ for m in migrator+ .iter()+ .filter(|m| m.version > after && m.version <= through)+ {let mut tx = conn.begin().await?;sqlx::raw_sql(&m.sql).execute(&mut *tx).await?;tx.commit().await?;@@ -34,13 +42,17 @@ async fn migrate_to(pool: &PgPool, through: i64) -> anyhow::Result<()> {Ok(())}-/// 在 `search_path` 为 `path` 的事务里跑 0070 本体-async fn migration_70_under(pool: &PgPool, path: &str) -> Result<(), sqlx::Error> {+async fn migrate_to(pool: &PgPool, through: i64) -> anyhow::Result<()> {+ migrate_range(pool, 0, through).await+}++/// 在 `search_path` 为 `path` 的事务里跑 `version` 那份迁移本体+async fn migration_under(pool: &PgPool, version: i64, path: &str) -> Result<(), sqlx::Error> {let migrator = sqlx::migrate!("../../migrations");let m = migrator.iter()- .find(|m| m.version == 70)- .expect("0070 必须在迁移集里");+ .find(|m| m.version == version)+ .unwrap_or_else(|| panic!("{version} 必须在迁移集里"));let mut conn = pool.acquire().await?;let mut tx = conn.begin().await?;sqlx::query(&format!("SET LOCAL search_path = {path}"))@@ -56,6 +68,10 @@ async fn migration_70_under(pool: &PgPool, path: &str) -> Result<(), sqlx::Error}}+async fn migration_70_under(pool: &PgPool, path: &str) -> Result<(), sqlx::Error> {+ migration_under(pool, 70, path).await+}+/// 隔离库:建 → 迁到 0069 → 返回(库名, 连接池)。/// 跳过只有一种情形:**根本没设** `UTOPIA_DATABASE_URL`。设了地址连不上、/// 建不了库、迁移链跑不动,全都以错误返回——给了地址却拿不到库,这次检查@@ -116,6 +132,28 @@ where}}+/// 完备性守卫的隔离库:scratch 迁到 0069 之后,把链上剩下的全部跑完——+/// 停在 0070 的守卫对后进的表结构性不可见,post-0070 的引用列要靠+/// 「迁到当前链尾」才数得出来。+async fn with_full_chain<Fut>(suffix: &str, f: impl FnOnce(PgPool) -> Fut) -> anyhow::Result<()>+where+ Fut: std::future::Future<Output = anyhow::Result<()>>,+{+ with_scratch(suffix, |pool| async move {+ migrate_range(&pool, 69, i64::MAX).await?;+ f(pool).await+ })+ .await+}++/// 装完 0070 之后把链推进到 0090,再在被测的 search_path 下装 0091。+/// 中间段的 search_path 不属被测面,走默认路径与真实升级同序。+async fn finish_chain_then_91_under(pool: &PgPool, path: &str) -> anyhow::Result<()> {+ migrate_range(pool, 70, 90).await?;+ migration_under(pool, 91, path).await?;+ Ok(())+}+/// 装完后要点名的几件东西:声明式边 26 条复合外键、父行作证边 10 个触发器、/// 库不可过户 12 个触发器、支撑唯一约束 8 条,且所有新函数都在 public schema。/// 同表自指边的提交边界检查由 DEFERRABLE INITIALLY DEFERRED 复合外键承担@@ -206,6 +244,56 @@ async fn assert_installed(pool: &PgPool) -> anyhow::Result<()> {Ok(())}+/// 0091 必须完成的装配:新触发器函数落 public、13 条新复合键、+/// 3 个 `(kb_id,id)` 支撑唯一约束、5 个 kb 不可过户触发器 ++/// implied_fact_sources 的归属推导触发器,一个都不能少。+async fn assert_0091_installed(pool: &PgPool) -> anyhow::Result<()> {+ let fns: i64 = sqlx::query_scalar(+ "SELECT COUNT(*) FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace+ WHERE n.nspname = 'public' AND p.proname = 'implied_source_stays_inside_its_kb'",+ )+ .fetch_one(pool)+ .await?;+ assert_eq!(fns, 1, "触发器函数必须落在 public schema");++ let fks: i64 = sqlx::query_scalar(+ "SELECT COUNT(*) FROM pg_constraint WHERE contype = 'f' AND conname IN (+ 'implication_rules_subject_type_same_kb','implication_rules_object_type_same_kb',+ 'implication_rules_conclude_property_same_kb',+ 'phrase_readings_entity_same_kb',+ 'attribute_rule_versions_rule_same_kb',+ 'derived_facts_attribute_rule_version_same_kb',+ 'errata_runs_document_same_kb',+ 'errata_actions_run_same_kb','errata_actions_document_same_kb',+ 'errata_actions_fact_same_kb','errata_actions_statement_same_kb',+ 'errata_actions_predicate_same_kb','errata_actions_new_fact_same_kb')",+ )+ .fetch_one(pool)+ .await?;+ assert_eq!(fks, 13, "0091 的复合外键要么全在要么全不在");++ let uniques: i64 = sqlx::query_scalar(+ "SELECT COUNT(*) FROM pg_constraint WHERE contype = 'u' AND conname IN (+ 'implication_rules_kb_id_key','attribute_rule_versions_kb_id_key',+ 'errata_runs_kb_id_key')",+ )+ .fetch_one(pool)+ .await?;+ assert_eq!(uniques, 3, "每个新被引表一条 (kb_id, id) 唯一约束");++ let trg: i64 = sqlx::query_scalar(+ "SELECT COUNT(*) FROM pg_trigger WHERE NOT tgisinternal AND tgname IN (+ 'implied_fact_sources_same_kb',+ 'implication_rules_keep_their_kb','phrase_readings_keep_their_kb',+ 'errata_runs_keep_their_kb','errata_actions_keep_their_kb',+ 'attribute_rule_versions_keep_their_kb')",+ )+ .fetch_one(pool)+ .await?;+ assert_eq!(trg, 6, "归属推导与不可过户触发器,一个都不能少");+ Ok(())+}+// =====================================================================// 完备性守卫:0070 的覆盖面不靠「数过的约束名/触发器名」维持——那种数法// 会在有人往账本里加了一条引用列、却没人回来改 0070 的时候保持全绿。@@ -218,6 +306,7 @@ async fn assert_installed(pool: &PgPool) -> anyhow::Result<()> {/// 它的引用边才轮到逐条归类;面外表(审计、暂存、运维)不归这条不变量管。const LEDGER_TABLES: &[&str] = &[// 自带 kb_id 的语义行+ "attribute_rule_versions","attribute_rules","chunks","derived_facts",@@ -225,8 +314,13 @@ const LEDGER_TABLES: &[&str] = &["entities","entity_type_disjoint","entity_types",+ "errata_actions",+ "errata_runs","facts",+ "implication_rules",+ "name_vectors","phrase_bindings",+ "phrase_readings","relation_types","rules","time_mentions",@@ -237,6 +331,7 @@ const LEDGER_TABLES: &[&str] = &["fact_derivations","fact_evidence","fact_qualifiers",+ "implied_fact_sources","relation_type_domains","relation_type_qualifiers","relation_type_ranges",@@ -253,6 +348,7 @@ const OWNER_ROWS: &[(&str, &str, &str)] = &[("fact_derivations", "derived_fact_id", "derived_facts"),("fact_evidence", "fact_id", "facts"),("fact_qualifiers", "fact_id", "facts"),+ ("implied_fact_sources", "fact_id", "facts"),("relation_type_domains","relation_type_id",@@ -301,6 +397,21 @@ const TRIGGER_EDGES: &[(&str, &str, &str)] = &["qualifier_type_id","fact_qualifiers_same_kb",),+ (+ "implied_fact_sources",+ "entity_id",+ "implied_fact_sources_same_kb",+ ),+ (+ "implied_fact_sources",+ "rule_id",+ "implied_fact_sources_same_kb",+ ),+ (+ "implied_fact_sources",+ "statement_id",+ "implied_fact_sources_same_kb",+ ),("relation_type_domains","entity_type_id",@@ -522,15 +633,15 @@ impl Coverage {dump("SURFACE_DRIFT", &self.surface_drift);dump("PREFLIGHT_MISSING", &self.preflight_missing);dump("STALE_PREFLIGHT", &self.stale_preflight);- if self.declarative.len() != 26 {+ if self.declarative.len() != 42 {problems.push_str(&format!(- " DECLARATIVE_EDGES = {} (expected 26)\n",+ " DECLARATIVE_EDGES = {} (expected 42)\n",self.declarative.len()));}- if self.trigger_covered.len() != 13 {+ if self.trigger_covered.len() != 16 {problems.push_str(&format!(- " TRIGGER_EDGES = {} (expected 13)\n",+ " TRIGGER_EDGES = {} (expected 16)\n",self.trigger_covered.len()));}@@ -852,19 +963,17 @@ async fn classify_reference_edges(pool: &PgPool) -> anyhow::Result<Coverage> {#[tokio::test]async fn every_reference_edge_on_the_ledger_is_classified() -> anyhow::Result<()> {- with_scratch("cover", |pool| async move {- migration_70_under(&pool, "public").await?;+ with_full_chain("cover", |pool| async move {classify_reference_edges(&pool).await?.assert_complete()}).await}/// 漂移探针 A:kb 自持行上新增一条单列外键(不配 kb_id)。-/// 「26 个名字还在」挡不住它——catalog 会把它数出来,归不进任何一类。+/// 「名字还在」挡不住它——catalog 会把它数出来,归不进任何一类。#[tokio::test]async fn a_new_reference_on_a_kb_owned_row_fails_the_guard() -> anyhow::Result<()> {- with_scratch("driftd", |pool| async move {- migration_70_under(&pool, "public").await?;+ with_full_chain("driftd", |pool| async move {sqlx::query("ALTER TABLE public.time_mentionsADD COLUMN probe_ref uuid REFERENCES public.relation_types(id)",@@ -888,8 +997,7 @@ async fn a_new_reference_on_a_kb_owned_row_fails_the_guard() -> anyhow::Result<(/// 触发器。「表上有触发器」不许让这条新列显得已被覆盖——登记是列级的。#[tokio::test]async fn a_new_reference_on_an_owner_derived_row_fails_the_guard() -> anyhow::Result<()> {- with_scratch("driftt", |pool| async move {- migration_70_under(&pool, "public").await?;+ with_full_chain("driftt", |pool| async move {sqlx::query("ALTER TABLE public.fact_evidenceADD COLUMN probe_rel uuid REFERENCES public.relation_types(id)",@@ -915,8 +1023,7 @@ async fn a_new_reference_on_an_owner_derived_row_fails_the_guard() -> anyhow::Re/// 报错里点名是哪条结构边#[tokio::test]async fn a_protected_edge_missing_from_preflight_fails_the_guard() -> anyhow::Result<()> {- with_scratch("driftp", |pool| async move {- migration_70_under(&pool, "public").await?;+ with_full_chain("driftp", |pool| async move {sqlx::query("ALTER TABLE public.time_mentionsADD COLUMN probe_ref uuid,@@ -953,8 +1060,8 @@ async fn a_protected_edge_missing_from_preflight_fails_the_guard() -> anyhow::Re#[test]fn the_preflight_check_notices_a_dropped_or_stray_edge() -> anyhow::Result<()> {let surface = preflight_surface()?;- // 同一份文件两个方向各数一次:39 条结构边 + 5 条 merged 过滤检查- assert_eq!(surface.edges.len(), 39, "preflight 必须覆盖全部保护边");+ // 同一份文件两个方向各数一次:58 条结构边 + 5 条 merged 过滤检查+ assert_eq!(surface.edges.len(), 58, "preflight 必须覆盖全部保护边");assert_eq!(surface.filters,[@@ -1015,7 +1122,10 @@ async fn the_migration_installs_under_an_empty_search_path() -> anyhow::Result<(with_scratch("empty", |pool| async move {let r = migration_70_under(&pool, "''").await;assert!(r.is_ok(), "search_path 为空时装得上 0070: {r:?}");- assert_installed(&pool).await+ assert_installed(&pool).await?;+ let r = finish_chain_then_91_under(&pool, "''").await;+ assert!(r.is_ok(), "search_path 为空时装得上 0091: {r:?}");+ assert_0091_installed(&pool).await}).await}@@ -1035,18 +1145,28 @@ async fn the_migration_installs_under_a_hostile_search_path() -> anyhow::Result<).execute(&pool).await?;+ sqlx::query(+ "CREATE FUNCTION decoy.implied_source_stays_inside_its_kb() RETURNS trigger+ LANGUAGE plpgsql AS $$ BEGIN RETURN NULL; END; $$",+ )+ .execute(&pool)+ .await?;let r = migration_70_under(&pool, "decoy, public").await;assert!(r.is_ok(), "首位被占的 search_path 下也装得上 0070: {r:?}");assert_installed(&pool).await?;+ let r = finish_chain_then_91_under(&pool, "decoy, public").await;+ assert!(r.is_ok(), "首位被占的 search_path 下也装得上 0091: {r:?}");+ assert_0091_installed(&pool).await?;// 干扰物原样留着:一次都没被选中let decoy_fn: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace- WHERE n.nspname = 'decoy' AND p.proname = 'kb_ownership_is_not_reassigned'",+ WHERE n.nspname = 'decoy' AND p.proname IN+ ('kb_ownership_is_not_reassigned','implied_source_stays_inside_its_kb')",).fetch_one(&pool).await?;- assert_eq!(decoy_fn, 1, "decoy 函数不该被覆盖也不该被删掉");+ assert_eq!(decoy_fn, 2, "decoy 函数不该被覆盖也不该被删掉");Ok(())}).await@@ -1057,7 +1177,79 @@ async fn the_migration_installs_under_a_normal_search_path() -> anyhow::Result<(with_scratch("norm", |pool| async move {let r = migration_70_under(&pool, "public").await;assert!(r.is_ok(), "正常 search_path 下装得上 0070: {r:?}");- assert_installed(&pool).await+ assert_installed(&pool).await?;+ let r = finish_chain_then_91_under(&pool, "public").await;+ assert!(r.is_ok(), "正常 search_path 下装得上 0091: {r:?}");+ assert_0091_installed(&pool).await+ })+ .await+}++/// 0091 的前置检查:账本上已经躺着越库出处的库,装 0091 必须整份中止——+/// 装上不变量却对已违反它的账本报喜,等于替坏数据背书。中止必须连锅端:+/// 报了哪条边、一行新机制都不许留下。+#[tokio::test]+async fn migration_91_refuses_a_ledger_with_cross_kb_sources() -> anyhow::Result<()> {+ with_scratch("dirty", |pool| async move {+ migration_70_under(&pool, "public").await?;+ migrate_range(&pool, 70, 90).await?;++ // 两库、各一实体/属性/规则/事实;出处行的事实在本库、规则在别库+ sqlx::query(+ "WITH org AS (+ INSERT INTO organizations (id, name) VALUES (gen_random_uuid(), 't')+ RETURNING id+ ), ws AS (+ INSERT INTO workspaces (id, org_id, name)+ SELECT gen_random_uuid(), id, 't' FROM org RETURNING id+ ), kbs AS (+ INSERT INTO knowledge_bases (id, workspace_id, name)+ SELECT gen_random_uuid(), ws.id, 'kb' || i FROM ws, generate_series(1, 2) i+ RETURNING id+ ), a AS (SELECT id FROM kbs ORDER BY id LIMIT 1),+ b AS (SELECT id FROM kbs ORDER BY id OFFSET 1),+ ents AS (+ INSERT INTO entities (id, kb_id, canonical_name)+ SELECT gen_random_uuid(), id, 'e' FROM kbs RETURNING id, kb_id+ ), rels AS (+ INSERT INTO relation_types (id, kb_id, key, label)+ SELECT gen_random_uuid(), id, 'r', 'r' FROM kbs RETURNING id, kb_id+ ), fcts AS (+ INSERT INTO facts (id, kb_id, subject_id, object_id, confidence)+ SELECT gen_random_uuid(), e.kb_id, e.id, e.id, 0.9 FROM ents e+ RETURNING id, kb_id+ ), rules_ AS (+ INSERT INTO implication_rules+ (id, kb_id, trigger, phrase, conclude_property_id, status)+ SELECT gen_random_uuid(), r.kb_id, 'phrase', 'p', r.id, 'approved' FROM rels r+ RETURNING id, kb_id+ )+ -- statement_id 是本库事实(CHECK 要求 statement/entity 恰好一个):+ -- 只坏 rule 那一头,报错的边名才好对+ INSERT INTO implied_fact_sources (fact_id, rule_id, statement_id)+ SELECT f.id, i.id, f.id FROM fcts f, rules_ i+ WHERE f.kb_id = (SELECT id FROM a) AND i.kb_id = (SELECT id FROM b)",+ )+ .execute(&pool)+ .await?;++ let r = migration_under(&pool, 91, "public").await;+ let err = r.expect_err("已有越库出处的账本必须装不上 0091");+ let msg = err.to_string();+ assert!(+ msg.contains("cross-KB references already present") && msg.contains("implied.rule"),+ "报错必须点名是哪条边: {msg}"+ );++ // 中止要干净:一行新机制都不能留+ let leftovers: i64 = sqlx::query_scalar(+ "SELECT COUNT(*) FROM pg_constraint+ WHERE contype = 'f' AND conname LIKE 'implication_rules%_same_kb'",+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(leftovers, 0, "失败的迁移不许留半套装上的机制");+ Ok(())}).await}diff --git a/docs/decisions/0048-provenance-references-stay-inside-the-knowledge-base.md b/docs/decisions/0048-provenance-references-stay-inside-the-knowledge-base.mdindex 22afd977..4a6b5d83 100644--- a/docs/decisions/0048-provenance-references-stay-inside-the-knowledge-base.md+++ b/docs/decisions/0048-provenance-references-stay-inside-the-knowledge-base.md@@ -88,6 +88,8 @@ The medians differ by −4% with fully overlapping ranges — **no measurable wr- 2026-09-23 (#874): the original rationale said replica-mode loading silenced user triggers while declarative foreign-key enforcement stayed active. That was wrong — PostgreSQL foreign keys are enforced by constraint triggers, and `session_replication_role = replica` suppresses those checks as well, so replica mode does not distinguish the two mechanisms. The hybrid stands for the narrower reason recorded above: composite foreign keys are the native, smaller mechanism where the referencing row carries its own `kb_id`, while owner-derived rows cannot express that authority declaratively without a denormalized `kb_id` and a second invariant keeping it equal. The same correction is why the export-side scan covers all 39 edges rather than only the trigger-covered ones. Migration 0070's own header still carries the earlier wording — an applied SQLx migration is checksum-addressed and stays byte-stable, so the corrected operational rule lives here rather than in an edit to that file: replica-mode loading can bypass user triggers and FK constraint-trigger checks alike, and export preflight is the post-load backstop.+- 2026-09-26 (#901): the family was pinned to migration 0070's table list, so every KB-owned table created afterwards escaped it — the catalog guard's scratch database stopped at 0070 and could not see post-0070 tables at all. Migration 0091 extends the same mechanisms to the post-0070 tables: composite same-KB foreign keys on `implication_rules`, `phrase_readings`, `errata_runs`, `errata_actions`, `attribute_rule_versions`, `derived_facts.attribute_rule_version_id`; an owner-derived trigger on `implied_fact_sources` (whose KB authority is the parent fact's `kb_id`); `UNIQUE (kb_id, id)` support on `implication_rules`, `attribute_rule_versions`, `errata_runs`; and `keep_their_kb` immutability on the five new KB-owned tables (`name_vectors` already carried it). `name_vectors`' two pre-existing composite edges and `attribute_rules.join_predicate_id` were also missing from the registered surface and export preflight — registry and scan now cover them. The catalog guard's scratch database now migrates through the current chain end, so future tables cannot become structurally invisible to the guard again.+## Open questions- Whether the eight supporting `UNIQUE (kb_id, id)` indexes should be partial indexes over live rows instead; measured cost does not currently justify the extra subtlety.diff --git a/migrations/0091_the_rule_surface_never_points_across_a_knowledge_base.sql b/migrations/0091_the_rule_surface_never_points_across_a_knowledge_base.sqlnew file mode 100644index 00000000..f894cc37--- /dev/null+++ b/migrations/0091_the_rule_surface_never_points_across_a_knowledge_base.sql@@ -0,0 +1,304 @@+-- 同一条不变量,补到 0070 之后才进库的表上(#901)。+--+-- 0070 把「出处与归属语义上的每一个引用,两端必须同属一个库」装上了当时的+-- 语义账本。但 catalog 守卫的 scratch 库只迁到 0070——之后进库的表对守卫+-- 结构性不可见,「新引用列不归档」这道关门在表粒度上又重演了一遍(与 #846+-- 修掉的列粒度盲区同形)。本次把整圈 post-0070 的库属表按责任分一遍类,+-- 该进同库家族的进家族:+--+-- implication_rules (0073) 规则本体:subject_type_id/object_type_id →+-- entity_types、conclude_property_id → relation_types+-- 全是单列外键;kb_id 也不在不可过户名单里——改 kb_id+-- 会把指着它的来源行一次全脱锚+-- phrase_readings (0073) 读数缓存:entity_id → entities 单列外键;+-- 别库的实体答案会把别库语义喂进本库的蕴含+-- implied_fact_sources (0073) 隐含事实的出处:rule_id → implication_rules、+-- statement_id → facts、entity_id → entities 三条单列+-- 外键;行自己没有 kb 列,归属按所属 fact 的库判——+-- 与 typed_fact_sources 同一个形状,走同一条路+-- errata_runs /+-- errata_actions (0074) 勘误账:run/document/fact/statement/+-- predicate/new_fact 六条引用全是单列外键。+-- (statement_id, predicate_id) 这对撤销键物化每轮+-- 都要读——越库的行是一条永远不兑现的死引用+-- attribute_rule_versions (0076) 规则定义史:rule_id → attribute_rules+-- 单列外键;derived_facts.attribute_rule_version_id+-- 同。派生记下「凭哪一版定义推出」,那版定义不许在别库+-- name_vectors (0080) 出生就带复合键与不可过户触发器,但一直没登记+-- ——「机制装上了、责任面没认它」也是漂移,这里归档+-- attribute_rules.join_predicate_id (0071) 出生就有复合外键,同样缺体检+-- 分支——这次一并补齐+--+-- 机制沿用 0070 的同一套分法,不加新东西:+-- §1b 行自己带 kb_id 的边 → 复合外键 `(kb_id, ref) REFERENCES t (kb_id,+-- id)`,共 13 条新边(errata_actions.new_fact_id 的 ON DELETE SET NULL+-- 照旧限定到引用列——复合键的 SET NULL 会把 kb_id 一起置空)。+-- §1c implied_fact_sources 没有 kb 列、归属由所属 fact 作证 → 与+-- typed_fact_sources 同款 owner-derived 触发器,三条引用一次判。+-- §2 五张新的 kb 自持表补 `keep_their_kb`(name_vectors 出生就有)。+-- §1a 被引表 implication_rules / attribute_rule_versions / errata_runs+-- 各补一条 `UNIQUE (kb_id, id)`——同库家族里被引表的标配支撑。+--+-- §0 前置检查照 0070 的规矩:先数存量越界行(含绕过触发器恢复进来的+-- 悬空引用——LEFT JOIN 落空与越库同罪),有就整份中止并报出是哪条边、+-- 坏了几行。装上不变量却对已违反它的账本报喜,等于替坏数据背书;+-- 这段查询同时是运维审计,升级前在真实库上跑一遍就知道会不会半截停。+--+-- 函数体一律 `SET search_path = pg_catalog`、标识符一律 `public.*` 限定:+-- pg_restore 会把会话 search_path 置空再灌数据,裸名解析不到任何东西;+-- 首位被恶意 schema 占住的会话也不能把函数建错地方。+--+-- =====================================================================+-- §0 前置检查:新覆盖的 16 条边上,存量越界/悬空行 → 整份中止+-- =====================================================================+DO $$+DECLARE+ report text;+BEGIN+ SELECT string_agg(edge || ' x' || n, '; ' ORDER BY edge) INTO report+ FROM (+ SELECT edge, COUNT(*) AS n FROM (+ -- 隐含事实的出处:行自己没有 kb 列,归属按所属 fact 的库判+ SELECT 'implied.rule' AS edge, f.kb_id AS owner_kb, r.kb_id AS ref_kb+ FROM public.implied_fact_sources i+ JOIN public.facts f ON f.id = i.fact_id+ LEFT JOIN public.implication_rules r ON r.id = i.rule_id+ UNION ALL+ SELECT 'implied.statement', f.kb_id, s.kb_id+ FROM public.implied_fact_sources i+ JOIN public.facts f ON f.id = i.fact_id+ LEFT JOIN public.facts s ON s.id = i.statement_id+ WHERE i.statement_id IS NOT NULL+ UNION ALL+ SELECT 'implied.entity', f.kb_id, e.kb_id+ FROM public.implied_fact_sources i+ JOIN public.facts f ON f.id = i.fact_id+ LEFT JOIN public.entities e ON e.id = i.entity_id+ WHERE i.entity_id IS NOT NULL+ UNION ALL+ -- 规则本体与读数缓存:行自己的 kb_id 作证+ SELECT 'irule.subject_type', r.kb_id, t.kb_id+ FROM public.implication_rules r+ LEFT JOIN public.entity_types t ON t.id = r.subject_type_id+ WHERE r.subject_type_id IS NOT NULL+ UNION ALL+ SELECT 'irule.object_type', r.kb_id, t.kb_id+ FROM public.implication_rules r+ LEFT JOIN public.entity_types t ON t.id = r.object_type_id+ WHERE r.object_type_id IS NOT NULL+ UNION ALL+ SELECT 'irule.conclude_property', r.kb_id, p.kb_id+ FROM public.implication_rules r+ LEFT JOIN public.relation_types p ON p.id = r.conclude_property_id+ UNION ALL+ SELECT 'reading.entity', pr.kb_id, e.kb_id+ FROM public.phrase_readings pr+ LEFT JOIN public.entities e ON e.id = pr.entity_id+ WHERE pr.entity_id IS NOT NULL+ UNION ALL+ -- 规则定义史与凭它推出的派生+ SELECT 'arversion.rule', v.kb_id, r.kb_id+ FROM public.attribute_rule_versions v+ LEFT JOIN public.attribute_rules r ON r.id = v.rule_id+ UNION ALL+ SELECT 'derived.attribute_rule_version', d.kb_id, v.kb_id+ FROM public.derived_facts d+ LEFT JOIN public.attribute_rule_versions v+ ON v.id = d.attribute_rule_version_id+ WHERE d.attribute_rule_version_id IS NOT NULL+ UNION ALL+ -- 勘误账+ SELECT 'erratarun.document', r.kb_id, d.kb_id+ FROM public.errata_runs r+ LEFT JOIN public.documents d ON d.id = r.document_id+ UNION ALL+ SELECT 'errata.run', a.kb_id, r.kb_id+ FROM public.errata_actions a+ LEFT JOIN public.errata_runs r ON r.id = a.run_id+ UNION ALL+ SELECT 'errata.document', a.kb_id, d.kb_id+ FROM public.errata_actions a+ LEFT JOIN public.documents d ON d.id = a.document_id+ UNION ALL+ SELECT 'errata.fact', a.kb_id, f.kb_id+ FROM public.errata_actions a+ LEFT JOIN public.facts f ON f.id = a.fact_id+ WHERE a.fact_id IS NOT NULL+ UNION ALL+ SELECT 'errata.statement', a.kb_id, f.kb_id+ FROM public.errata_actions a+ LEFT JOIN public.facts f ON f.id = a.statement_id+ WHERE a.statement_id IS NOT NULL+ UNION ALL+ SELECT 'errata.predicate', a.kb_id, p.kb_id+ FROM public.errata_actions a+ LEFT JOIN public.relation_types p ON p.id = a.predicate_id+ WHERE a.predicate_id IS NOT NULL+ UNION ALL+ SELECT 'errata.new_fact', a.kb_id, f.kb_id+ FROM public.errata_actions a+ LEFT JOIN public.facts f ON f.id = a.new_fact_id+ WHERE a.new_fact_id IS NOT NULL+ ) refs+ WHERE ref_kb IS DISTINCT FROM owner_kb+ GROUP BY edge+ ) bad;+ IF report IS NOT NULL THEN+ RAISE EXCEPTION 'cross-KB references already present (%) — repair the ledger before this invariant can be installed', report+ USING ERRCODE = 'integrity_constraint_violation';+ END IF;+END;+$$;++-- =====================================================================+-- §1a 复合键的支撑唯一约束:每个被引表一个 (kb_id, id)+-- =====================================================================+-- implied_fact_sources.rule_id 由触发器查 implication_rules 的 kb,复合外键+-- 用不上这条唯一约束;补上它是同库家族的标配——被引表一家一个 (kb_id, id),+-- 以后的复合边才有键可指(与 0070 给八张被引表补键同一道理)。+ALTER TABLE public.implication_rules+ ADD CONSTRAINT implication_rules_kb_id_key UNIQUE (kb_id, id);+ALTER TABLE public.attribute_rule_versions+ ADD CONSTRAINT attribute_rule_versions_kb_id_key UNIQUE (kb_id, id);+ALTER TABLE public.errata_runs+ ADD CONSTRAINT errata_runs_kb_id_key UNIQUE (kb_id, id);++-- =====================================================================+-- §1b 声明式边:源行自己带 kb_id 的引用 → 复合外键(13 条)+-- =====================================================================+ALTER TABLE public.implication_rules+ DROP CONSTRAINT implication_rules_subject_type_id_fkey,+ DROP CONSTRAINT implication_rules_object_type_id_fkey,+ DROP CONSTRAINT implication_rules_conclude_property_id_fkey,+ ADD CONSTRAINT implication_rules_subject_type_same_kb+ FOREIGN KEY (kb_id, subject_type_id) REFERENCES public.entity_types (kb_id, id)+ ON DELETE CASCADE,+ ADD CONSTRAINT implication_rules_object_type_same_kb+ FOREIGN KEY (kb_id, object_type_id) REFERENCES public.entity_types (kb_id, id)+ ON DELETE CASCADE,+ ADD CONSTRAINT implication_rules_conclude_property_same_kb+ FOREIGN KEY (kb_id, conclude_property_id) REFERENCES public.relation_types (kb_id, id)+ ON DELETE CASCADE;++ALTER TABLE public.phrase_readings+ DROP CONSTRAINT phrase_readings_entity_id_fkey,+ ADD CONSTRAINT phrase_readings_entity_same_kb+ FOREIGN KEY (kb_id, entity_id) REFERENCES public.entities (kb_id, id)+ ON DELETE CASCADE;++ALTER TABLE public.attribute_rule_versions+ DROP CONSTRAINT attribute_rule_versions_rule_id_fkey,+ ADD CONSTRAINT attribute_rule_versions_rule_same_kb+ FOREIGN KEY (kb_id, rule_id) REFERENCES public.attribute_rules (kb_id, id)+ ON DELETE CASCADE;++ALTER TABLE public.derived_facts+ DROP CONSTRAINT derived_facts_attribute_rule_version_id_fkey,+ ADD CONSTRAINT derived_facts_attribute_rule_version_same_kb+ FOREIGN KEY (kb_id, attribute_rule_version_id)+ REFERENCES public.attribute_rule_versions (kb_id, id)+ ON DELETE CASCADE;++ALTER TABLE public.errata_runs+ DROP CONSTRAINT errata_runs_document_id_fkey,+ ADD CONSTRAINT errata_runs_document_same_kb+ FOREIGN KEY (kb_id, document_id) REFERENCES public.documents (kb_id, id)+ ON DELETE CASCADE;++ALTER TABLE public.errata_actions+ DROP CONSTRAINT errata_actions_run_id_fkey,+ DROP CONSTRAINT errata_actions_document_id_fkey,+ DROP CONSTRAINT errata_actions_fact_id_fkey,+ DROP CONSTRAINT errata_actions_statement_id_fkey,+ DROP CONSTRAINT errata_actions_predicate_id_fkey,+ DROP CONSTRAINT errata_actions_new_fact_id_fkey,+ ADD CONSTRAINT errata_actions_run_same_kb+ FOREIGN KEY (kb_id, run_id) REFERENCES public.errata_runs (kb_id, id)+ ON DELETE CASCADE,+ ADD CONSTRAINT errata_actions_document_same_kb+ FOREIGN KEY (kb_id, document_id) REFERENCES public.documents (kb_id, id)+ ON DELETE CASCADE,+ ADD CONSTRAINT errata_actions_fact_same_kb+ FOREIGN KEY (kb_id, fact_id) REFERENCES public.facts (kb_id, id)+ ON DELETE CASCADE,+ ADD CONSTRAINT errata_actions_statement_same_kb+ FOREIGN KEY (kb_id, statement_id) REFERENCES public.facts (kb_id, id)+ ON DELETE CASCADE,+ ADD CONSTRAINT errata_actions_predicate_same_kb+ FOREIGN KEY (kb_id, predicate_id) REFERENCES public.relation_types (kb_id, id)+ ON DELETE CASCADE,+ -- SET NULL 限定到引用列:不限定会把 kb_id 一起置空(0070 同一条规矩,+ -- PG15+ 的列清单语法)+ ADD CONSTRAINT errata_actions_new_fact_same_kb+ FOREIGN KEY (kb_id, new_fact_id) REFERENCES public.facts (kb_id, id)+ ON DELETE SET NULL (new_fact_id);++-- =====================================================================+-- §1c 触发器边:库归属在所属 fact 手上、引用行没有 kb_id 的 3 条+-- =====================================================================+-- 隐含事实的出处:规则、触发它的陈述、触发它的实体必须与所属 fact 同库——+-- 别库的规则改了状态会隔空作废本库的事实,别库的来源行也可能把本该作废的+-- 事实钉活(materialize 的 sweep 按 rule.kb_id join 查,越库行两头都够不着)。+-- 父行不存在交给外键报错;这里只管「都存在,却不在同一个库」。+CREATE FUNCTION public.implied_source_stays_inside_its_kb() RETURNS trigger+LANGUAGE plpgsql SET search_path = pg_catalog AS $$+DECLARE+ fact_kb uuid;+ ref_kb uuid;+BEGIN+ SELECT kb_id INTO fact_kb FROM public.facts WHERE id = NEW.fact_id;+ IF fact_kb IS NULL THEN+ RETURN NEW;+ END IF;+ SELECT kb_id INTO ref_kb FROM public.implication_rules WHERE id = NEW.rule_id;+ IF ref_kb IS NOT NULL AND ref_kb <> fact_kb THEN+ RAISE EXCEPTION 'implied fact source % cannot name rule % in another knowledge base',+ NEW.fact_id, NEW.rule_id;+ END IF;+ IF NEW.statement_id IS NOT NULL THEN+ SELECT kb_id INTO ref_kb FROM public.facts WHERE id = NEW.statement_id;+ IF ref_kb IS NOT NULL AND ref_kb <> fact_kb THEN+ RAISE EXCEPTION 'implied fact source % cannot name statement % in another knowledge base',+ NEW.fact_id, NEW.statement_id;+ END IF;+ END IF;+ IF NEW.entity_id IS NOT NULL THEN+ SELECT kb_id INTO ref_kb FROM public.entities WHERE id = NEW.entity_id;+ IF ref_kb IS NOT NULL AND ref_kb <> fact_kb THEN+ RAISE EXCEPTION 'implied fact source % cannot name entity % in another knowledge base',+ NEW.fact_id, NEW.entity_id;+ END IF;+ END IF;+ RETURN NEW;+END;+$$;++CREATE TRIGGER implied_fact_sources_same_kb+ BEFORE INSERT OR UPDATE OF fact_id, rule_id, statement_id, entity_id+ ON public.implied_fact_sources+ FOR EACH ROW EXECUTE FUNCTION public.implied_source_stays_inside_its_kb();++-- =====================================================================+-- §2 库归属不可过户:0070 的同一个共享函数,补到五张新 kb 表上+-- =====================================================================+-- 被引行的 kb_id 一动,所有指着它的行一次全脱锚;复合外键只护住被指的行,+-- 不可过户是全量保留的。name_vectors 出生就带着这条,这里不重复装。+CREATE TRIGGER implication_rules_keep_their_kb+ BEFORE UPDATE OF kb_id ON public.implication_rules+ FOR EACH ROW EXECUTE FUNCTION public.kb_ownership_is_not_reassigned();++CREATE TRIGGER phrase_readings_keep_their_kb+ BEFORE UPDATE OF kb_id ON public.phrase_readings+ FOR EACH ROW EXECUTE FUNCTION public.kb_ownership_is_not_reassigned();++CREATE TRIGGER errata_runs_keep_their_kb+ BEFORE UPDATE OF kb_id ON public.errata_runs+ FOR EACH ROW EXECUTE FUNCTION public.kb_ownership_is_not_reassigned();++CREATE TRIGGER errata_actions_keep_their_kb+ BEFORE UPDATE OF kb_id ON public.errata_actions+ FOR EACH ROW EXECUTE FUNCTION public.kb_ownership_is_not_reassigned();++CREATE TRIGGER attribute_rule_versions_keep_their_kb+ BEFORE UPDATE OF kb_id ON public.attribute_rule_versions+ FOR EACH ROW EXECUTE FUNCTION public.kb_ownership_is_not_reassigned();