Elffuss BraidHub

kikocis/utopia public

b7cca7fa81d9 · 26.5 KiBRawPermalink
1//! 一致性检查的取数与落库。判断本身在 `utopia-reason`——那一层不碰数据库。
2//!
3//! 三步:把活事实取成边、把 `relation_types` 的公理列取成 `Axioms`、把
4//! `check()` 吐出来的违规写进 `axiom_violations`。
5//!
6//! **重跑是幂等的,而且以「重算」为准。** 每次跑完,这个库里没被重新算出来的
7//! `open` 行会被删掉——它们是派生状态,事实撤了、公理放宽了,那条违规就不该
8//! 还挂在 Review 页上。已经有人表态的(`resolved`)一行不动:那是人的决定,
9//! 不是算出来的东西。
10//!
11//! 这条规矩踩过一次坑的反面(见 `ontology_proposals`):那边重跑会把被拒绝过的
12//! 提案刷回待看,等于每跑一次就把人的否决抹掉一次。所以这里 `ON CONFLICT`
13//! 什么都不做——已经在库里的那一行,无论 open 还是 resolved,都按原样留着。
14
15use sqlx::PgPool;
16use std::collections::HashMap;
17use utopia_core::models::{AxiomViolation, DerivedFactView, OntologyDefect};
18/// 规则种类的字面量。用 &'static str 而不是枚举:它直接进 SQL 也直接做键
19type RuleKind = &'static str;
20use utopia_core::AppResult;
21use utopia_reason::derive::TimedEdge;
22use utopia_reason::{check, Axioms, Edge, Violation};
23use uuid::Uuid;
24
25/// 一次检查的产出,给调用方写审计与告诉用户。
26#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
27pub struct Report {
28 /// 参与检查的边数
29 pub edges: usize,
30 /// 声明了至少一条公理的谓词数。**为零时结论是「没有判据」而不是「没有矛盾」**
31 pub predicates_with_axioms: usize,
32 /// 这次算出来的违规总数
33 pub found: usize,
34 /// 其中是新的(此前没在库里)
35 pub inserted: usize,
36 /// 清掉的陈旧 open 行
37 pub cleared: usize,
38}
39
40/// 取这个库里所有能参与检查的边。
41///
42/// 三个过滤条件都是必要的:
43///
44/// - `invalidated_at IS NULL`——被推翻的事实不该再报矛盾,它已经不是我们的断言了
45/// - `predicate_id IS NOT NULL`——没有谓词就没有公理可依(见 `facts.predicate_id`)
46/// - `object_id IS NOT NULL`——属性事实的宾语是字面值,公理谈的是实体之间的关系
47async fn edges(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<Edge>> {
48 let rows: Vec<(Uuid, Uuid, Uuid, Uuid)> = sqlx::query_as(
49 "SELECT id, predicate_id, subject_id, object_id
50 FROM facts
51 WHERE kb_id = $1
52 AND invalidated_at IS NULL
53 AND predicate_id IS NOT NULL
54 AND object_id IS NOT NULL",
55 )
56 .bind(kb_id)
57 .fetch_all(pool)
58 .await?;
59 Ok(rows
60 .into_iter()
61 .map(|(fact, predicate, subject, object)| Edge {
62 fact,
63 predicate,
64 subject,
65 object,
66 })
67 .collect())
68}
69
70/// 取这个库的谓词公理。
71///
72/// **只取声明了至少一位的**:一位都没声明的谓词进了表也不会被检查(`says_nothing`
73/// 会跳过),白白占内存。而且这个条数本身有意义——它是「有没有判据」的度量,
74/// 报告里要用。
75async fn axioms(pool: &PgPool, kb_id: Uuid) -> AppResult<HashMap<Uuid, Axioms>> {
76 let rows: Vec<(Uuid, bool, bool, bool, bool, bool, bool)> = sqlx::query_as(
77 "SELECT id, is_transitive, is_symmetric, is_asymmetric, is_irreflexive,
78 functional, inverse_functional
79 FROM relation_types
80 WHERE kb_id = $1
81 AND (is_transitive OR is_symmetric OR is_asymmetric OR is_irreflexive
82 OR functional OR inverse_functional)",
83 )
84 .bind(kb_id)
85 .fetch_all(pool)
86 .await?;
87 Ok(rows
88 .into_iter()
89 .map(
90 |(
91 id,
92 transitive,
93 symmetric,
94 asymmetric,
95 irreflexive,
96 functional,
97 inverse_functional,
98 )| {
99 (
100 id,
101 Axioms {
102 transitive,
103 symmetric,
104 asymmetric,
105 irreflexive,
106 functional,
107 inverse_functional,
108 },
109 )
110 },
111 )
112 .collect())
113}
114
115/// 跑一遍检查,把结果落库。
116pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {
117 let edges = edges(pool, kb_id).await?;
118 let axioms = axioms(pool, kb_id).await?;
119 let violations = check(&edges, &axioms);
120
121 let mut report = Report {
122 edges: edges.len(),
123 predicates_with_axioms: axioms.len(),
124 found: violations.len(),
125 ..Default::default()
126 };
127
128 // 事务里做,否则「插新的」与「清陈旧的」之间有个窗口,那一瞬间 Review 页
129 // 会短暂地少东西
130 let mut tx = pool.begin().await?;
131 let mut fresh: Vec<Uuid> = Vec::with_capacity(violations.len());
132 for v in &violations {
133 let Violation {
134 kind,
135 left,
136 right,
137 path,
138 } = v;
139 let id: Option<(Uuid,)> = sqlx::query_as(
140 "INSERT INTO axiom_violations (id, kb_id, kind, left_fact, right_fact, path)
141 VALUES ($1, $2, $3, $4, $5, $6)
142 ON CONFLICT (kb_id, kind, left_fact, right_fact) DO NOTHING
143 RETURNING id",
144 )
145 .bind(Uuid::now_v7())
146 .bind(kb_id)
147 .bind(kind.as_str())
148 .bind(left)
149 .bind(right)
150 .bind(path)
151 .fetch_optional(&mut *tx)
152 .await?;
153 if id.is_some() {
154 report.inserted += 1;
155 }
156 // 无论新插的还是本来就在的,都算「这一轮仍然成立」
157 let keep: (Uuid,) = sqlx::query_as(
158 "SELECT id FROM axiom_violations
159 WHERE kb_id = $1 AND kind = $2 AND left_fact = $3 AND right_fact = $4",
160 )
161 .bind(kb_id)
162 .bind(kind.as_str())
163 .bind(left)
164 .bind(right)
165 .fetch_one(&mut *tx)
166 .await?;
167 fresh.push(keep.0);
168 }
169
170 // 这一轮没算出来的 open 行是陈的:事实被撤了,或者公理放宽了。
171 // resolved 的不动——那是人的决定,不是派生状态
172 let cleared = sqlx::query(
173 "DELETE FROM axiom_violations
174 WHERE kb_id = $1 AND status = 'open' AND NOT (id = ANY($2))",
175 )
176 .bind(kb_id)
177 .bind(&fresh)
178 .execute(&mut *tx)
179 .await?;
180 report.cleared = cleared.rows_affected() as usize;
181 tx.commit().await?;
182 Ok(report)
183}
184
185/// Review 页要看的:还没人表态的违规,连同两条事实的三元组文本。
186///
187/// 展开成文本在 SQL 里做而不是回来再查一遍:一页几十条,每条两个三元组,
188/// 分开查就是上百次往返。谓词用 `fact_surface_predicate` 兜底——本体里没有
189/// 对应关系的事实拿原文说法显示(见 `facts.predicate_id`)。
190pub async fn open_violations(
191 pool: &PgPool,
192 kb_id: Uuid,
193 limit: i64,
194 offset: i64,
195) -> AppResult<Vec<AxiomViolation>> {
196 Ok(sqlx::query_as(
197 "WITH triple AS (
198 SELECT f.id,
199 s.canonical_name || ' · '
200 || COALESCE(r.label, fact_surface_predicate(f.id), '?') || ' · '
201 || COALESCE(o.canonical_name, f.object_value ->> 'summary',
202 f.object_value #>> '{}', '?') AS text,
203 r.label AS predicate
204 FROM facts f
205 JOIN entities s ON s.id = f.subject_id
206 LEFT JOIN relation_types r ON r.id = f.predicate_id
207 LEFT JOIN entities o ON o.id = f.object_id
208 WHERE f.kb_id = $1
209 )
210 SELECT v.id, v.kind, l.predicate,
211 v.left_fact, l.text AS left_text,
212 v.right_fact, rt.text AS right_text,
213 coalesce(array_length(v.path, 1), 0) AS path_len,
214 v.detected_at
215 FROM axiom_violations v
216 JOIN triple l ON l.id = v.left_fact
217 JOIN triple rt ON rt.id = v.right_fact
218 WHERE v.kb_id = $1 AND v.status = 'open'
219 ORDER BY v.detected_at DESC
220 LIMIT $2 OFFSET $3",
221 )
222 .bind(kb_id)
223 .bind(limit)
224 .bind(offset)
225 .fetch_all(pool)
226 .await?)
227}
228
229/// 人裁决一处违规。
230///
231/// **三个出路,不是两个。** 时态冲突问「哪条对」,而这里可能是定义错了——
232/// 用户导的本体把某个属性声明成反对称,而他自己的语料里那关系其实双向。
233/// `axiom_relaxed` 记的就是这种:该改的是本体,不是二十条事实。
234///
235/// 改状态不删行,与账本同一个规矩:表过态这件事本身要留痕,而且 `run` 靠
236/// `status = 'open'` 判断哪些是派生的、可以重算掉——人的决定必须活过重跑。
237pub async fn decide(
238 pool: &PgPool,
239 kb_id: Uuid,
240 violation_id: Uuid,
241 resolution: &str,
242 actor: Uuid,
243) -> AppResult<()> {
244 let res = sqlx::query(
245 "UPDATE axiom_violations
246 SET status = 'resolved', resolution = $3, decided_by = $4, decided_at = now()
247 WHERE id = $2 AND kb_id = $1 AND status = 'open'",
248 )
249 .bind(kb_id)
250 .bind(violation_id)
251 .bind(resolution)
252 .bind(actor)
253 .execute(pool)
254 .await?;
255 if res.rows_affected() == 0 {
256 return Err(utopia_core::AppError::NotFound);
257 }
258 Ok(())
259}
260
261// ===================== R0 的另一半:本体自己 =====================
262
263/// 本体自洽性检查的产出。
264#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
265pub struct OntologyReport {
266 pub classes: usize,
267 pub found: usize,
268 pub inserted: usize,
269 pub cleared: usize,
270}
271
272/// 量一遍本体自己:谓词的公理组合、subClassOf 的环、不可满足的类。
273///
274/// 与 [`run`] 同一套重跑规矩:`open` 是派生状态、可以被重算掉,`resolved`
275/// 是人的决定、一行不动。
276pub async fn check_ontology(pool: &PgPool, kb_id: Uuid) -> AppResult<OntologyReport> {
277 let ax = axioms(pool, kb_id).await?;
278 let parents: Vec<(Uuid, Uuid)> = sqlx::query_as(
279 "SELECT child_id, parent_id FROM entity_type_parents p
280 JOIN entity_types t ON t.id = p.child_id
281 WHERE t.kb_id = $1",
282 )
283 .bind(kb_id)
284 .fetch_all(pool)
285 .await?;
286 let disjoint: Vec<(Uuid, Uuid)> =
287 sqlx::query_as("SELECT a_id, b_id FROM entity_type_disjoint WHERE kb_id = $1")
288 .bind(kb_id)
289 .fetch_all(pool)
290 .await?;
291 let classes: i64 = sqlx::query_scalar("SELECT count(*) FROM entity_types WHERE kb_id = $1")
292 .bind(kb_id)
293 .fetch_one(pool)
294 .await?;
295
296 let defects = utopia_reason::ontology::check_ontology(&ax, &parents, &disjoint);
297 let mut report = OntologyReport {
298 classes: classes as usize,
299 found: defects.len(),
300 ..Default::default()
301 };
302
303 let mut tx = pool.begin().await?;
304 let mut fresh: Vec<Uuid> = Vec::with_capacity(defects.len());
305 for d in &defects {
306 let existing: Option<(Uuid,)> = sqlx::query_as(
307 "SELECT id FROM ontology_defects
308 WHERE kb_id = $1 AND kind = $2 AND subject = $3
309 AND other IS NOT DISTINCT FROM $4",
310 )
311 .bind(kb_id)
312 .bind(d.kind.as_str())
313 .bind(d.subject)
314 .bind(d.other)
315 .fetch_optional(&mut *tx)
316 .await?;
317 let id = match existing {
318 Some((id,)) => id,
319 None => {
320 let id = Uuid::now_v7();
321 sqlx::query(
322 "INSERT INTO ontology_defects (id, kb_id, kind, subject, other, path)
323 VALUES ($1, $2, $3, $4, $5, $6)",
324 )
325 .bind(id)
326 .bind(kb_id)
327 .bind(d.kind.as_str())
328 .bind(d.subject)
329 .bind(d.other)
330 .bind(&d.path)
331 .execute(&mut *tx)
332 .await?;
333 report.inserted += 1;
334 id
335 }
336 };
337 fresh.push(id);
338 }
339 let cleared = sqlx::query(
340 "DELETE FROM ontology_defects
341 WHERE kb_id = $1 AND status = 'open' AND NOT (id = ANY($2))",
342 )
343 .bind(kb_id)
344 .bind(&fresh)
345 .execute(&mut *tx)
346 .await?;
347 report.cleared = cleared.rows_affected() as usize;
348 tx.commit().await?;
349 Ok(report)
350}
351
352// ===================== R1:物化推导 =====================
353
354/// 一次推导的产出。
355#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
356pub struct DeriveReport {
357 /// 编译出来的规则条数。**为零时结论是「没有规则」而不是「推不出东西」**
358 pub rules: usize,
359 pub edges: usize,
360 /// 这一轮算出来的派生总数
361 pub derived: usize,
362 /// 新落库的
363 pub inserted: usize,
364 /// 前提没了、跟着作废的
365 pub invalidated: usize,
366 /// 撞上单谓词上限、没推完的谓词个数
367 pub capped: usize,
368}
369
370/// 派生事实的身份:三元组 + 区间。
371///
372/// **区间进键**是有意的:区间变了就是另一条断言,老的作废、新的落地,
373/// 因为账本不许原地改。
374type DerivedKey = (Uuid, Uuid, Uuid, Option<i64>, Option<i64>);
375
376/// 精度按「最粗的那个」取。
377///
378/// 派生区间的两端各来自某一条前提,严格说该各随各的精度。取最粗是**故意保守**:
379/// 一条链只和它最不确定的那一环一样可信,而把 year 级的前提推出来的结论标成
380/// day,正是 `facts.valid_from_precision` 那条注释里说的「在无知的地方填一个
381/// 确定的值」。
382fn coarsest(a: Option<&str>, b: Option<&str>) -> Option<String> {
383 let rank = |p: &str| match p {
384 "year" => 0,
385 "month" => 1,
386 _ => 2,
387 };
388 match (a, b) {
389 (Some(x), Some(y)) => Some(if rank(x) <= rank(y) { x } else { y }.to_string()),
390 (Some(x), None) | (None, Some(x)) => Some(x.to_string()),
391 (None, None) => None,
392 }
393}
394
395/// 按本体公理重编译规则,返回 `(谓词, 种类) → 规则 id`。
396///
397/// **幂等**:身份取 `(kb, 谓词, 种类)`,重编译认得出「还是那条规则」——否则每跑
398/// 一次 `derived_facts.rule_id` 就指向一个新 id,历史全断。
399///
400/// **公理撤了的规则不删。** 已失效的派生行仍指着它,解释「当时是靠哪条规则推的」
401/// 需要它还在;而它不再出现在返回值里,据它推出来的事实由下面的对账作废。
402/// 规则一个库也就几条,留着不占地方。
403async fn compile_rules(
404 pool: &PgPool,
405 kb_id: Uuid,
406 ax: &HashMap<Uuid, Axioms>,
407) -> AppResult<HashMap<(Uuid, RuleKind), Uuid>> {
408 let mut want: Vec<(Uuid, RuleKind)> = Vec::new();
409 for (&pred, a) in ax {
410 if a.transitive {
411 want.push((pred, "transitive"));
412 }
413 if a.symmetric {
414 want.push((pred, "symmetric"));
415 }
416 }
417 want.sort();
418 let mut out = HashMap::new();
419 for (pred, kind) in want {
420 sqlx::query(
421 "INSERT INTO rules (id, kb_id, predicate_id, kind) VALUES ($1, $2, $3, $4)
422 ON CONFLICT (kb_id, predicate_id, kind) DO NOTHING",
423 )
424 .bind(Uuid::now_v7())
425 .bind(kb_id)
426 .bind(pred)
427 .bind(kind)
428 .execute(pool)
429 .await?;
430 let (id,): (Uuid,) = sqlx::query_as(
431 "SELECT id FROM rules WHERE kb_id = $1 AND predicate_id = $2 AND kind = $3",
432 )
433 .bind(kb_id)
434 .bind(pred)
435 .bind(kind)
436 .fetch_one(pool)
437 .await?;
438 out.insert((pred, kind), id);
439 }
440 Ok(out)
441}
442
443/// 取边时一并拿回来的随行信息(精度与置信度,落库要用)。
444type EdgeRow = (
445 Uuid,
446 Uuid,
447 Uuid,
448 Uuid,
449 Option<chrono::DateTime<chrono::Utc>>,
450 Option<chrono::DateTime<chrono::Utc>>,
451 Option<String>,
452 Option<String>,
453 f32,
454);
455
456type LiveRow = (
457 Uuid,
458 Uuid,
459 Uuid,
460 Uuid,
461 Option<chrono::DateTime<chrono::Utc>>,
462 Option<chrono::DateTime<chrono::Utc>>,
463);
464
465/// 推一遍,把派生事实落进账本。
466///
467/// **调用方负责检查 `materialize_inferences` 开关。** 这一层不判——它也被
468/// 「预览一下会推出什么」那条路用,而预览不该受开关约束。
469pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport> {
470 let ax = axioms(pool, kb_id).await?;
471 let rules = compile_rules(pool, kb_id, &ax).await?;
472
473 // 输入**只有断言**。派生住在另一张表,所以这里连过滤都不必写——那正是
474 // 分表买到的东西:忘了排除的后果是推不出东西,不是把自己的输出喂回自己
475 let rows: Vec<EdgeRow> = sqlx::query_as(
476 "SELECT id, predicate_id, subject_id, object_id,
477 valid_from, valid_to, valid_from_precision, valid_to_precision, confidence
478 FROM facts
479 WHERE kb_id = $1
480 AND invalidated_at IS NULL
481 AND predicate_id IS NOT NULL
482 AND object_id IS NOT NULL",
483 )
484 .bind(kb_id)
485 .fetch_all(pool)
486 .await?;
487
488 let mut edges = Vec::with_capacity(rows.len());
489 let mut meta: HashMap<Uuid, (Option<String>, Option<String>, f32)> = HashMap::new();
490 let mut spans: HashMap<Uuid, (Option<i64>, Option<i64>)> = HashMap::new();
491 for (id, pred, subj, obj, from, to, fp, tp, conf) in rows {
492 let (f, t) = (from.map(|x| x.timestamp()), to.map(|x| x.timestamp()));
493 edges.push(TimedEdge {
494 edge: Edge {
495 fact: id,
496 predicate: pred,
497 subject: subj,
498 object: obj,
499 },
500 from: f,
501 to: t,
502 });
503 spans.insert(id, (f, t));
504 meta.insert(id, (fp, tp, conf));
505 }
506
507 let derivation = utopia_reason::derive::derive(&edges, &ax);
508 let mut report = DeriveReport {
509 rules: rules.len(),
510 edges: edges.len(),
511 derived: derivation.facts.len(),
512 capped: derivation.capped.len(),
513 ..Default::default()
514 };
515
516 let mut wanted: HashMap<DerivedKey, &utopia_reason::derive::Derived> = HashMap::new();
517 for d in &derivation.facts {
518 let Some((from, to)) = utopia_reason::derive::validity(&d.premises, &spans) else {
519 continue;
520 };
521 wanted.insert((d.subject, d.predicate, d.object, from, to), d);
522 }
523
524 let mut tx = pool.begin().await?;
525 let live: Vec<LiveRow> = sqlx::query_as(
526 "SELECT id, subject_id, predicate_id, object_id, valid_from, valid_to
527 FROM derived_facts
528 WHERE kb_id = $1 AND invalidated_at IS NULL",
529 )
530 .bind(kb_id)
531 .fetch_all(&mut *tx)
532 .await?;
533
534 let mut stale: Vec<Uuid> = Vec::new();
535 for (id, s, p, o, from, to) in &live {
536 let key = (
537 *s,
538 *p,
539 *o,
540 from.map(|x| x.timestamp()),
541 to.map(|x| x.timestamp()),
542 );
543 if wanted.remove(&key).is_none() {
544 stale.push(*id);
545 }
546 }
547
548 // 前提没了 → 派生跟着失效。**置 invalidated_at 而不是删**:与拒绝一条事实
549 // 完全同构,记录轴上留下「我们曾据此推出,后来前提没了」,实体历史页面
550 // 直接就能展示(0002 第 3 节)
551 if !stale.is_empty() {
552 sqlx::query("UPDATE derived_facts SET invalidated_at = now() WHERE id = ANY($1)")
553 .bind(&stale)
554 .execute(&mut *tx)
555 .await?;
556 report.invalidated = stale.len();
557 }
558
559 for ((subject, predicate, object, from, to), d) in wanted {
560 let Some(&rule_id) = rules.get(&(predicate, d.rule.as_str())) else {
561 continue;
562 };
563 // 精度与置信度都取前提里最保守的那一个
564 let mut fp: Option<String> = None;
565 let mut tp: Option<String> = None;
566 let mut conf = 1.0f32;
567 for p in &d.premises {
568 if let Some((pf, pt, pc)) = meta.get(p) {
569 fp = coarsest(fp.as_deref(), pf.as_deref());
570 tp = coarsest(tp.as_deref(), pt.as_deref());
571 conf = conf.min(*pc);
572 }
573 }
574 // 约束是「有日期才有精度」——交集把某一端算成无界时,那一端的精度也得清掉
575 let fp = from.and(fp);
576 let tp = to.and(tp);
577 let id = Uuid::now_v7();
578 sqlx::query(
579 "INSERT INTO derived_facts (id, kb_id, subject_id, predicate_id, object_id,
580 valid_from, valid_to,
581 valid_from_precision, valid_to_precision,
582 confidence, rule_id)
583 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)",
584 )
585 .bind(id)
586 .bind(kb_id)
587 .bind(subject)
588 .bind(predicate)
589 .bind(object)
590 .bind(from.map(stamp))
591 .bind(to.map(stamp))
592 .bind(&fp)
593 .bind(&tp)
594 .bind(conf)
595 .bind(rule_id)
596 .execute(&mut *tx)
597 .await?;
598 for (seq, premise) in d.premises.iter().enumerate() {
599 sqlx::query(
600 "INSERT INTO fact_derivations (derived_fact_id, premise_fact_id, seq)
601 VALUES ($1, $2, $3)",
602 )
603 .bind(id)
604 .bind(premise)
605 .bind(seq as i32)
606 .execute(&mut *tx)
607 .await?;
608 }
609 report.inserted += 1;
610 }
611 tx.commit().await?;
612 Ok(report)
613}
614
615fn stamp(secs: i64) -> chrono::DateTime<chrono::Utc> {
616 chrono::DateTime::from_timestamp(secs, 0).unwrap_or_default()
617}
618
619/// Review 页要看的本体缺陷,连同标签。
620///
621/// 标签在 SQL 里取而不是回来再查:`subject` 那一列同一列指两张表(谓词或类),
622/// 分开查就要先按 kind 分组、再发两批查询,而一次 LEFT JOIN 两张表就够——
623/// 一个 id 只可能命中其中一张。
624pub async fn open_defects(
625 pool: &PgPool,
626 kb_id: Uuid,
627 limit: i64,
628 offset: i64,
629) -> AppResult<Vec<OntologyDefect>> {
630 Ok(sqlx::query_as(
631 "SELECT d.id, d.kind,
632 COALESCE(st.label, sr.label) AS subject_label,
633 ot.label AS other_label,
634 COALESCE(
635 (SELECT array_agg(t.label ORDER BY x.ord)
636 FROM unnest(d.path) WITH ORDINALITY AS x(id, ord)
637 JOIN entity_types t ON t.id = x.id),
638 ARRAY[]::text[]
639 ) AS path_labels,
640 d.detected_at
641 FROM ontology_defects d
642 LEFT JOIN entity_types st ON st.id = d.subject
643 LEFT JOIN relation_types sr ON sr.id = d.subject
644 LEFT JOIN entity_types ot ON ot.id = d.other
645 WHERE d.kb_id = $1 AND d.status = 'open'
646 ORDER BY d.detected_at DESC
647 LIMIT $2 OFFSET $3",
648 )
649 .bind(kb_id)
650 .bind(limit)
651 .bind(offset)
652 .fetch_all(pool)
653 .await?)
654}
655
656/// 人对一处本体缺陷表态。
657///
658/// 两个出路而不是三个:本体缺陷没有「数据错了」这一条——它压根没看数据。
659/// `fixed` 是「我去改了本体」,`accepted` 是「看过,不必改」。
660pub async fn decide_defect(
661 pool: &PgPool,
662 kb_id: Uuid,
663 defect_id: Uuid,
664 resolution: &str,
665 actor: Uuid,
666) -> AppResult<()> {
667 let res = sqlx::query(
668 "UPDATE ontology_defects
669 SET status = 'resolved', resolution = $3, decided_by = $4, decided_at = now()
670 WHERE id = $2 AND kb_id = $1 AND status = 'open'",
671 )
672 .bind(kb_id)
673 .bind(defect_id)
674 .bind(resolution)
675 .bind(actor)
676 .execute(pool)
677 .await?;
678 if res.rows_affected() == 0 {
679 return Err(utopia_core::AppError::NotFound);
680 }
681 Ok(())
682}
683
684/// 到点该重推的库。
685///
686/// 与来源同步同一个形状:一个间隔 + 一个上次时间。**从没推过的算到期**——
687/// 刚打开开关的库不该等一个周期才第一次推。
688pub async fn due_for_inference(pool: &PgPool) -> AppResult<Vec<Uuid>> {
689 Ok(sqlx::query_scalar(
690 "SELECT id FROM knowledge_bases
691 WHERE materialize_inferences
692 AND (last_inference_at IS NULL
693 OR last_inference_at < now()
694 - make_interval(mins => inference_interval_minutes))",
695 )
696 .fetch_all(pool)
697 .await?)
698}
699
700/// 记下这一轮推完的时间。
701///
702/// **推完就记,哪怕什么都没变**:这一列答的是「上次看过没有」,不是「上次改过
703/// 没有」。不记的话没变化的库会每分钟被扫起来重算一遍。
704pub async fn mark_inference_ran(pool: &PgPool, kb_id: Uuid) -> AppResult<()> {
705 sqlx::query("UPDATE knowledge_bases SET last_inference_at = now() WHERE id = $1")
706 .bind(kb_id)
707 .execute(pool)
708 .await?;
709 Ok(())
710}
711
712/// 一条派生事实,配好展示与证明所需的文本(实体面板的「推出来的」那一档)。
713///
714/// **证明一起取回来**:这一档存在的理由就是「这条边不是谁说的,是这么推出来的」,
715/// 而不给出前提的话它跟一条普通的边看不出区别——那正是用户担心的污染。
716pub async fn derived_for_entity(
717 pool: &PgPool,
718 kb_id: Uuid,
719 entity_id: Uuid,
720) -> AppResult<Vec<DerivedFactView>> {
721 Ok(sqlx::query_as(
722 "SELECT d.id,
723 d.subject_id, s.canonical_name AS subject,
724 d.object_id, o.canonical_name AS object,
725 r.label AS predicate,
726 ru.kind AS rule,
727 d.valid_from, d.valid_to, d.confidence, d.derived_at,
728 COALESCE(
729 (SELECT array_agg(
730 ps.canonical_name || ' · '
731 || COALESCE(pr.label, '?') || ' · '
732 || COALESCE(po.canonical_name, '?')
733 ORDER BY fd.seq)
734 FROM fact_derivations fd
735 JOIN facts pf ON pf.id = fd.premise_fact_id
736 JOIN entities ps ON ps.id = pf.subject_id
737 LEFT JOIN relation_types pr ON pr.id = pf.predicate_id
738 LEFT JOIN entities po ON po.id = pf.object_id
739 WHERE fd.derived_fact_id = d.id),
740 ARRAY[]::text[]
741 ) AS premises
742 FROM derived_facts d
743 JOIN entities s ON s.id = d.subject_id
744 JOIN entities o ON o.id = d.object_id
745 JOIN relation_types r ON r.id = d.predicate_id
746 JOIN rules ru ON ru.id = d.rule_id
747 WHERE d.kb_id = $1 AND d.invalidated_at IS NULL
748 AND (d.subject_id = $2 OR d.object_id = $2)
749 ORDER BY d.derived_at DESC",
750 )
751 .bind(kb_id)
752 .bind(entity_id)
753 .fetch_all(pool)
754 .await?)
755}