Elffuss BraidHub

kikocis/utopia public

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