Elffuss BraidHub

kikocis/utopia public

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