Elffuss BraidHub

kikocis/utopia public

ffe9e37e55e3 · 19.3 KiBRawPermalink
1//! 一致性检查:拿本体声明的公理去量已经落库的事实(见 `docs/decisions/0002` R0)。
2//!
3//! **不写 `facts` 表,也不碰数据库。** 这一层只做判断:输入是边与公理,输出是
4//! 「哪几条事实互相矛盾」。取数与落库在 `utopia-store` / `utopia-server`。
5//!
6//! 这样分不是洁癖。ADR 说 R0 的价值在于「引擎的难点——规则表示、求值、终止——
7//! 全部建成并验证,而风险面为零」,而那些难点是纯逻辑:不起数据库就能跑几百个
8//! 用例,包括那些真实语料里未必凑得出来的形状(十一个节点的环、自环套在环里、
9//! 同一对节点被两条不同谓词连着)。
10//!
11//! **没有公理就没有依据。** 四类检查每一类都由本体里的一位布尔决定要不要查,
12//! 没声明就不查——不报矛盾比猜一个公理出来安全。所以一个没装本体包的库跑出来
13//! 是零,那是实情不是故障。
14
15pub mod derive;
16pub mod ontology;
17
18use std::collections::{HashMap, HashSet};
19use uuid::Uuid;
20
21/// 一条参与检查的事实:谁、什么关系、指向谁。
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct Edge {
24 pub fact: Uuid,
25 pub predicate: Uuid,
26 pub subject: Uuid,
27 pub object: Uuid,
28}
29
30/// 一个谓词声明了哪些公理。四位都为假的谓词根本不进检查。
31#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
32pub struct Axioms {
33 pub transitive: bool,
34 pub symmetric: bool,
35 pub asymmetric: bool,
36 pub irreflexive: bool,
37 pub functional: bool,
38 pub inverse_functional: bool,
39 /// `p⁻¹ = q`:这个谓词的逆是哪一个。**跨谓词的规则从这里来**——
40 /// `A p B` 推出 `B q A`,而 R0 的检查也要看它(自己是自己的逆等于对称)
41 pub inverse_of: Option<Uuid>,
42 /// `p ⊑ q`:断言了具体的,通用的也成立。链要防成环,R0 那边查
43 pub sub_property_of: Option<Uuid>,
44}
45
46impl Axioms {
47 /// 一位都没声明的谓词不必检查——**这是性能上的事,也是语义上的事**:
48 /// 没有公理就没有判据,扫它只会白扫。
49 fn says_nothing(&self) -> bool {
50 *self == Axioms::default()
51 }
52}
53
54/// 查出来的一处矛盾。落库在 `axiom_violations`——**不进 `fact_conflicts`**:
55/// 那张表问的是「哪条对」,而公理违规问的是「错在数据还是错在定义」,
56/// 后者的出路可能是去改本体。
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct Violation {
59 pub kind: Kind,
60 /// 涉及的事实。**自反违反只有一条**——它跟自己矛盾,不需要第二条。
61 /// 环取首尾两条(中间那些在 `path` 里)。
62 pub left: Uuid,
63 pub right: Uuid,
64 /// 环的完整路径,按事实排列;其余三类为空。
65 /// 留着是因为「A→B→C→A」比「A 与 C 矛盾」有用得多——人要顺着看一遍才知道
66 /// 该撤哪一条
67 pub path: Vec<Uuid>,
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
71pub enum Kind {
72 /// `A p A`,而 p 声明了 irreflexive
73 SelfLoop,
74 /// `A p B` 且 `B p A`,而 p 声明了 asymmetric
75 Asymmetry,
76 /// `A p B p … p A`,而 p 声明了 transitive——闭包里推出 `A p A`
77 Cycle,
78 /// 同一主语与谓词同时指向两个宾语,而 p 声明了 functional
79 /// (inverse_functional 则是同一宾语被两个主语指)
80 Functional,
81 /// `A p B`,而 A 不在 p 声明的 domain 里、或 B 不在 range 里(#190 / #196)。
82 ///
83 /// **这一类不由本 crate 算出**:它要看实体的类型与 domain / range 的闭包,那是
84 /// 库里的东西,`utopia-store::reasoning::signature_breaks` 用 SQL 量。列在这里
85 /// 是为了与其它四类走同一条落库、清陈、裁决的路——left 与 right 同一条事实,
86 /// 与自反那类同款
87 Signature,
88 /// 一条派生撞上了一条断言(0017):推出来的 `A p B` 与账本里的某条断言在 p 的
89 /// 公理上不能并存。派生不落地,这一行把它摆到人面前。`left` 是被撞的断言,
90 /// `right` 是派生的最后一条前提,`path` 是全部前提;推出来的三元组本身在
91 /// `axiom_violations.detail` 里——它没有落库,没有 id 可指
92 DerivedContradiction,
93}
94
95impl Kind {
96 pub fn as_str(self) -> &'static str {
97 match self {
98 Kind::SelfLoop => "self_loop",
99 Kind::Asymmetry => "asymmetry",
100 Kind::Cycle => "cycle",
101 Kind::Functional => "functional",
102 Kind::Signature => "signature",
103 Kind::DerivedContradiction => "derived_contradiction",
104 }
105 }
106}
107
108/// 环检测的深度上限。
109///
110/// **必须有,不是防御性编程。** 0002 在真实语料上量过:`part_of` 的传递闭包
111/// 从 185 条膨胀到 828 条且**不收敛**——深度分布 `1:185 2:181 3:141 4:45
112/// 5:52 6:40 7:52 8:40 9:52 10:40`,第 5 层起振荡而不是衰减,那是有环的形状。
113/// 没有上限,一个环就能让求值不终止。
114pub const MAX_DEPTH: usize = 12;
115
116/// 拿公理量一遍这批边。
117///
118/// 每个谓词各查各的:公理是挂在谓词上的,跨谓词的边之间没有可比性
119/// (`A part_of B` 与 `B produces A` 同时成立不是矛盾)。
120pub fn check(edges: &[Edge], axioms: &HashMap<Uuid, Axioms>) -> Vec<Violation> {
121 let mut out = Vec::new();
122 let mut by_pred: HashMap<Uuid, Vec<Edge>> = HashMap::new();
123 for e in edges {
124 let Some(ax) = axioms.get(&e.predicate) else {
125 continue;
126 };
127 if ax.says_nothing() {
128 continue;
129 }
130 by_pred.entry(e.predicate).or_default().push(*e);
131 }
132 for (pred, group) in by_pred {
133 let ax = axioms[&pred];
134 if ax.irreflexive {
135 out.extend(self_loops(&group));
136 }
137 if ax.asymmetric {
138 out.extend(asymmetries(&group));
139 }
140 if ax.transitive {
141 out.extend(cycles(&group));
142 }
143 if ax.functional {
144 out.extend(too_many(&group, |e| e.subject, |e| e.object));
145 }
146 if ax.inverse_functional {
147 out.extend(too_many(&group, |e| e.object, |e| e.subject));
148 }
149 }
150 out
151}
152
153fn self_loops(edges: &[Edge]) -> Vec<Violation> {
154 edges
155 .iter()
156 .filter(|e| e.subject == e.object)
157 .map(|e| Violation {
158 kind: Kind::SelfLoop,
159 // 两列填同一条:它跟自己矛盾,没有第二条事实可指
160 left: e.fact,
161 right: e.fact,
162 path: Vec::new(),
163 })
164 .collect()
165}
166
167fn asymmetries(edges: &[Edge]) -> Vec<Violation> {
168 let mut seen: HashMap<(Uuid, Uuid), Uuid> = HashMap::new();
169 let mut out = Vec::new();
170 for e in edges {
171 if e.subject == e.object {
172 // 自环由 irreflexive 那一档负责;反对称在这里报一遍是重复
173 continue;
174 }
175 if let Some(&other) = seen.get(&(e.object, e.subject)) {
176 out.push(Violation {
177 kind: Kind::Asymmetry,
178 left: other,
179 right: e.fact,
180 path: Vec::new(),
181 });
182 }
183 seen.insert((e.subject, e.object), e.fact);
184 }
185 out
186}
187
188/// 找环。**每个环只报一次**,从环上最小的节点起算。
189///
190/// 用深度优先而不是半朴素闭包求值:两者都能发现环,但闭包只告诉你「A 推出了
191/// A」,而人要的是**路径**——顺着 `A→B→C→A` 看一遍才知道该撤哪一条。闭包丢掉
192/// 的正是这个。
193///
194/// R1 物化推导要的是闭包本身,那时再建;R0 要的是「哪几条边凑成了环」。
195fn cycles(edges: &[Edge]) -> Vec<Violation> {
196 let mut adj: HashMap<Uuid, Vec<&Edge>> = HashMap::new();
197 for e in edges {
198 adj.entry(e.subject).or_default().push(e);
199 }
200 let mut reported: HashSet<Vec<Uuid>> = HashSet::new();
201 let mut out = Vec::new();
202 let nodes: Vec<Uuid> = adj.keys().copied().collect();
203 for start in nodes {
204 let mut path: Vec<&Edge> = Vec::new();
205 let mut on_path: HashSet<Uuid> = HashSet::new();
206 walk(
207 start,
208 start,
209 &adj,
210 &mut path,
211 &mut on_path,
212 &mut reported,
213 &mut out,
214 );
215 }
216 out
217}
218
219#[allow(clippy::too_many_arguments)]
220fn walk<'a>(
221 start: Uuid,
222 at: Uuid,
223 adj: &HashMap<Uuid, Vec<&'a Edge>>,
224 path: &mut Vec<&'a Edge>,
225 on_path: &mut HashSet<Uuid>,
226 reported: &mut HashSet<Vec<Uuid>>,
227 out: &mut Vec<Violation>,
228) {
229 if path.len() >= MAX_DEPTH {
230 return;
231 }
232 let Some(next) = adj.get(&at) else { return };
233 for e in next {
234 if e.object == start && !path.is_empty() {
235 // 回到起点:成环。**按事实 id 排序去重**——同一个环从不同节点
236 // 出发会被走到 n 次,报 n 遍就是让人把同一件事看 n 次
237 let mut facts: Vec<Uuid> = path.iter().map(|x| x.fact).collect();
238 facts.push(e.fact);
239 let mut key = facts.clone();
240 key.sort();
241 if reported.insert(key) {
242 out.push(Violation {
243 kind: Kind::Cycle,
244 left: facts[0],
245 right: *facts.last().unwrap(),
246 path: facts,
247 });
248 }
249 continue;
250 }
251 if e.object == start || on_path.contains(&e.object) {
252 continue;
253 }
254 on_path.insert(e.object);
255 path.push(e);
256 walk(start, e.object, adj, path, on_path, reported, out);
257 path.pop();
258 on_path.remove(&e.object);
259 }
260}
261
262/// 函数性违反:同一个「一端」指向了两个不同的「另一端」。
263///
264/// `functional` 与 `inverse_functional` 是同一个判断的两个方向,所以共用这一个
265/// 函数,由调用方决定哪一端是键。
266fn too_many(edges: &[Edge], key: fn(&Edge) -> Uuid, val: fn(&Edge) -> Uuid) -> Vec<Violation> {
267 let mut by_key: HashMap<Uuid, Vec<&Edge>> = HashMap::new();
268 for e in edges {
269 by_key.entry(key(e)).or_default().push(e);
270 }
271 let mut out = Vec::new();
272 for (_, group) in by_key {
273 // 只报第一对。同一个主语指了五个宾语时报十对(两两组合)只是把同一件事
274 // 说十遍——人要处理的是「这里有冲突」,看一对就够去查了
275 let mut distinct: Vec<&Edge> = Vec::new();
276 for e in group {
277 if !distinct.iter().any(|d| val(d) == val(e)) {
278 distinct.push(e);
279 }
280 }
281 if distinct.len() > 1 {
282 out.push(Violation {
283 kind: Kind::Functional,
284 left: distinct[0].fact,
285 right: distinct[1].fact,
286 path: Vec::new(),
287 });
288 }
289 }
290 out
291}
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296
297 /// 造边的简写。节点用小整数编出稳定的 uuid,读断言时看得出谁是谁。
298 fn n(i: u8) -> Uuid {
299 Uuid::from_bytes([i; 16])
300 }
301 fn f(i: u8) -> Uuid {
302 // 与节点 id 分段:节点用低位,事实用高位。`u8` 装得下 0..=255,
303 // 而测试里造过 30 条边的链——用 `200 + i` 会溢出
304 Uuid::from_bytes([i; 16].map(|b| b ^ 0xF0))
305 }
306 fn e(fact: u8, s: u8, o: u8) -> Edge {
307 Edge {
308 fact: f(fact),
309 predicate: n(99),
310 subject: n(s),
311 object: n(o),
312 }
313 }
314 fn with(ax: Axioms) -> HashMap<Uuid, Axioms> {
315 HashMap::from([(n(99), ax)])
316 }
317 fn kinds(v: &[Violation]) -> Vec<Kind> {
318 let mut k: Vec<Kind> = v.iter().map(|x| x.kind).collect();
319 k.sort_by_key(|x| x.as_str());
320 k
321 }
322
323 /// **没声明公理的谓词一条都不查。** 这是整套检查的地基:没有依据就不报矛盾。
324 ///
325 /// 反过来说也成立——一个没装本体包的库跑出来是零,那是实情不是故障。
326 #[test]
327 fn a_predicate_that_declares_nothing_is_never_checked() {
328 let edges = [e(1, 1, 1), e(2, 1, 2), e(3, 2, 1)];
329 assert!(check(&edges, &with(Axioms::default())).is_empty());
330 // 连 axioms 里都没有这个谓词时同样不查(本体里没有这一行)
331 assert!(check(&edges, &HashMap::new()).is_empty());
332 }
333
334 #[test]
335 fn a_self_loop_needs_irreflexive_to_be_a_problem() {
336 let edges = [e(1, 1, 1)];
337 assert!(check(
338 &edges,
339 &with(Axioms {
340 transitive: true,
341 ..Default::default()
342 })
343 )
344 .is_empty());
345 let v = check(
346 &edges,
347 &with(Axioms {
348 irreflexive: true,
349 ..Default::default()
350 }),
351 );
352 assert_eq!(kinds(&v), vec![Kind::SelfLoop]);
353 // 只有一条事实:两列填同一个 id
354 assert_eq!(v[0].left, v[0].right);
355 }
356
357 /// 反对称那一档**不重复报自环**。`A p A` 同时满足「有反向边」的字面意思,
358 /// 不挡掉的话一条自环会在两档里各报一次,人看到两条要处理的东西而其实是一件。
359 #[test]
360 fn a_self_loop_is_reported_once_not_twice() {
361 let edges = [e(1, 1, 1)];
362 let v = check(
363 &edges,
364 &with(Axioms {
365 irreflexive: true,
366 asymmetric: true,
367 ..Default::default()
368 }),
369 );
370 assert_eq!(kinds(&v), vec![Kind::SelfLoop]);
371 }
372
373 #[test]
374 fn a_pair_pointing_both_ways_needs_asymmetric() {
375 let edges = [e(1, 1, 2), e(2, 2, 1)];
376 assert!(check(
377 &edges,
378 &with(Axioms {
379 transitive: true,
380 ..Default::default()
381 })
382 )
383 .iter()
384 .all(|v| v.kind != Kind::Asymmetry));
385 let v = check(
386 &edges,
387 &with(Axioms {
388 asymmetric: true,
389 ..Default::default()
390 }),
391 );
392 assert_eq!(kinds(&v), vec![Kind::Asymmetry]);
393 assert_eq!((v[0].left, v[0].right), (f(1), f(2)));
394 }
395
396 /// 长环要报出**路径**,而不只是「首尾矛盾」——人要顺着看一遍才知道撤哪一条。
397 #[test]
398 fn a_long_cycle_reports_the_whole_path() {
399 let edges = [e(1, 1, 2), e(2, 2, 3), e(3, 3, 4), e(4, 4, 1)];
400 let v = check(
401 &edges,
402 &with(Axioms {
403 transitive: true,
404 ..Default::default()
405 }),
406 );
407 assert_eq!(v.len(), 1, "一个环只报一次");
408 assert_eq!(v[0].path.len(), 4, "四条边都该在路径里");
409 }
410
411 /// **同一个环从不同节点出发会被走到 n 次。** 去重是这个函数存在的一半理由:
412 /// 报四遍就是让人把同一件事看四遍。
413 #[test]
414 fn one_cycle_is_one_finding_however_many_ways_in() {
415 let edges = [e(1, 1, 2), e(2, 2, 3), e(3, 3, 1)];
416 let v = check(
417 &edges,
418 &with(Axioms {
419 transitive: true,
420 ..Default::default()
421 }),
422 );
423 assert_eq!(v.len(), 1);
424 }
425
426 /// 两个互不相干的环各报一次。
427 #[test]
428 fn separate_cycles_stay_separate() {
429 let edges = [e(1, 1, 2), e(2, 2, 1), e(3, 5, 6), e(4, 6, 5)];
430 let v = check(
431 &edges,
432 &with(Axioms {
433 transitive: true,
434 ..Default::default()
435 }),
436 );
437 assert_eq!(v.len(), 2);
438 }
439
440 /// **深度上限挡得住不收敛。** 0002 在真实语料上量到 `part_of` 闭包深度到 10
441 /// 仍在振荡;没有上限,一条长链加一个环就能让求值不终止。
442 ///
443 /// 这里造一条比上限更长的链再闭合——它不该让检查挂住,报不报得出那个环是
444 /// 次要的,**不挂住是首要的**。
445 #[test]
446 fn a_chain_longer_than_the_limit_still_terminates() {
447 let mut edges: Vec<Edge> = (0..30).map(|i| e(i, i, i + 1)).collect();
448 edges.push(e(60, 30, 0));
449 let v = check(
450 &edges,
451 &with(Axioms {
452 transitive: true,
453 ..Default::default()
454 }),
455 );
456 // 断言的是"跑完了",长度不作要求
457 assert!(v.len() <= 1);
458 }
459
460 #[test]
461 fn functional_and_its_inverse_are_two_directions_of_one_check() {
462 // 同一个主语指了两个宾语
463 let out = [e(1, 1, 2), e(2, 1, 3)];
464 assert_eq!(
465 kinds(&check(
466 &out,
467 &with(Axioms {
468 functional: true,
469 ..Default::default()
470 })
471 )),
472 vec![Kind::Functional]
473 );
474 assert!(check(
475 &out,
476 &with(Axioms {
477 inverse_functional: true,
478 ..Default::default()
479 })
480 )
481 .is_empty());
482
483 // 同一个宾语被两个主语指
484 let inn = [e(1, 2, 1), e(2, 3, 1)];
485 assert_eq!(
486 kinds(&check(
487 &inn,
488 &with(Axioms {
489 inverse_functional: true,
490 ..Default::default()
491 })
492 )),
493 vec![Kind::Functional]
494 );
495 assert!(check(
496 &inn,
497 &with(Axioms {
498 functional: true,
499 ..Default::default()
500 })
501 )
502 .is_empty());
503 }
504
505 /// 同一个主语指五个宾语只报一对。报十对(两两组合)是把同一件事说十遍——
506 /// 人要处理的是「这里有冲突」,看一对就够去查了。
507 #[test]
508 fn one_finding_per_conflicting_key_not_one_per_pair() {
509 let edges = [e(1, 1, 2), e(2, 1, 3), e(3, 1, 4), e(4, 1, 5), e(5, 1, 6)];
510 let v = check(
511 &edges,
512 &with(Axioms {
513 functional: true,
514 ..Default::default()
515 }),
516 );
517 assert_eq!(v.len(), 1);
518 }
519
520 /// 同一个主语两次指向**同一个**宾语不是冲突——重复断言而已。
521 #[test]
522 fn saying_the_same_thing_twice_is_not_a_contradiction() {
523 let edges = [e(1, 1, 2), e(2, 1, 2)];
524 assert!(check(
525 &edges,
526 &with(Axioms {
527 functional: true,
528 ..Default::default()
529 })
530 )
531 .is_empty());
532 }
533
534 /// **公理挂在谓词上,跨谓词的边之间没有可比性。**
535 /// `A p B` 与 `B q A` 同时成立不是矛盾,哪怕 p 声明了反对称。
536 #[test]
537 fn axioms_do_not_leak_across_predicates() {
538 let a = Edge {
539 fact: f(1),
540 predicate: n(90),
541 subject: n(1),
542 object: n(2),
543 };
544 let b = Edge {
545 fact: f(2),
546 predicate: n(91),
547 subject: n(2),
548 object: n(1),
549 };
550 let ax = HashMap::from([
551 (
552 n(90),
553 Axioms {
554 asymmetric: true,
555 ..Default::default()
556 },
557 ),
558 (
559 n(91),
560 Axioms {
561 asymmetric: true,
562 ..Default::default()
563 },
564 ),
565 ]);
566 assert!(check(&[a, b], &ax).is_empty());
567 }
568}