Elffuss BraidHub

kikocis/utopia public

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