World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
A cycle is keyed by all its facts (#647)
WaylandYangc88b336f8a17
diff --git a/crates/utopia-reason/src/lib.rs b/crates/utopia-reason/src/lib.rsindex 5e7636ca..4dadb759 100644--- a/crates/utopia-reason/src/lib.rs+++ b/crates/utopia-reason/src/lib.rs@@ -286,8 +286,8 @@ fn walk<'a>(// **报之前把环转到规范位置。**环是一个圈,从哪条边开始读都是同一个// 环;可 `left`/`right` 取的是这一次遍历的首尾,而遍历的起点来自// `adj.keys()`——一个 HashMap,顺序每次不同。于是同一个三元环会以- // 三种旋转轮流出现,而 `axiom_violations` 是按- // `(kind, left_fact, right_fact)` 唯一的:换一种旋转就是换一行。+ // 三种旋转轮流出现,而 `axiom_violations` 里环是按整条 `path` 唯一的+ // (0054;之前按首尾两条):换一种旋转就是换一行。//// 后果不是"多一行",是**人的裁决会悄悄失效**:重算删掉的是 open 的// 行,裁过的那行留着,同一个环以新键插成 open,而重开那一支按键匹配,@@ -512,6 +512,37 @@ mod tests {assert_eq!(path.len(), 3);}+ /// **共用首尾两条边的两个环是两个环**(#641)。A→B 起头、X→A 收尾,中间一条走 C、+ /// 一条走 D:两个环的 left 都是 A→B、right 都是 X→A。从前库里按这两列定键,一个+ /// 覆盖另一个;这里钉的是检查器给出的就是两个、路径不同——落库那边按整条 path 定键+ #[test]+ fn two_cycles_sharing_their_ends_are_two_cycles() {+ let edges = [+ e(1, 1, 2),+ e(2, 2, 3),+ e(3, 2, 4),+ e(4, 3, 5),+ e(5, 4, 5),+ e(6, 5, 1),+ ];+ let v: Vec<Violation> = check(+ &edges,+ &with(Axioms {+ transitive: true,+ ..Default::default()+ }),+ )+ .into_iter()+ .filter(|v| v.kind == Kind::Cycle)+ .collect();+ let paths: HashSet<Vec<Uuid>> = v.iter().map(|c| c.path.clone()).collect();+ assert_eq!(+ paths,+ HashSet::from([vec![f(1), f(2), f(4), f(6)], vec![f(1), f(3), f(5), f(6)]])+ );+ assert!(v.iter().all(|c| (c.left, c.right) == (f(1), f(6))));+ }+/// **没声明公理的谓词一条都不查。** 这是整套检查的地基:没有依据就不报矛盾。////// 反过来说也成立——一个没装本体包的库跑出来是零,那是实情不是故障。diff --git a/crates/utopia-store/src/reasoning.rs b/crates/utopia-store/src/reasoning.rsindex 40d18822..26b40473 100644--- a/crates/utopia-store/src/reasoning.rs+++ b/crates/utopia-store/src/reasoning.rs@@ -196,7 +196,7 @@ pub async fn record_signature_breaks(let id: Option<(Uuid,)> = sqlx::query_as("INSERT INTO axiom_violations (id, kb_id, kind, left_fact, right_fact)VALUES ($1, $2, 'signature', $3, $3)- ON CONFLICT (kb_id, kind, left_fact, right_fact) DO NOTHING+ ON CONFLICT (kb_id, kind, left_fact, right_fact) WHERE kind <> 'cycle' DO NOTHINGRETURNING id",).bind(Uuid::now_v7())@@ -319,10 +319,14 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {.unwrap_or_else(|| json!({}));// **证据跟着这一轮走**(#619)。从前这里是 `DO NOTHING`,而除此之外没有任何// 地方写 `path` / `detail`——重开那一支也不写。于是一行只要不被删,它带的- // 证据就永远是**头一次**记下这个键时算出来的那一份:同一个环后来经由另一条- // 中间路径再被算出来,行上写的还是最早那条。重开时更难看,`detected_at`+ // 证据就永远是**头一次**记下这个键时算出来的那一份:同一处派生矛盾后来经由另一组+ // 前提再被算出来,行上写的还是最早那组。重开时更难看,`detected_at`// 换成 now() 而 path 不动,一行上于是一个新时间戳配一份别的轮次的证据。//+ // **环不走首尾两条的键**(#641)。两个环共用最小的那条和收尾那条、中间不同,+ // 从前落在同一个键上,后一个覆盖前一个的 path——那不是「同一个环换了证据」,+ // 是另一个环被吞掉了。环就是它的事实集合,按整条 path 定键(0054)。+ //// 插与更新合成一条语句:从前是插一次再 SELECT 一次,两条语句问的是同一行。// `xmax = 0` 只有真正新插的行才成立——`DO UPDATE` 会让 RETURNING 对更新也// 出一行,不这么分就会把「本来就在」数成「新插的」。@@ -333,24 +337,33 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {// 违规就不该再算出来。又算出来了,承诺就是没兑现,那行回到 open,人再看一次。// `accepted` 是有意并存,重算多少次都沉默(#202)——只要还是认可时那几条。// 互斥的组走到这里说明上面没拦住:同一个键下多了一条,那行也回到 open+ // 两条部分唯一索引各管一类,冲突目标要把索引的 WHERE 原样写出来才推断得到+ let upsert = if *kind == Kind::Cycle {+ "INSERT INTO axiom_violations+ (id, kb_id, kind, left_fact, right_fact, path, detail)+ VALUES ($1, $2, $3, $4, $5, $6, $7)+ ON CONFLICT (kb_id, path) WHERE kind = 'cycle' DO UPDATE+ SET path = EXCLUDED.path, detail = EXCLUDED.detail+ RETURNING id, status, resolution, xmax = 0"+ } else {+ "INSERT INTO axiom_violations+ (id, kb_id, kind, left_fact, right_fact, path, detail)+ VALUES ($1, $2, $3, $4, $5, $6, $7)+ ON CONFLICT (kb_id, kind, left_fact, right_fact) WHERE kind <> 'cycle' DO UPDATE+ SET path = EXCLUDED.path, detail = EXCLUDED.detail+ RETURNING id, status, resolution, xmax = 0"+ };let (keep, status, resolution, is_new): (Uuid, String, Option<String>, bool) =- sqlx::query_as(- "INSERT INTO axiom_violations- (id, kb_id, kind, left_fact, right_fact, path, detail)- VALUES ($1, $2, $3, $4, $5, $6, $7)- ON CONFLICT (kb_id, kind, left_fact, right_fact) DO UPDATE- SET path = EXCLUDED.path, detail = EXCLUDED.detail- RETURNING id, status, resolution, xmax = 0",- )- .bind(Uuid::now_v7())- .bind(kb_id)- .bind(kind.as_str())- .bind(left)- .bind(right)- .bind(path)- .bind(&detail)- .fetch_one(&mut *tx)- .await?;+ sqlx::query_as(upsert)+ .bind(Uuid::now_v7())+ .bind(kb_id)+ .bind(kind.as_str())+ .bind(left)+ .bind(right)+ .bind(path)+ .bind(&detail)+ .fetch_one(&mut *tx)+ .await?;if is_new {report.inserted += 1;}diff --git a/crates/utopia-store/tests/a_cycle_is_keyed_by_all_its_facts.rs b/crates/utopia-store/tests/a_cycle_is_keyed_by_all_its_facts.rsnew file mode 100644index 00000000..8982e557--- /dev/null+++ b/crates/utopia-store/tests/a_cycle_is_keyed_by_all_its_facts.rs@@ -0,0 +1,236 @@+//! 环按整条路径定键(#641),打在真库上。+//!+//! 环的 left 是最小那条事实、right 是转到它起头之后的最后一条。两个环共用这两条、+//! 中间走的不同时,从前在 `(kb_id, kind, left_fact, right_fact)` 上撞成一行:后算出来的+//! 覆盖先算出来的 path,另一个环在 Review 里消失,而留下哪一个取决于遍历顺序。钉四样:+//!+//! 1. **两个环两行**,重跑不插不清、行的 id 不变+//! 2. **裁决各管各的**:认可其中一个,另一个放宽公理后重开——被认可的那一行 path+//! 仍是它自己的环,没有被另一个环的路径盖掉+//! 3. **撤掉只在一个环上的边**,只影响那一个+//! 4. **别的种类照旧按首尾两条**:反对称那一对重跑仍是同一行+//!+//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。++use sqlx::PgPool;+use utopia_store::reasoning;+use uuid::Uuid;++struct Fixture {+ org: Uuid,+ kb: Uuid,+ etype: Uuid,+ user: Uuid,+ /// state + transitive+ part_of: Uuid,+ /// state + asymmetric+ reports_to: Uuid,+}++async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ let (etype, user, part_of, reports_to) = (+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ );+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'cycle-key-test')")+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'cycle-key-test')")+ .bind(ws)+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'cycle-key-test')",+ )+ .bind(kb)+ .bind(ws)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO users (id, org_id, email, password_hash, display_name)+ VALUES ($1, $2, $3, '', 'Cycle Key Reviewer')",+ )+ .bind(user)+ .bind(org)+ .bind(format!("cycle-key-{user}@test.local"))+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, 'thing', 'Thing')",+ )+ .bind(etype)+ .bind(kb)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO relation_types (id, kb_id, key, label, temporal, is_transitive, is_asymmetric)+ VALUES ($1, $2, 'part_of', 'part_of', 'state', TRUE, FALSE),+ ($3, $2, 'reports_to', 'reports_to', 'state', FALSE, TRUE)",+ )+ .bind(part_of)+ .bind(kb)+ .bind(reports_to)+ .execute(pool)+ .await?;+ Ok(Fixture {+ org,+ kb,+ etype,+ user,+ part_of,+ reports_to,+ })+}++async fn entity(pool: &PgPool, f: &Fixture, name: &str) -> anyhow::Result<Uuid> {+ let id = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",+ )+ .bind(id)+ .bind(f.kb)+ .bind(f.etype)+ .bind(name)+ .execute(pool)+ .await?;+ Ok(id)+}++/// 一条从此刻起一直成立的事实:大家同时成立,这里只问形状+async fn fact(pool: &PgPool, f: &Fixture, s: Uuid, p: Uuid, o: Uuid) -> anyhow::Result<Uuid> {+ let id = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id)+ VALUES ($1, $2, $3, $4, $5)",+ )+ .bind(id)+ .bind(f.kb)+ .bind(s)+ .bind(p)+ .bind(o)+ .execute(pool)+ .await?;+ Ok(id)+}++/// 环行:(id, path, status, resolution),按 path 排+async fn cycle_rows(+ pool: &PgPool,+ f: &Fixture,+) -> anyhow::Result<Vec<(Uuid, Vec<Uuid>, String, Option<String>)>> {+ Ok(sqlx::query_as(+ "SELECT id, path, status, resolution FROM axiom_violations+ WHERE kb_id = $1 AND kind = 'cycle' ORDER BY path",+ )+ .bind(f.kb)+ .fetch_all(pool)+ .await?)+}++#[tokio::test]+async fn two_cycles_sharing_their_ends_are_two_rows() -> anyhow::Result<()> {+ let Some(url) = utopia_store::test_db::url() else {+ return Ok(());+ };+ let pool = PgPool::connect(&url).await?;+ let f = seed(&pool).await?;++ let result = async {+ let [a, b, c, d, x] = [+ entity(&pool, &f, "A").await?,+ entity(&pool, &f, "B").await?,+ entity(&pool, &f, "C").await?,+ entity(&pool, &f, "D").await?,+ entity(&pool, &f, "X").await?,+ ];+ // 按 id 先后插:A→B 最小,X→A 收尾最后一条。两个环的首尾都是这两条+ let ab = fact(&pool, &f, a, f.part_of, b).await?;+ let bc = fact(&pool, &f, b, f.part_of, c).await?;+ let bd = fact(&pool, &f, b, f.part_of, d).await?;+ let cx = fact(&pool, &f, c, f.part_of, x).await?;+ let dx = fact(&pool, &f, d, f.part_of, x).await?;+ let xa = fact(&pool, &f, x, f.part_of, a).await?;+ let (via_c, via_d) = (vec![ab, bc, cx, xa], vec![ab, bd, dx, xa]);++ // ---- 一、两个环两行;重跑稳定+ let first = reasoning::run(&pool, f.kb).await?;+ assert_eq!(first.found, 2);+ assert_eq!(first.inserted, 2, "两个环各插一行,不是一行被另一行覆盖");+ let rows = cycle_rows(&pool, &f).await?;+ let paths: Vec<Vec<Uuid>> = rows.iter().map(|r| r.1.clone()).collect();+ assert_eq!(paths, vec![via_c.clone(), via_d.clone()]);+ for _ in 0..3 {+ let again = reasoning::run(&pool, f.kb).await?;+ assert_eq!((again.inserted, again.cleared), (0, 0));+ let ids: Vec<Uuid> = cycle_rows(&pool, &f).await?.iter().map(|r| r.0).collect();+ assert_eq!(+ ids,+ rows.iter().map(|r| r.0).collect::<Vec<_>>(),+ "行不换 id"+ );+ }+ let (id_c, id_d) = (rows[0].0, rows[1].0);++ // ---- 二、裁决各管各的+ reasoning::decide(&pool, f.kb, id_c, "accepted", f.user).await?;+ reasoning::decide(&pool, f.kb, id_d, "axiom_relaxed", f.user).await?;+ let r = reasoning::run(&pool, f.kb).await?;+ assert_eq!(r.reopened, 1, "放宽公理的那个环还在,重开它——只重开它");+ let rows = cycle_rows(&pool, &f).await?;+ assert_eq!(rows.len(), 2);+ assert_eq!(+ (+ rows[0].0,+ &rows[0].1,+ rows[0].2.as_str(),+ rows[0].3.as_deref()+ ),+ (id_c, &via_c, "resolved", Some("accepted")),+ "认可的那一行仍是经 C 的环,没被经 D 的路径盖掉"+ );+ assert_eq!((rows[1].0, rows[1].2.as_str()), (id_d, "open"));++ // ---- 三、撤掉只在经 D 那个环上的 B→D+ reasoning::retract_from_violation(&pool, f.kb, id_d, Some(bd), f.user).await?;+ let r = reasoning::run(&pool, f.kb).await?;+ assert_eq!(+ (r.found, r.reopened, r.inserted),+ (1, 0, 0),+ "只剩经 C 的环,而它认可过"+ );+ let rows = cycle_rows(&pool, &f).await?;+ assert_eq!(rows[0].3.as_deref(), Some("accepted"));+ assert_eq!(rows[1].3.as_deref(), Some("fact_retracted"));++ // ---- 四、别的种类照旧按首尾两条+ let boss = fact(&pool, &f, c, f.reports_to, d).await?;+ let back = fact(&pool, &f, d, f.reports_to, c).await?;+ reasoning::run(&pool, f.kb).await?;+ let again = reasoning::run(&pool, f.kb).await?;+ assert_eq!(again.inserted, 0);+ let pair: Vec<(Uuid, Uuid)> = sqlx::query_as(+ "SELECT left_fact, right_fact FROM axiom_violations+ WHERE kb_id = $1 AND kind = 'asymmetry'",+ )+ .bind(f.kb)+ .fetch_all(&pool)+ .await?;+ assert_eq!(pair, vec![(boss.min(back), boss.max(back))]);+ Ok::<_, anyhow::Error>(())+ }+ .await;+ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")+ .bind(f.kb)+ .execute(&pool)+ .await?;+ sqlx::query("DELETE FROM organizations WHERE id = $1")+ .bind(f.org)+ .execute(&pool)+ .await?;+ result+}diff --git a/migrations/0054_a_cycle_is_keyed_by_all_its_facts.sql b/migrations/0054_a_cycle_is_keyed_by_all_its_facts.sqlnew file mode 100644index 00000000..252dd742--- /dev/null+++ b/migrations/0054_a_cycle_is_keyed_by_all_its_facts.sql@@ -0,0 +1,29 @@+-- 环按整条路径定键(#641)。+--+-- `axiom_violations` 从 0012 起按 `(kb_id, kind, left_fact, right_fact)` 唯一。环的+-- left 是最小的那条事实、right 是转到它起头之后的最后一条(0052)——两个环只要共用+-- 这两条、中间走的不同,就落在同一个键上,后算出来的覆盖先算出来的 `path`。量过:+-- 400 个单位的组织重组库上形状环 572 个,落库 165 行。被吞掉的环在 Review 里看不到,+-- 留下的是哪一条取决于遍历顺序,人裁的那一个可能在下一轮换成了另一个。+--+-- 一个环就是它的事实集合。节点不重复的回路里,集合定下来顺序就定了,转到最小事实+-- 起头之后 `path` 本身就是规范形状,所以环按 `(kb_id, path)` 唯一。别的种类不变:+-- 互斥组的首尾本来就是组的函数(0053),派生矛盾有意把同一处撞法的不同前提算作一处+-- (#619)。++-- 很早记下的环行可能没有 path(path 列是后加的)。首尾两条在 0052 之后是唯一的,+-- 补成它们,免得几行空 path 在新索引上撞在一起+UPDATE axiom_violations+ SET path = ARRAY[left_fact, right_fact]+ WHERE kind = 'cycle' AND cardinality(path) = 0;++ALTER TABLE axiom_violations+ DROP CONSTRAINT axiom_violations_kb_id_kind_left_fact_right_fact_key;++CREATE UNIQUE INDEX axiom_violations_pair_key+ ON axiom_violations (kb_id, kind, left_fact, right_fact)+ WHERE kind <> 'cycle';++CREATE UNIQUE INDEX axiom_violations_cycle_key+ ON axiom_violations (kb_id, path)+ WHERE kind = 'cycle';