Elffuss BraidHub

kikocis/utopia public

dev · 13.9 KiBRawPermalink
1//! 0017:派生撞上断言时,让路这件事从静默变成可见。
2//!
3//! `ceo_of ⊑ works_at`,`works_at` functional。Mira `ceo_of` Acme 推出 Mira `works_at`
4//! Acme,而账本里说她 `works_at` Globex。这里守四件事:
5//!
6//! 1. **派生不落地,而队列里有一行。** `run` 记一条 `derived_contradiction`,left 是被撞
7//! 的断言,right 是最后一条前提,detail 写着推出来的三元组;`materialize` 拦下它。
8//! 2. **修了就落。** 给旧断言一个结束日期,派生的区间与它不再重叠,下一轮落地,
9//! 队列里那一行随之清掉。
10//! 3. **认可就落。** 人说两边都对,`accepted` 之后派生照常落地,那一行留着不再报。
11//! 4. **派生之间互撞按规则对聚合。** 两个 ceo 推出两条互斥的 works_at,进
12//! `ontology_defects` 一行 `rules_disagree`,两条派生都不落。
13//!
14//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。
15
16use sqlx::PgPool;
17use utopia_store::reasoning;
18use uuid::Uuid;
19
20struct Fixture {
21 org: Uuid,
22 user: Uuid,
23 kb: Uuid,
24 ceo_of: Uuid,
25 works_at: Uuid,
26 mira: Uuid,
27 acme: Uuid,
28 globex: Uuid,
29 initech: Uuid,
30}
31
32async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {
33 let (org, ws, kb, user) = (
34 Uuid::now_v7(),
35 Uuid::now_v7(),
36 Uuid::now_v7(),
37 Uuid::now_v7(),
38 );
39 let etype = Uuid::now_v7();
40 let (ceo_of, works_at) = (Uuid::now_v7(), Uuid::now_v7());
41 let (mira, acme, globex, initech) = (
42 Uuid::now_v7(),
43 Uuid::now_v7(),
44 Uuid::now_v7(),
45 Uuid::now_v7(),
46 );
47
48 sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'contradiction-test')")
49 .bind(org)
50 .execute(pool)
51 .await?;
52 sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'contradiction-test')")
53 .bind(ws)
54 .bind(org)
55 .execute(pool)
56 .await?;
57 sqlx::query(
58 "INSERT INTO users (id, org_id, email, display_name, password_hash)
59 VALUES ($1, $2, $1 || '@contradiction.test', 'c', 'x')",
60 )
61 .bind(user)
62 .bind(org)
63 .execute(pool)
64 .await?;
65 sqlx::query(
66 "INSERT INTO knowledge_bases (id, workspace_id, name, materialize_inferences)
67 VALUES ($1, $2, 'contradiction-test', TRUE)",
68 )
69 .bind(kb)
70 .bind(ws)
71 .execute(pool)
72 .await?;
73 sqlx::query(
74 "INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, 'thing', 'Thing')",
75 )
76 .bind(etype)
77 .bind(kb)
78 .execute(pool)
79 .await?;
80 sqlx::query(
81 "INSERT INTO relation_types (id, kb_id, key, label, functional)
82 VALUES ($1, $2, 'works_at', 'works at', TRUE)",
83 )
84 .bind(works_at)
85 .bind(kb)
86 .execute(pool)
87 .await?;
88 sqlx::query(
89 "INSERT INTO relation_types (id, kb_id, key, label, sub_property_of)
90 VALUES ($1, $2, 'ceo_of', 'CEO of', $3)",
91 )
92 .bind(ceo_of)
93 .bind(kb)
94 .bind(works_at)
95 .execute(pool)
96 .await?;
97 for (id, name) in [
98 (mira, "Mira"),
99 (acme, "Acme"),
100 (globex, "Globex"),
101 (initech, "Initech"),
102 ] {
103 sqlx::query(
104 "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",
105 )
106 .bind(id)
107 .bind(kb)
108 .bind(etype)
109 .bind(name)
110 .execute(pool)
111 .await?;
112 }
113 Ok(Fixture {
114 org,
115 user,
116 kb,
117 ceo_of,
118 works_at,
119 mira,
120 acme,
121 globex,
122 initech,
123 })
124}
125
126async fn asserted(
127 pool: &PgPool,
128 f: &Fixture,
129 subject: Uuid,
130 predicate: Uuid,
131 object: Uuid,
132 from: Option<&str>,
133) -> anyhow::Result<Uuid> {
134 let id = Uuid::now_v7();
135 sqlx::query(
136 "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, confidence,
137 valid_from, valid_from_precision)
138 VALUES ($1, $2, $3, $4, $5, 0.9, $6::timestamptz, CASE WHEN $6 IS NULL THEN NULL ELSE 'day' END)",
139 )
140 .bind(id)
141 .bind(f.kb)
142 .bind(subject)
143 .bind(predicate)
144 .bind(object)
145 .bind(from)
146 .execute(pool)
147 .await?;
148 Ok(id)
149}
150
151async fn live_derived(pool: &PgPool, f: &Fixture) -> anyhow::Result<Vec<(Uuid, Uuid)>> {
152 Ok(sqlx::query_as(
153 "SELECT subject_id, object_id FROM derived_facts
154 WHERE kb_id = $1 AND invalidated_at IS NULL ORDER BY subject_id, object_id",
155 )
156 .bind(f.kb)
157 .fetch_all(pool)
158 .await?)
159}
160
161async fn open_contradictions(
162 pool: &PgPool,
163 f: &Fixture,
164) -> anyhow::Result<Vec<(Uuid, Uuid, serde_json::Value)>> {
165 Ok(sqlx::query_as(
166 "SELECT id, left_fact, detail FROM axiom_violations
167 WHERE kb_id = $1 AND kind = 'derived_contradiction' AND status = 'open'",
168 )
169 .bind(f.kb)
170 .fetch_all(pool)
171 .await?)
172}
173
174#[tokio::test]
175async fn a_contradiction_points_upstream() -> anyhow::Result<()> {
176 let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {
177 eprintln!("跳过:未设 UTOPIA_DATABASE_URL");
178 return Ok(());
179 };
180 let pool = PgPool::connect(&url).await?;
181 let f = seed(&pool).await?;
182
183 let run = async {
184 // Mira works_at Globex(没写结束日期);Mira ceo_of Acme 自 2024 起
185 let old = asserted(&pool, &f, f.mira, f.works_at, f.globex, Some("2020-01-01")).await?;
186 let ceo = asserted(&pool, &f, f.mira, f.ceo_of, f.acme, Some("2024-01-01")).await?;
187
188 // 1. 派生不落地,队列里有一行
189 let m = reasoning::materialize(&pool, f.kb).await?;
190 assert_eq!(m.derived, 1);
191 assert_eq!(
192 m.blocked, 1,
193 "the derivation that hits an assertion stays out"
194 );
195 assert_eq!(m.inserted, 0);
196 assert!(live_derived(&pool, &f).await?.is_empty());
197
198 let r = reasoning::run(&pool, f.kb).await?;
199 assert_eq!(r.contradictions, 1);
200 assert_eq!(r.rules_disagree, 0);
201 let rows = open_contradictions(&pool, &f).await?;
202 assert_eq!(rows.len(), 1);
203 let (vid, left, detail) = &rows[0];
204 assert_eq!(*left, old, "left is the assertion that was hit");
205 assert_eq!(detail["axiom"], "functional");
206 assert_eq!(detail["rule"], "sub_property");
207 assert_eq!(detail["subject"], "Mira");
208 assert_eq!(detail["predicate"], "works at");
209 assert_eq!(detail["object"], "Acme");
210 assert_eq!(detail["via_label"], "CEO of");
211 assert_eq!(detail["premises"][0], serde_json::json!(ceo));
212 let (right,): (Uuid,) =
213 sqlx::query_as("SELECT right_fact FROM axiom_violations WHERE id = $1")
214 .bind(vid)
215 .fetch_one(&pool)
216 .await?;
217 assert_eq!(right, ceo, "right is the last premise");
218
219 // Review 给的线索:旧断言没写结束日期、派生起得更晚 → stale
220 let page = reasoning::open_violations(&pool, f.kb, 50, 0).await?;
221 let card = page
222 .iter()
223 .find(|v| v.id == *vid)
224 .expect("card on the page");
225 assert_eq!(card.hint.as_deref(), Some("stale"));
226 assert_eq!(card.detail["subject"], "Mira");
227
228 // 争议在它坐的地方可见(0017 §3):面板行挂 contested,图上有一条幽灵边,
229 // 「没落地的」一档有一行,它的证明链读得出前提
230 let (_, facts) = utopia_store::graph::entity_detail(&pool, f.kb, f.mira).await?;
231 let hit = facts
232 .iter()
233 .find(|x| x.id == old)
234 .expect("the assertion is on the panel");
235 let c = hit
236 .contested
237 .as_ref()
238 .expect("the hit assertion is contested");
239 assert_eq!(c["kind"], "derived_contradiction");
240 assert_eq!(c["ref_id"], serde_json::json!(vid));
241 assert!(
242 facts
243 .iter()
244 .find(|x| x.id == ceo)
245 .unwrap()
246 .contested
247 .is_none(),
248 "the premise is not the disputed one"
249 );
250 let (_, edges) = utopia_store::graph::neighborhood(&pool, f.kb, f.mira, 1, None).await?;
251 let ghost = edges
252 .iter()
253 .find(|e| e.blocked)
254 .expect("a ghost edge for the blocked derivation");
255 assert_eq!(ghost.id, *vid);
256 assert!(ghost.derived && ghost.contested);
257 assert_eq!((ghost.source, ghost.target), (f.mira, f.acme));
258 assert!(edges.iter().find(|e| e.id == old).unwrap().contested);
259 assert!(!edges.iter().find(|e| e.id == ceo).unwrap().contested);
260 let blocked = reasoning::blocked_for_entity(&pool, f.kb, f.acme).await?;
261 assert_eq!(blocked.len(), 1);
262 assert_eq!(blocked[0].violation_id, *vid);
263 assert_eq!(blocked[0].against_fact, old);
264 assert_eq!(blocked[0].premises, vec![ceo]);
265 let steps = reasoning::blocked_proof(&pool, f.kb, *vid)
266 .await?
267 .expect("the ghost has a proof");
268 assert_eq!(steps.len(), 1);
269 assert_eq!(steps[0].fact_id, ceo);
270
271 // 重跑幂等:还是那一行
272 reasoning::run(&pool, f.kb).await?;
273 assert_eq!(open_contradictions(&pool, &f).await?.len(), 1);
274
275 // 2. 修了就落:给旧断言一个结束日期,区间不再重叠
276 sqlx::query(
277 "UPDATE facts SET valid_to = '2023-06-30'::timestamptz, valid_to_precision = 'day'
278 WHERE id = $1",
279 )
280 .bind(old)
281 .execute(&pool)
282 .await?;
283 let m = reasoning::materialize(&pool, f.kb).await?;
284 assert_eq!(m.blocked, 0);
285 assert_eq!(
286 m.inserted, 1,
287 "once the assertion ends, the derivation lands"
288 );
289 assert_eq!(live_derived(&pool, &f).await?, vec![(f.mira, f.acme)]);
290 reasoning::run(&pool, f.kb).await?;
291 assert!(
292 open_contradictions(&pool, &f).await?.is_empty(),
293 "the queue row clears with the contradiction"
294 );
295
296 // 3. 认可就落:把结束日期拿掉,矛盾回来;人说两边都对,派生照常落地
297 sqlx::query("UPDATE facts SET valid_to = NULL, valid_to_precision = NULL WHERE id = $1")
298 .bind(old)
299 .execute(&pool)
300 .await?;
301 let m = reasoning::materialize(&pool, f.kb).await?;
302 assert_eq!(m.blocked, 1);
303 assert_eq!(m.invalidated, 1, "the landed derivation is withdrawn again");
304 reasoning::run(&pool, f.kb).await?;
305 let rows = open_contradictions(&pool, &f).await?;
306 assert_eq!(rows.len(), 1);
307 reasoning::decide(&pool, f.kb, rows[0].0, "accepted", f.user).await?;
308 let m = reasoning::materialize(&pool, f.kb).await?;
309 assert_eq!(m.blocked, 0, "an accepted pair lands");
310 assert_eq!(live_derived(&pool, &f).await?, vec![(f.mira, f.acme)]);
311 let r = reasoning::run(&pool, f.kb).await?;
312 assert_eq!(r.contradictions, 1, "still counted");
313 assert!(
314 open_contradictions(&pool, &f).await?.is_empty(),
315 "but the accepted row stays resolved and nothing new is opened"
316 );
317
318 // 4. 派生之间互撞:先把旧断言闭合掉,让断言不再参与;再来一个 ceo_of Initech,
319 // 两条 works_at 由同一条规则推出、互斥——按规则对报一次,两条都不落
320 sqlx::query(
321 "UPDATE facts SET valid_to = '2023-06-30'::timestamptz, valid_to_precision = 'day'
322 WHERE id = $1",
323 )
324 .bind(old)
325 .execute(&pool)
326 .await?;
327 let ceo2 = asserted(&pool, &f, f.mira, f.ceo_of, f.initech, Some("2024-01-01")).await?;
328 let m = reasoning::materialize(&pool, f.kb).await?;
329 assert_eq!(m.derived, 2);
330 assert_eq!(m.blocked, 2, "both sides of a rule clash stay out");
331 assert_eq!(m.invalidated, 1, "the one that had landed is withdrawn");
332 assert!(live_derived(&pool, &f).await?.is_empty());
333 let r = reasoning::run(&pool, f.kb).await?;
334 assert_eq!(r.contradictions, 0);
335 assert_eq!(r.rules_disagree, 1);
336 let defects: Vec<(Uuid, Option<Uuid>, serde_json::Value)> = sqlx::query_as(
337 "SELECT subject, other, detail FROM ontology_defects
338 WHERE kb_id = $1 AND kind = 'rules_disagree' AND status = 'open'",
339 )
340 .bind(f.kb)
341 .fetch_all(&pool)
342 .await?;
343 assert_eq!(defects.len(), 1);
344 assert_eq!(defects[0].0, f.ceo_of);
345 assert_eq!(defects[0].1, Some(f.ceo_of));
346 assert_eq!(defects[0].2["count"], 1);
347 assert_eq!(defects[0].2["rules"][0]["axiom"], "functional");
348 assert_eq!(defects[0].2["rules"][0]["rule_a"], "sub_property");
349 assert_eq!(defects[0].2["rules"][0]["via_a"], "CEO of");
350 let page = reasoning::open_defects(&pool, f.kb, 50, 0).await?;
351 let card = page
352 .iter()
353 .find(|d| d.kind == "rules_disagree")
354 .expect("the rule clash is on the page");
355 assert_eq!(card.subject_label.as_deref(), Some("CEO of"));
356 assert_eq!(card.other_label.as_deref(), Some("CEO of"));
357
358 // 撤掉第二个 ceo:规则对的那一行清掉,第一条派生重新落地
359 sqlx::query("UPDATE facts SET invalidated_at = now() WHERE id = $1")
360 .bind(ceo2)
361 .execute(&pool)
362 .await?;
363 reasoning::run(&pool, f.kb).await?;
364 let (n,): (i64,) = sqlx::query_as(
365 "SELECT count(*) FROM ontology_defects
366 WHERE kb_id = $1 AND kind = 'rules_disagree' AND status = 'open'",
367 )
368 .bind(f.kb)
369 .fetch_one(&pool)
370 .await?;
371 assert_eq!(n, 0, "a rule clash clears when its derivations go");
372 let m = reasoning::materialize(&pool, f.kb).await?;
373 assert_eq!(m.blocked, 0);
374 assert_eq!(live_derived(&pool, &f).await?, vec![(f.mira, f.acme)]);
375 anyhow::Ok(())
376 }
377 .await;
378
379 let _ = sqlx::query("DELETE FROM organizations WHERE id = $1")
380 .bind(f.org)
381 .execute(&pool)
382 .await;
383 run
384}