World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Keep opposite relationship directions distinct in graph paths (#822)
Maya Kidae5ef12de141
diff --git a/crates/utopia-server/src/api/mcp_tests.rs b/crates/utopia-server/src/api/mcp_tests.rsindex 18f269bb..0df41098 100644--- a/crates/utopia-server/src/api/mcp_tests.rs+++ b/crates/utopia-server/src/api/mcp_tests.rs@@ -682,6 +682,83 @@ async fn changes_returns_fact_ids_and_a_reusable_correction_timestamp() -> anyhof.clean().await}+#[tokio::test]+async fn opposite_directions_reach_authenticated_path_output() -> anyhow::Result<()> {+ let Some(f) = Fixture::new().await? else {+ return Ok(());+ };+ async fn check(f: &Fixture) -> anyhow::Result<()> {+ let (a, b, p) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ sqlx::query(+ "INSERT INTO relation_types(id,kb_id,key,label) VALUES ($1,$2,'supplies','supplies')",+ )+ .bind(p)+ .bind(f.kb)+ .execute(&f.state.pool)+ .await?;+ for (id, name) in [(a, "A"), (b, "B")] {+ sqlx::query("INSERT INTO entities(id,kb_id,canonical_name) VALUES ($1,$2,$3)")+ .bind(id)+ .bind(f.kb)+ .bind(name)+ .execute(&f.state.pool)+ .await?;+ }+ for (s, o) in [(a, b), (b, a)] {+ utopia_store::graph::insert_fact(+ &f.state.pool,+ f.kb,+ s,+ Some(p),+ o,+ utopia_store::graph::Validity::starting(+ Some("2026-01-01T00:00:00Z".parse()?),+ Some("day"),+ ),+ 0.9,+ )+ .await?;+ }+ let snapshot_sql = "SELECT jsonb_build_array(+ (SELECT jsonb_agg(to_jsonb(t) ORDER BY id) FROM facts t WHERE kb_id=$1),+ (SELECT jsonb_agg(to_jsonb(t) ORDER BY id) FROM entities t WHERE kb_id=$1),+ (SELECT jsonb_agg(to_jsonb(t) ORDER BY id) FROM relation_types t WHERE kb_id=$1),+ (SELECT jsonb_agg(to_jsonb(t) ORDER BY id) FROM derived_facts t WHERE kb_id=$1),+ (SELECT jsonb_agg(to_jsonb(t) ORDER BY id) FROM rules t WHERE kb_id=$1),+ (SELECT jsonb_agg(to_jsonb(t) ORDER BY id) FROM jobs t WHERE payload->>'kb_id'=$1::text))";+ let before: Value = sqlx::query_scalar(snapshot_sql)+ .bind(f.kb)+ .fetch_one(&f.state.pool)+ .await?;+ for (from, to, left, right) in [+ (a, b, "A —supplies→ B", "A ←supplies— B"),+ (b, a, "B —supplies→ A", "B ←supplies— A"),+ ] {+ let result = f+ .call(+ "paths_between",+ json!({"from":from,"to":to,"max_hops":1,"at":"2026-06-01"}),+ )+ .await?;+ let text = result["content"][0]["text"].as_str().unwrap_or_default();+ anyhow::ensure!(+ text.contains(left) && text.contains(right),+ "opposite path lost: {text}"+ );+ anyhow::ensure!(text.contains("2 paths"), "unexpected path count: {text}");+ }+ let after: Value = sqlx::query_scalar(snapshot_sql)+ .bind(f.kb)+ .fetch_one(&f.state.pool)+ .await?;+ anyhow::ensure!(before == after, "path read changed business data");+ Ok(())+ }+ let result = check(&f).await;+ let cleanup = f.clean().await;+ result.and(cleanup)+}+#[tokio::test]async fn missing_entities_and_empty_graph_reads_keep_their_results() -> anyhow::Result<()> {let Some(f) = Fixture::new().await? else {diff --git a/crates/utopia-store/src/paths.rs b/crates/utopia-store/src/paths.rsindex 648c1fea..23294c05 100644--- a/crates/utopia-store/src/paths.rs+++ b/crates/utopia-store/src/paths.rs@@ -273,9 +273,9 @@ pub async fn paths_between(.then(y.2.partial_cmp(&x.2).unwrap_or(std::cmp::Ordering::Equal))});- // 同一串节点、同一串谓词只回一条:同一条边常有两份事实(一份带日期,一份只有- // 锚点),不去重的话十个名额里有三个是同一条路- let mut seen: HashSet<(Vec<Uuid>, Vec<String>)> = HashSet::new();+ // 同一串节点、同一串有向谓词只回一条:同向的重复观察折叠,但 A → B 和+ // A ← B 不是同一条关系,不能因遍历时两端相同而丢掉一个方向。+ let mut seen = HashSet::new();let mut out = Vec::new();for (_, spec, _, c) in scored {if out.len() >= limits.max_paths {@@ -286,11 +286,17 @@ pub async fn paths_between(let Some(edges) = edges else {continue;};- let predicates: Vec<String> = edges+ let directed_predicates: Vec<_> = edges.iter()- .map(|e| e.predicate.clone().unwrap_or_default())+ .zip(&c.nodes)+ .map(|(e, node)| {+ (+ e.predicate.clone().unwrap_or_default(),+ e.subject_id == *node,+ )+ }).collect();- if !seen.insert((c.nodes.clone(), predicates)) {+ if !seen.insert((c.nodes.clone(), directed_predicates)) {continue;}out.push(Path {diff --git a/crates/utopia-store/tests/a_path_joins_two_entities.rs b/crates/utopia-store/tests/a_path_joins_two_entities.rsindex 4c58c738..36d516ae 100644--- a/crates/utopia-store/tests/a_path_joins_two_entities.rs+++ b/crates/utopia-store/tests/a_path_joins_two_entities.rs@@ -356,3 +356,67 @@ async fn a_path_reads_the_base_as_it_was() -> anyhow::Result<()> {teardown(&pool, &f).await?;run}++#[tokio::test]+async fn opposite_directions_remain_distinct_at_every_hop_count() -> 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 nodes = [Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7()];+ for node in nodes {+ sqlx::query("INSERT INTO entities(id,kb_id,canonical_name,created_at) VALUES ($1,$2,$1::text,'2020-01-01')")+ .bind(node).bind(f.kb).execute(&pool).await?;+ }+ let mut facts = Vec::new();+ for (s, o, year, confidence) in [+ (nodes[0], nodes[1], "2021-01-01T00:00:00Z", 0.9),+ (nodes[0], nodes[1], "2022-01-01T00:00:00Z", 0.7),+ (nodes[1], nodes[0], "2021-01-01T00:00:00Z", 0.8),+ (nodes[1], nodes[2], "2021-01-01T00:00:00Z", 0.9),+ (nodes[2], nodes[3], "2021-01-01T00:00:00Z", 0.9),+ ] {+ facts.push(utopia_store::graph::insert_fact(&pool, f.kb, s, Some(f.partner), o,+ Validity::starting(Some(t(year)), Some("day")), confidence).await?.0);+ }+ sqlx::query("UPDATE facts SET recorded_at='2022-01-01' WHERE id=ANY($1)")+ .bind(&facts).execute(&pool).await?;+ let snapshot_sql = "SELECT jsonb_agg(to_jsonb(f) ORDER BY id) FROM facts f WHERE kb_id=$1";+ let before: serde_json::Value = sqlx::query_scalar(snapshot_sql).bind(f.kb).fetch_one(&pool).await?;+ let at = Some(t("2023-01-01T00:00:00Z"));+ for hops in 1..=3 {+ for (from, to) in [(nodes[0], nodes[hops]), (nodes[hops], nodes[0])] {+ let limits = Limits { max_hops: hops, ..Limits::default() };+ let paths = paths_between(&pool, f.kb, from, to, at, at, limits).await?;+ anyhow::ensure!(paths.len() == 2, "{hops}-hop query lost an opposite direction: {paths:?}");+ let signatures: std::collections::HashSet<_> = paths.iter().map(|p|+ p.edges.iter().map(|e| (e.subject_id, e.object_id)).collect::<Vec<_>>()+ ).collect();+ anyhow::ensure!(signatures.len() == 2, "duplicate direction survived");+ anyhow::ensure!(paths.iter().all(|p| !p.edges.iter().any(|e| e.fact_id == facts[1])),+ "lower-confidence duplicate displaced the preferred observation");+ let capped = paths_between(&pool, f.kb, from, to, at, at,+ Limits { max_paths: 1, ..limits }).await?;+ anyhow::ensure!(capped.len() == 1 && capped[0].edges.iter().map(|e| e.fact_id).collect::<Vec<_>>()+ == paths[0].edges.iter().map(|e| e.fact_id).collect::<Vec<_>>(), "cap/ranking changed");+ anyhow::ensure!(paths_between(&pool, Uuid::now_v7(), from, to, at, at, limits).await?.is_empty(),+ "cross-KB path escaped isolation");+ }+ }+ let after: serde_json::Value = sqlx::query_scalar(snapshot_sql).bind(f.kb).fetch_one(&pool).await?;+ anyhow::ensure!(before == after, "path reads changed facts");+ sqlx::query("UPDATE facts SET invalidated_at='2024-01-01' WHERE id=$1")+ .bind(facts[2]).execute(&pool).await?;+ let historic = paths_between(&pool, f.kb, nodes[0], nodes[1], at, at, Limits::default()).await?;+ let current = paths_between(&pool, f.kb, nodes[0], nodes[1], at,+ Some(t("2025-01-01T00:00:00Z")), Limits::default()).await?;+ anyhow::ensure!(historic.len() == 2 && current.len() == 1, "record-axis retraction changed");+ anyhow::ensure!(paths_between(&pool, f.kb, nodes[0], nodes[1],+ Some(t("2019-01-01T00:00:00Z")), at, Limits::default()).await?.is_empty(), "world-axis filter changed");+ Ok(())+ }.await;+ let cleanup = teardown(&pool, &f).await;+ result.and(cleanup)+}