| 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 | |
| 15 | use serde_json::json; |
| 16 | use sqlx::PgPool; |
| 17 | use std::collections::{HashMap, HashSet}; |
| 18 | use utopia_core::models::{AxiomViolation, DerivedFactView, OntologyDefect}; |
| 19 | /// 规则种类的字面量。用 &'static str 而不是枚举:它直接进 SQL 也直接做键 |
| 20 | type RuleKind = &'static str; |
| 21 | use utopia_core::AppResult; |
| 22 | use utopia_reason::derive::{Contradictions, Derivation, TimedEdge}; |
| 23 | use utopia_reason::{check, Axioms, Edge, Kind, Violation}; |
| 24 | use uuid::Uuid; |
| 25 | |
| 26 | /// 一次检查的产出,给调用方写审计与告诉用户。 |
| 27 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 28 | pub struct Report { |
| 29 | /// 参与检查的边数 |
| 30 | pub edges: usize, |
| 31 | /// 声明了至少一条公理的谓词数。**为零时结论是「没有判据」而不是「没有矛盾」** |
| 32 | pub predicates_with_axioms: usize, |
| 33 | /// 这次算出来的违规总数 |
| 34 | pub found: usize, |
| 35 | /// 其中是新的(此前没在库里) |
| 36 | pub inserted: usize, |
| 37 | /// 清掉的陈旧 open 行 |
| 38 | pub cleared: usize, |
| 39 | /// 派生撞上断言的条数(0017),已含在 `found` 里 |
| 40 | pub contradictions: usize, |
| 41 | /// 撞上单谓词上限、没进队列的矛盾条数。**不为零时说明根子在规则**: |
| 42 | /// 一条谓词上上百条派生都撞了,逐条看是没有意义的 |
| 43 | pub contradictions_capped: usize, |
| 44 | /// 互撞的规则对数——进 `ontology_defects`,不进这张表 |
| 45 | pub rules_disagree: usize, |
| 46 | } |
| 47 | |
| 48 | /// 单个谓词上进队列的矛盾上限(0017 §1)。超出的部分只计数。 |
| 49 | const MAX_CLASHES_PER_PREDICATE: usize = 50; |
| 50 | |
| 51 | /// 取这个库的谓词公理。 |
| 52 | /// |
| 53 | /// **只取声明了至少一位的**:一位都没声明的谓词进了表也不会被检查(`says_nothing` |
| 54 | /// 会跳过),白白占内存。而且这个条数本身有意义——它是「有没有判据」的度量, |
| 55 | /// 报告里要用。 |
| 56 | #[allow(clippy::type_complexity)] |
| 57 | async fn axioms(pool: &PgPool, kb_id: Uuid) -> AppResult<HashMap<Uuid, Axioms>> { |
| 58 | let rows: Vec<( |
| 59 | Uuid, |
| 60 | bool, |
| 61 | bool, |
| 62 | bool, |
| 63 | bool, |
| 64 | bool, |
| 65 | bool, |
| 66 | Option<Uuid>, |
| 67 | Option<Uuid>, |
| 68 | )> = sqlx::query_as( |
| 69 | "SELECT id, is_transitive, is_symmetric, is_asymmetric, is_irreflexive, |
| 70 | functional, inverse_functional, inverse_of, sub_property_of |
| 71 | FROM relation_types |
| 72 | WHERE kb_id = $1 |
| 73 | AND (is_transitive OR is_symmetric OR is_asymmetric OR is_irreflexive |
| 74 | OR functional OR inverse_functional |
| 75 | OR inverse_of IS NOT NULL OR sub_property_of IS NOT NULL)", |
| 76 | ) |
| 77 | .bind(kb_id) |
| 78 | .fetch_all(pool) |
| 79 | .await?; |
| 80 | let mut map: HashMap<Uuid, Axioms> = rows |
| 81 | .into_iter() |
| 82 | .map( |
| 83 | |( |
| 84 | id, |
| 85 | transitive, |
| 86 | symmetric, |
| 87 | asymmetric, |
| 88 | irreflexive, |
| 89 | functional, |
| 90 | inverse_functional, |
| 91 | inverse_of, |
| 92 | sub_property_of, |
| 93 | )| { |
| 94 | ( |
| 95 | id, |
| 96 | Axioms { |
| 97 | transitive, |
| 98 | symmetric, |
| 99 | asymmetric, |
| 100 | irreflexive, |
| 101 | functional, |
| 102 | inverse_functional, |
| 103 | inverse_of, |
| 104 | sub_property_of, |
| 105 | }, |
| 106 | ) |
| 107 | }, |
| 108 | ) |
| 109 | .collect(); |
| 110 | |
| 111 | // **逆是相互的,而库里只存单向。** 声明了 `p⁻¹ = q` 却没回填 |
| 112 | // `q⁻¹ = p` 的话,`A p B` 推得出 `B q A`,`B q A` 却推不回 `A p B` |
| 113 | // ——「问工作和问雇佣答案不同」正是 R1 要消灭的东西,只修一半等于没修。 |
| 114 | // |
| 115 | // 归一化放在这里而不是数据库触发器:绕过触发器的路不止一条(RDF 导入、 |
| 116 | // 直接改表),而载入公理只有这一处,谁也绕不过去。 |
| 117 | let pairs: Vec<(Uuid, Uuid)> = map |
| 118 | .iter() |
| 119 | .filter_map(|(id, ax)| ax.inverse_of.map(|inv| (inv, *id))) |
| 120 | .collect(); |
| 121 | for (target, source) in pairs { |
| 122 | // 已经声明了自己的逆就不动它——**人写的优先于推出来的**, |
| 123 | // 两边指得不一样是本体自己的矛盾,交给 R0 报,不在这里悄悄改 |
| 124 | map.entry(target) |
| 125 | .or_default() |
| 126 | .inverse_of |
| 127 | .get_or_insert(source); |
| 128 | } |
| 129 | Ok(map) |
| 130 | } |
| 131 | |
| 132 | /// 主语不在谓词声明的 domain 里、或宾语不在 range 里的活事实(#190 / #196)。 |
| 133 | /// |
| 134 | /// 这是签名检查在**账本层**的那一半:抽取与采纳在写入时按 `ontology::judge_direction` |
| 135 | /// 掰正或留空,但合并会换掉主语、本体会事后改 domain,写入时的守卫挡不住写入之后 |
| 136 | /// 的改动。所以这里对着库量一遍,任何一条路写反了都在 Review 里看得见。 |
| 137 | /// |
| 138 | /// **没有类型的实体不算**:它没有类型可比,「不知道」不是「不符合」——按 0009, |
| 139 | /// 未分类是一种诚实的状态,不该因此被报成矛盾。声明了 domain / range 的谓词才查, |
| 140 | /// 与其它四类同一条纪律:没有公理就没有判据。 |
| 141 | /// |
| 142 | /// `only` 给了就只看这些事实(合并之后对搬动过的那几条立刻查);None 是全量。 |
| 143 | pub async fn signature_breaks( |
| 144 | pool: &PgPool, |
| 145 | kb_id: Uuid, |
| 146 | only: Option<&[Uuid]>, |
| 147 | ) -> AppResult<Vec<Uuid>> { |
| 148 | let rows: Vec<(Uuid,)> = sqlx::query_as( |
| 149 | "WITH RECURSIVE anc(type_id, anc_id) AS ( |
| 150 | SELECT id, id FROM entity_types WHERE kb_id = $1 |
| 151 | UNION |
| 152 | SELECT a.type_id, p.parent_id |
| 153 | FROM anc a JOIN entity_type_parents p ON p.child_id = a.anc_id |
| 154 | ) |
| 155 | SELECT f.id |
| 156 | FROM facts f |
| 157 | JOIN relation_types r ON r.id = f.predicate_id |
| 158 | JOIN entities s ON s.id = f.subject_id |
| 159 | JOIN entities o ON o.id = f.object_id |
| 160 | WHERE f.kb_id = $1 AND f.invalidated_at IS NULL |
| 161 | AND ($2::uuid[] IS NULL OR f.id = ANY($2)) |
| 162 | AND ( |
| 163 | (s.type_id IS NOT NULL |
| 164 | AND EXISTS (SELECT 1 FROM relation_type_domains d WHERE d.relation_type_id = r.id) |
| 165 | AND NOT EXISTS (SELECT 1 FROM relation_type_domains d |
| 166 | JOIN anc a ON a.anc_id = d.entity_type_id |
| 167 | WHERE d.relation_type_id = r.id AND a.type_id = s.type_id)) |
| 168 | OR |
| 169 | (o.type_id IS NOT NULL |
| 170 | AND EXISTS (SELECT 1 FROM relation_type_ranges g WHERE g.relation_type_id = r.id) |
| 171 | AND NOT EXISTS (SELECT 1 FROM relation_type_ranges g |
| 172 | JOIN anc a ON a.anc_id = g.entity_type_id |
| 173 | WHERE g.relation_type_id = r.id AND a.type_id = o.type_id)) |
| 174 | ) |
| 175 | ORDER BY f.recorded_at", |
| 176 | ) |
| 177 | .bind(kb_id) |
| 178 | .bind(only) |
| 179 | .fetch_all(pool) |
| 180 | .await?; |
| 181 | Ok(rows.into_iter().map(|(id,)| id).collect()) |
| 182 | } |
| 183 | |
| 184 | /// 把签名违规落进 `axiom_violations`(kind = `signature`,left 与 right 同一条事实)。 |
| 185 | /// 幂等:同一条事实重复报不重复入库。返回新插入的条数。 |
| 186 | pub async fn record_signature_breaks( |
| 187 | pool: &PgPool, |
| 188 | kb_id: Uuid, |
| 189 | facts: &[Uuid], |
| 190 | ) -> AppResult<usize> { |
| 191 | let mut inserted = 0usize; |
| 192 | for fact in facts { |
| 193 | let id: Option<(Uuid,)> = sqlx::query_as( |
| 194 | "INSERT INTO axiom_violations (id, kb_id, kind, left_fact, right_fact) |
| 195 | VALUES ($1, $2, 'signature', $3, $3) |
| 196 | ON CONFLICT (kb_id, kind, left_fact, right_fact) DO NOTHING |
| 197 | RETURNING id", |
| 198 | ) |
| 199 | .bind(Uuid::now_v7()) |
| 200 | .bind(kb_id) |
| 201 | .bind(fact) |
| 202 | .fetch_optional(pool) |
| 203 | .await?; |
| 204 | if id.is_some() { |
| 205 | inserted += 1; |
| 206 | } |
| 207 | } |
| 208 | Ok(inserted) |
| 209 | } |
| 210 | |
| 211 | /// 跑一遍检查,把结果落库。 |
| 212 | pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> { |
| 213 | let (timed, spans, _) = timed_edges(pool, kb_id).await?; |
| 214 | let edges: Vec<Edge> = timed.iter().map(|t| t.edge).collect(); |
| 215 | let axioms = axioms(pool, kb_id).await?; |
| 216 | let mut violations = check(&edges, &axioms); |
| 217 | // 第五类不在纯逻辑引擎里:它要看实体的类型与谓词的 domain / range,那是库里的 |
| 218 | // 东西。算出来后与其它四类走同一条落库与清陈规矩 |
| 219 | for fact in signature_breaks(pool, kb_id, None).await? { |
| 220 | violations.push(Violation { |
| 221 | kind: Kind::Signature, |
| 222 | left: fact, |
| 223 | right: fact, |
| 224 | path: Vec::new(), |
| 225 | }); |
| 226 | } |
| 227 | |
| 228 | // 第六类(0017):推出来却落不了地的派生。与 `materialize` 用同一个函数算, |
| 229 | // 所以这里报的正是那边拦下的——两边各算一套的话,队列会跟图对不上 |
| 230 | let derivation = utopia_reason::derive::derive(&timed, &axioms); |
| 231 | let clashes = utopia_reason::derive::contradictions(&derivation, &timed, &axioms, &spans); |
| 232 | let names = names_for(pool, &derivation, &clashes).await?; |
| 233 | let mut details: HashMap<(Uuid, Uuid), serde_json::Value> = HashMap::new(); |
| 234 | let mut per_pred: HashMap<Uuid, usize> = HashMap::new(); |
| 235 | let mut contradictions_capped = 0usize; |
| 236 | for c in &clashes.with_assertions { |
| 237 | let d = &derivation.facts[c.derived]; |
| 238 | let Some(&last) = d.premises.last() else { |
| 239 | continue; |
| 240 | }; |
| 241 | let key = (c.against, last); |
| 242 | if details.contains_key(&key) { |
| 243 | continue; |
| 244 | } |
| 245 | let n = per_pred.entry(d.predicate).or_default(); |
| 246 | if *n >= MAX_CLASHES_PER_PREDICATE { |
| 247 | contradictions_capped += 1; |
| 248 | continue; |
| 249 | } |
| 250 | *n += 1; |
| 251 | let span = utopia_reason::derive::validity(&d.premises, &spans); |
| 252 | details.insert( |
| 253 | key, |
| 254 | json!({ |
| 255 | "axiom": c.axiom.as_str(), |
| 256 | "rule": d.rule.as_str(), |
| 257 | "via": d.via, |
| 258 | "via_label": names.predicate(d.via), |
| 259 | "subject_id": d.subject, |
| 260 | "subject": names.entity(d.subject), |
| 261 | "predicate_id": d.predicate, |
| 262 | "predicate": names.predicate(d.predicate), |
| 263 | "object_id": d.object, |
| 264 | "object": names.entity(d.object), |
| 265 | "valid_from": span.and_then(|s| s.0).map(|t| stamp(t).to_rfc3339()), |
| 266 | "valid_to": span.and_then(|s| s.1).map(|t| stamp(t).to_rfc3339()), |
| 267 | "premises": d.premises, |
| 268 | }), |
| 269 | ); |
| 270 | violations.push(Violation { |
| 271 | kind: Kind::DerivedContradiction, |
| 272 | left: c.against, |
| 273 | right: last, |
| 274 | path: d.premises.clone(), |
| 275 | }); |
| 276 | } |
| 277 | |
| 278 | let mut report = Report { |
| 279 | edges: edges.len(), |
| 280 | predicates_with_axioms: axioms.len(), |
| 281 | found: violations.len(), |
| 282 | contradictions: details.len(), |
| 283 | contradictions_capped, |
| 284 | rules_disagree: clashes.between_derivations.len(), |
| 285 | ..Default::default() |
| 286 | }; |
| 287 | |
| 288 | // 事务里做,否则「插新的」与「清陈旧的」之间有个窗口,那一瞬间 Review 页 |
| 289 | // 会短暂地少东西 |
| 290 | let mut tx = pool.begin().await?; |
| 291 | let mut fresh: Vec<Uuid> = Vec::with_capacity(violations.len()); |
| 292 | for v in &violations { |
| 293 | let Violation { |
| 294 | kind, |
| 295 | left, |
| 296 | right, |
| 297 | path, |
| 298 | } = v; |
| 299 | let detail = details |
| 300 | .get(&(*left, *right)) |
| 301 | .cloned() |
| 302 | .unwrap_or_else(|| json!({})); |
| 303 | let id: Option<(Uuid,)> = sqlx::query_as( |
| 304 | "INSERT INTO axiom_violations (id, kb_id, kind, left_fact, right_fact, path, detail) |
| 305 | VALUES ($1, $2, $3, $4, $5, $6, $7) |
| 306 | ON CONFLICT (kb_id, kind, left_fact, right_fact) DO NOTHING |
| 307 | RETURNING id", |
| 308 | ) |
| 309 | .bind(Uuid::now_v7()) |
| 310 | .bind(kb_id) |
| 311 | .bind(kind.as_str()) |
| 312 | .bind(left) |
| 313 | .bind(right) |
| 314 | .bind(path) |
| 315 | .bind(&detail) |
| 316 | .fetch_optional(&mut *tx) |
| 317 | .await?; |
| 318 | if id.is_some() { |
| 319 | report.inserted += 1; |
| 320 | } |
| 321 | // 无论新插的还是本来就在的,都算「这一轮仍然成立」 |
| 322 | let keep: (Uuid,) = sqlx::query_as( |
| 323 | "SELECT id FROM axiom_violations |
| 324 | WHERE kb_id = $1 AND kind = $2 AND left_fact = $3 AND right_fact = $4", |
| 325 | ) |
| 326 | .bind(kb_id) |
| 327 | .bind(kind.as_str()) |
| 328 | .bind(left) |
| 329 | .bind(right) |
| 330 | .fetch_one(&mut *tx) |
| 331 | .await?; |
| 332 | fresh.push(keep.0); |
| 333 | } |
| 334 | |
| 335 | // 这一轮没算出来的 open 行是陈的:事实被撤了,或者公理放宽了。 |
| 336 | // resolved 的不动——那是人的决定,不是派生状态 |
| 337 | let cleared = sqlx::query( |
| 338 | "DELETE FROM axiom_violations |
| 339 | WHERE kb_id = $1 AND status = 'open' AND NOT (id = ANY($2))", |
| 340 | ) |
| 341 | .bind(kb_id) |
| 342 | .bind(&fresh) |
| 343 | .execute(&mut *tx) |
| 344 | .await?; |
| 345 | report.cleared = cleared.rows_affected() as usize; |
| 346 | |
| 347 | // 派生之间互撞的按规则对进 `ontology_defects`——根子是那两条声明,不是哪条事实。 |
| 348 | // 同一对谓词上可能有几种撞法(functional 与 asymmetric 各撞各的),唯一键只到 |
| 349 | // 谓词对,所以合成一行,几种撞法都写进 detail |
| 350 | let mut by_pair: HashMap<(Uuid, Uuid), Vec<serde_json::Value>> = HashMap::new(); |
| 351 | let mut order: Vec<(Uuid, Uuid)> = Vec::new(); |
| 352 | for rc in &clashes.between_derivations { |
| 353 | let triple = |i: usize| { |
| 354 | let d = &derivation.facts[i]; |
| 355 | format!( |
| 356 | "{} · {} · {}", |
| 357 | names.entity(d.subject), |
| 358 | names.predicate(d.predicate), |
| 359 | names.entity(d.object) |
| 360 | ) |
| 361 | }; |
| 362 | let examples: Vec<serde_json::Value> = rc |
| 363 | .pairs |
| 364 | .iter() |
| 365 | .take(3) |
| 366 | .map(|(i, j)| json!([triple(*i), triple(*j)])) |
| 367 | .collect(); |
| 368 | let key = (rc.a.0, rc.b.0); |
| 369 | if !by_pair.contains_key(&key) { |
| 370 | order.push(key); |
| 371 | } |
| 372 | by_pair.entry(key).or_default().push(json!({ |
| 373 | "rule_a": rc.a.1.as_str(), |
| 374 | "via_a": names.predicate(rc.a.0), |
| 375 | "rule_b": rc.b.1.as_str(), |
| 376 | "via_b": names.predicate(rc.b.0), |
| 377 | "axiom": rc.axiom.as_str(), |
| 378 | "count": rc.pairs.len(), |
| 379 | "examples": examples, |
| 380 | })); |
| 381 | } |
| 382 | let mut fresh_defects: Vec<Uuid> = Vec::with_capacity(order.len()); |
| 383 | for key in order { |
| 384 | let rules = by_pair.remove(&key).unwrap_or_default(); |
| 385 | let count: usize = rules |
| 386 | .iter() |
| 387 | .map(|r| r["count"].as_u64().unwrap_or(0) as usize) |
| 388 | .sum(); |
| 389 | // 已经有人认可过的那一行保持 resolved,只刷 detail:0017 说认可之后不再报 |
| 390 | let (id,): (Uuid,) = sqlx::query_as( |
| 391 | "INSERT INTO ontology_defects (id, kb_id, kind, subject, other, path, detail) |
| 392 | VALUES ($1, $2, 'rules_disagree', $3, $4, '{}', $5) |
| 393 | ON CONFLICT (kb_id, kind, subject, other) DO UPDATE SET detail = EXCLUDED.detail |
| 394 | RETURNING id", |
| 395 | ) |
| 396 | .bind(Uuid::now_v7()) |
| 397 | .bind(kb_id) |
| 398 | .bind(key.0) |
| 399 | .bind(key.1) |
| 400 | .bind(json!({ "count": count, "rules": rules })) |
| 401 | .fetch_one(&mut *tx) |
| 402 | .await?; |
| 403 | fresh_defects.push(id); |
| 404 | } |
| 405 | sqlx::query( |
| 406 | "DELETE FROM ontology_defects |
| 407 | WHERE kb_id = $1 AND kind = 'rules_disagree' AND status = 'open' |
| 408 | AND NOT (id = ANY($2))", |
| 409 | ) |
| 410 | .bind(kb_id) |
| 411 | .bind(&fresh_defects) |
| 412 | .execute(&mut *tx) |
| 413 | .await?; |
| 414 | tx.commit().await?; |
| 415 | Ok(report) |
| 416 | } |
| 417 | |
| 418 | /// 矛盾要写成人能读的话,而派生没有落库、没有文本可查——名字在这里补。 |
| 419 | struct Names { |
| 420 | entities: HashMap<Uuid, String>, |
| 421 | predicates: HashMap<Uuid, String>, |
| 422 | } |
| 423 | |
| 424 | impl Names { |
| 425 | fn entity(&self, id: Uuid) -> String { |
| 426 | self.entities |
| 427 | .get(&id) |
| 428 | .cloned() |
| 429 | .unwrap_or_else(|| "?".into()) |
| 430 | } |
| 431 | fn predicate(&self, id: Uuid) -> String { |
| 432 | self.predicates |
| 433 | .get(&id) |
| 434 | .cloned() |
| 435 | .unwrap_or_else(|| "?".into()) |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | async fn names_for( |
| 440 | pool: &PgPool, |
| 441 | derivation: &Derivation, |
| 442 | clashes: &Contradictions, |
| 443 | ) -> AppResult<Names> { |
| 444 | let mut ents: HashSet<Uuid> = HashSet::new(); |
| 445 | let mut preds: HashSet<Uuid> = HashSet::new(); |
| 446 | let mut want = |i: usize| { |
| 447 | let d = &derivation.facts[i]; |
| 448 | ents.insert(d.subject); |
| 449 | ents.insert(d.object); |
| 450 | preds.insert(d.predicate); |
| 451 | preds.insert(d.via); |
| 452 | }; |
| 453 | for c in &clashes.with_assertions { |
| 454 | want(c.derived); |
| 455 | } |
| 456 | for rc in &clashes.between_derivations { |
| 457 | for (i, j) in rc.pairs.iter().take(3) { |
| 458 | want(*i); |
| 459 | want(*j); |
| 460 | } |
| 461 | } |
| 462 | for rc in &clashes.between_derivations { |
| 463 | preds.insert(rc.a.0); |
| 464 | preds.insert(rc.b.0); |
| 465 | } |
| 466 | let ents: Vec<Uuid> = ents.into_iter().collect(); |
| 467 | let preds: Vec<Uuid> = preds.into_iter().collect(); |
| 468 | let entities: Vec<(Uuid, String)> = |
| 469 | sqlx::query_as("SELECT id, canonical_name FROM entities WHERE id = ANY($1)") |
| 470 | .bind(&ents) |
| 471 | .fetch_all(pool) |
| 472 | .await?; |
| 473 | let predicates: Vec<(Uuid, String)> = |
| 474 | sqlx::query_as("SELECT id, label FROM relation_types WHERE id = ANY($1)") |
| 475 | .bind(&preds) |
| 476 | .fetch_all(pool) |
| 477 | .await?; |
| 478 | Ok(Names { |
| 479 | entities: entities.into_iter().collect(), |
| 480 | predicates: predicates.into_iter().collect(), |
| 481 | }) |
| 482 | } |
| 483 | |
| 484 | /// Review 页要看的:还没人表态的违规,连同两条事实的三元组文本。 |
| 485 | /// |
| 486 | /// 展开成文本在 SQL 里做而不是回来再查一遍:一页几十条,每条两个三元组, |
| 487 | /// 分开查就是上百次往返。谓词用 `fact_surface_predicate` 兜底——本体里没有 |
| 488 | /// 对应关系的事实拿原文说法显示(见 `facts.predicate_id`)。 |
| 489 | pub async fn open_violations( |
| 490 | pool: &PgPool, |
| 491 | kb_id: Uuid, |
| 492 | limit: i64, |
| 493 | offset: i64, |
| 494 | ) -> AppResult<Vec<AxiomViolation>> { |
| 495 | Ok(sqlx::query_as( |
| 496 | "WITH triple AS ( |
| 497 | SELECT f.id, |
| 498 | s.canonical_name || ' · ' |
| 499 | || COALESCE(r.label, fact_surface_predicate(f.id), '?') || ' · ' |
| 500 | || COALESCE(o.canonical_name, f.object_value ->> 'summary', |
| 501 | f.object_value #>> '{}', '?') AS text, |
| 502 | r.label AS predicate |
| 503 | FROM facts f |
| 504 | JOIN entities s ON s.id = f.subject_id |
| 505 | LEFT JOIN relation_types r ON r.id = f.predicate_id |
| 506 | LEFT JOIN entities o ON o.id = f.object_id |
| 507 | WHERE f.kb_id = $1 |
| 508 | ) |
| 509 | SELECT v.id, v.kind, l.predicate, |
| 510 | v.left_fact, l.text AS left_text, |
| 511 | v.right_fact, rt.text AS right_text, |
| 512 | coalesce(array_length(v.path, 1), 0) AS path_len, |
| 513 | v.detected_at, v.detail, |
| 514 | lf.valid_to IS NULL AS left_open, |
| 515 | lf.confidence AS left_confidence, |
| 516 | EXISTS ( |
| 517 | SELECT 1 FROM entities e |
| 518 | JOIN entities x ON x.kb_id = e.kb_id AND x.id <> e.id |
| 519 | AND x.merged_into IS NULL |
| 520 | AND lower(x.canonical_name) = lower(e.canonical_name) |
| 521 | WHERE e.id IN (lf.subject_id, lf.object_id) |
| 522 | ) AS same_name_peers |
| 523 | FROM axiom_violations v |
| 524 | JOIN triple l ON l.id = v.left_fact |
| 525 | JOIN triple rt ON rt.id = v.right_fact |
| 526 | JOIN facts lf ON lf.id = v.left_fact |
| 527 | WHERE v.kb_id = $1 AND v.status = 'open' |
| 528 | ORDER BY v.detected_at DESC |
| 529 | LIMIT $2 OFFSET $3", |
| 530 | ) |
| 531 | .bind(kb_id) |
| 532 | .bind(limit) |
| 533 | .bind(offset) |
| 534 | .fetch_all(pool) |
| 535 | .await? |
| 536 | .into_iter() |
| 537 | .map(|r: ViolationRow| { |
| 538 | let hint = if r.kind == "derived_contradiction" { |
| 539 | hint_for(&r).map(String::from) |
| 540 | } else { |
| 541 | None |
| 542 | }; |
| 543 | AxiomViolation { |
| 544 | id: r.id, |
| 545 | kind: r.kind, |
| 546 | predicate: r.predicate, |
| 547 | left_fact: r.left_fact, |
| 548 | left_text: r.left_text, |
| 549 | right_fact: r.right_fact, |
| 550 | right_text: r.right_text, |
| 551 | path_len: r.path_len, |
| 552 | detected_at: r.detected_at, |
| 553 | detail: r.detail, |
| 554 | hint, |
| 555 | } |
| 556 | }) |
| 557 | .collect()) |
| 558 | } |
| 559 | |
| 560 | #[derive(sqlx::FromRow)] |
| 561 | struct ViolationRow { |
| 562 | id: Uuid, |
| 563 | kind: String, |
| 564 | predicate: Option<String>, |
| 565 | left_fact: Uuid, |
| 566 | left_text: String, |
| 567 | right_fact: Uuid, |
| 568 | right_text: String, |
| 569 | path_len: i32, |
| 570 | detected_at: chrono::DateTime<chrono::Utc>, |
| 571 | detail: serde_json::Value, |
| 572 | left_open: bool, |
| 573 | left_confidence: f32, |
| 574 | same_name_peers: bool, |
| 575 | } |
| 576 | |
| 577 | /// 线索按最常见的错法排(0017 §2):旧断言没写结束日期、两个同名实体、抽取本来就 |
| 578 | /// 没把握。一次只给一条——三条并列等于没给 |
| 579 | fn hint_for(r: &ViolationRow) -> Option<&'static str> { |
| 580 | if r.left_open && r.detail.get("valid_from").is_some_and(|v| !v.is_null()) { |
| 581 | Some("stale") |
| 582 | } else if r.same_name_peers { |
| 583 | Some("duplicate") |
| 584 | } else if r.left_confidence < 0.75 { |
| 585 | Some("unsure") |
| 586 | } else { |
| 587 | None |
| 588 | } |
| 589 | } |
| 590 | |
| 591 | /// 人裁决一处违规。 |
| 592 | /// |
| 593 | /// **三个出路,不是两个。** 时态冲突问「哪条对」,而这里可能是定义错了—— |
| 594 | /// 用户导的本体把某个属性声明成反对称,而他自己的语料里那关系其实双向。 |
| 595 | /// `axiom_relaxed` 记的就是这种:该改的是本体,不是二十条事实。 |
| 596 | /// |
| 597 | /// 改状态不删行,与账本同一个规矩:表过态这件事本身要留痕,而且 `run` 靠 |
| 598 | /// `status = 'open'` 判断哪些是派生的、可以重算掉——人的决定必须活过重跑。 |
| 599 | pub async fn decide( |
| 600 | pool: &PgPool, |
| 601 | kb_id: Uuid, |
| 602 | violation_id: Uuid, |
| 603 | resolution: &str, |
| 604 | actor: Uuid, |
| 605 | ) -> AppResult<()> { |
| 606 | let res = sqlx::query( |
| 607 | "UPDATE axiom_violations |
| 608 | SET status = 'resolved', resolution = $3, decided_by = $4, decided_at = now() |
| 609 | WHERE id = $2 AND kb_id = $1 AND status = 'open'", |
| 610 | ) |
| 611 | .bind(kb_id) |
| 612 | .bind(violation_id) |
| 613 | .bind(resolution) |
| 614 | .bind(actor) |
| 615 | .execute(pool) |
| 616 | .await?; |
| 617 | if res.rows_affected() == 0 { |
| 618 | return Err(utopia_core::AppError::NotFound); |
| 619 | } |
| 620 | Ok(()) |
| 621 | } |
| 622 | |
| 623 | // ===================== R0 的另一半:本体自己 ===================== |
| 624 | |
| 625 | /// 本体自洽性检查的产出。 |
| 626 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 627 | pub struct OntologyReport { |
| 628 | pub classes: usize, |
| 629 | pub found: usize, |
| 630 | pub inserted: usize, |
| 631 | pub cleared: usize, |
| 632 | } |
| 633 | |
| 634 | /// 量一遍本体自己:谓词的公理组合、subClassOf 的环、不可满足的类。 |
| 635 | /// |
| 636 | /// 与 [`run`] 同一套重跑规矩:`open` 是派生状态、可以被重算掉,`resolved` |
| 637 | /// 是人的决定、一行不动。 |
| 638 | pub async fn check_ontology(pool: &PgPool, kb_id: Uuid) -> AppResult<OntologyReport> { |
| 639 | let ax = axioms(pool, kb_id).await?; |
| 640 | let parents: Vec<(Uuid, Uuid)> = sqlx::query_as( |
| 641 | "SELECT child_id, parent_id FROM entity_type_parents p |
| 642 | JOIN entity_types t ON t.id = p.child_id |
| 643 | WHERE t.kb_id = $1", |
| 644 | ) |
| 645 | .bind(kb_id) |
| 646 | .fetch_all(pool) |
| 647 | .await?; |
| 648 | let disjoint: Vec<(Uuid, Uuid)> = |
| 649 | sqlx::query_as("SELECT a_id, b_id FROM entity_type_disjoint WHERE kb_id = $1") |
| 650 | .bind(kb_id) |
| 651 | .fetch_all(pool) |
| 652 | .await?; |
| 653 | let classes: i64 = sqlx::query_scalar("SELECT count(*) FROM entity_types WHERE kb_id = $1") |
| 654 | .bind(kb_id) |
| 655 | .fetch_one(pool) |
| 656 | .await?; |
| 657 | |
| 658 | let defects = utopia_reason::ontology::check_ontology(&ax, &parents, &disjoint); |
| 659 | let mut report = OntologyReport { |
| 660 | classes: classes as usize, |
| 661 | found: defects.len(), |
| 662 | ..Default::default() |
| 663 | }; |
| 664 | |
| 665 | let mut tx = pool.begin().await?; |
| 666 | let mut fresh: Vec<Uuid> = Vec::with_capacity(defects.len()); |
| 667 | for d in &defects { |
| 668 | let existing: Option<(Uuid,)> = sqlx::query_as( |
| 669 | "SELECT id FROM ontology_defects |
| 670 | WHERE kb_id = $1 AND kind = $2 AND subject = $3 |
| 671 | AND other IS NOT DISTINCT FROM $4", |
| 672 | ) |
| 673 | .bind(kb_id) |
| 674 | .bind(d.kind.as_str()) |
| 675 | .bind(d.subject) |
| 676 | .bind(d.other) |
| 677 | .fetch_optional(&mut *tx) |
| 678 | .await?; |
| 679 | let id = match existing { |
| 680 | Some((id,)) => id, |
| 681 | None => { |
| 682 | let id = Uuid::now_v7(); |
| 683 | sqlx::query( |
| 684 | "INSERT INTO ontology_defects (id, kb_id, kind, subject, other, path) |
| 685 | VALUES ($1, $2, $3, $4, $5, $6)", |
| 686 | ) |
| 687 | .bind(id) |
| 688 | .bind(kb_id) |
| 689 | .bind(d.kind.as_str()) |
| 690 | .bind(d.subject) |
| 691 | .bind(d.other) |
| 692 | .bind(&d.path) |
| 693 | .execute(&mut *tx) |
| 694 | .await?; |
| 695 | report.inserted += 1; |
| 696 | id |
| 697 | } |
| 698 | }; |
| 699 | fresh.push(id); |
| 700 | } |
| 701 | let cleared = sqlx::query( |
| 702 | "DELETE FROM ontology_defects |
| 703 | WHERE kb_id = $1 AND status = 'open' AND kind <> 'rules_disagree' |
| 704 | AND NOT (id = ANY($2))", |
| 705 | ) |
| 706 | .bind(kb_id) |
| 707 | .bind(&fresh) |
| 708 | .execute(&mut *tx) |
| 709 | .await?; |
| 710 | report.cleared = cleared.rows_affected() as usize; |
| 711 | tx.commit().await?; |
| 712 | Ok(report) |
| 713 | } |
| 714 | |
| 715 | // ===================== R1:物化推导 ===================== |
| 716 | |
| 717 | /// 一次推导的产出。 |
| 718 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 719 | pub struct DeriveReport { |
| 720 | /// 编译出来的规则条数。**为零时结论是「没有规则」而不是「推不出东西」** |
| 721 | pub rules: usize, |
| 722 | pub edges: usize, |
| 723 | /// 这一轮算出来的派生总数 |
| 724 | pub derived: usize, |
| 725 | /// 新落库的 |
| 726 | pub inserted: usize, |
| 727 | /// 前提没了、跟着作废的 |
| 728 | pub invalidated: usize, |
| 729 | /// 撞上单谓词上限、没推完的谓词个数 |
| 730 | pub capped: usize, |
| 731 | /// **推出来了却找不到对应规则行的条数。正常应当恒为零。** |
| 732 | /// |
| 733 | /// 不为零意味着规则编译与推导对不上了。之前这里是一句 `continue`, |
| 734 | /// 于是 `ceo_of ⊑ works_at` 推出的那条 `works_at` 事实**推出来了却不落库**, |
| 735 | /// 而下游靠它推出的 `employs` 反倒进了库——一条派生的前提凭空消失。 |
| 736 | /// 数出来,别再让它静默一次 |
| 737 | pub unruled: usize, |
| 738 | /// 推出来了却撞上断言或别的派生、这一轮拦下没落的(0017)。**拦下的每一条 |
| 739 | /// 都在 Review 里有对应的一行**——`run` 与这里用同一个函数算 |
| 740 | pub blocked: usize, |
| 741 | } |
| 742 | |
| 743 | /// 一次取数,三样东西:带区间的边、每条事实的区间、精度与置信度。 |
| 744 | /// `run` 与 `materialize` 共用——两边看到的边必须是同一批 |
| 745 | type TimedEdges = ( |
| 746 | Vec<TimedEdge>, |
| 747 | HashMap<Uuid, (Option<i64>, Option<i64>)>, |
| 748 | HashMap<Uuid, (Option<String>, Option<String>, f32)>, |
| 749 | ); |
| 750 | |
| 751 | async fn timed_edges(pool: &PgPool, kb_id: Uuid) -> AppResult<TimedEdges> { |
| 752 | // 输入**只有断言**。派生住在另一张表,所以这里连过滤都不必写——那正是 |
| 753 | // 分表买到的东西:忘了排除的后果是推不出东西,不是把自己的输出喂回自己 |
| 754 | let rows: Vec<EdgeRow> = sqlx::query_as( |
| 755 | "SELECT id, predicate_id, subject_id, object_id, |
| 756 | valid_from, valid_to, valid_from_precision, valid_to_precision, confidence |
| 757 | FROM facts |
| 758 | WHERE kb_id = $1 |
| 759 | AND invalidated_at IS NULL |
| 760 | AND predicate_id IS NOT NULL |
| 761 | AND object_id IS NOT NULL", |
| 762 | ) |
| 763 | .bind(kb_id) |
| 764 | .fetch_all(pool) |
| 765 | .await?; |
| 766 | |
| 767 | let mut edges = Vec::with_capacity(rows.len()); |
| 768 | let mut meta: HashMap<Uuid, (Option<String>, Option<String>, f32)> = HashMap::new(); |
| 769 | let mut spans: HashMap<Uuid, (Option<i64>, Option<i64>)> = HashMap::new(); |
| 770 | for (id, pred, subj, obj, from, to, fp, tp, conf) in rows { |
| 771 | let (f, t) = (from.map(|x| x.timestamp()), to.map(|x| x.timestamp())); |
| 772 | edges.push(TimedEdge { |
| 773 | edge: Edge { |
| 774 | fact: id, |
| 775 | predicate: pred, |
| 776 | subject: subj, |
| 777 | object: obj, |
| 778 | }, |
| 779 | from: f, |
| 780 | to: t, |
| 781 | }); |
| 782 | spans.insert(id, (f, t)); |
| 783 | meta.insert(id, (fp, tp, conf)); |
| 784 | } |
| 785 | Ok((edges, spans, meta)) |
| 786 | } |
| 787 | |
| 788 | /// 人认可过并存的(派生三元组, 断言)对:这些派生下一轮照常落地(0017 §2)。 |
| 789 | async fn accepted_clashes( |
| 790 | pool: &PgPool, |
| 791 | kb_id: Uuid, |
| 792 | ) -> AppResult<HashSet<(Uuid, Uuid, Uuid, Uuid)>> { |
| 793 | let rows: Vec<(Uuid, serde_json::Value)> = sqlx::query_as( |
| 794 | "SELECT left_fact, detail FROM axiom_violations |
| 795 | WHERE kb_id = $1 AND kind = 'derived_contradiction' AND resolution = 'accepted'", |
| 796 | ) |
| 797 | .bind(kb_id) |
| 798 | .fetch_all(pool) |
| 799 | .await?; |
| 800 | let id = |v: &serde_json::Value, k: &str| { |
| 801 | v.get(k) |
| 802 | .and_then(|x| x.as_str()) |
| 803 | .and_then(|s| s.parse::<Uuid>().ok()) |
| 804 | }; |
| 805 | Ok(rows |
| 806 | .into_iter() |
| 807 | .filter_map(|(against, d)| { |
| 808 | Some(( |
| 809 | id(&d, "subject_id")?, |
| 810 | id(&d, "predicate_id")?, |
| 811 | id(&d, "object_id")?, |
| 812 | against, |
| 813 | )) |
| 814 | }) |
| 815 | .collect()) |
| 816 | } |
| 817 | |
| 818 | /// 派生事实的身份:三元组 + 区间。 |
| 819 | /// |
| 820 | /// **区间进键**是有意的:区间变了就是另一条断言,老的作废、新的落地, |
| 821 | /// 因为账本不许原地改。 |
| 822 | type DerivedKey = (Uuid, Uuid, Uuid, Option<i64>, Option<i64>); |
| 823 | |
| 824 | /// 精度按「最粗的那个」取。 |
| 825 | /// |
| 826 | /// 派生区间的两端各来自某一条前提,严格说该各随各的精度。取最粗是**故意保守**: |
| 827 | /// 一条链只和它最不确定的那一环一样可信,而把 year 级的前提推出来的结论标成 |
| 828 | /// day,正是 `facts.valid_from_precision` 那条注释里说的「在无知的地方填一个 |
| 829 | /// 确定的值」。 |
| 830 | fn coarsest(a: Option<&str>, b: Option<&str>) -> Option<String> { |
| 831 | let rank = |p: &str| match p { |
| 832 | "year" => 0, |
| 833 | "month" => 1, |
| 834 | _ => 2, |
| 835 | }; |
| 836 | match (a, b) { |
| 837 | (Some(x), Some(y)) => Some(if rank(x) <= rank(y) { x } else { y }.to_string()), |
| 838 | (Some(x), None) | (None, Some(x)) => Some(x.to_string()), |
| 839 | (None, None) => None, |
| 840 | } |
| 841 | } |
| 842 | |
| 843 | /// 按本体公理重编译规则,返回 `(谓词, 种类) → 规则 id`。 |
| 844 | /// |
| 845 | /// **幂等**:身份取 `(kb, 谓词, 种类)`,重编译认得出「还是那条规则」——否则每跑 |
| 846 | /// 一次 `derived_facts.rule_id` 就指向一个新 id,历史全断。 |
| 847 | /// |
| 848 | /// **公理撤了的规则不删。** 已失效的派生行仍指着它,解释「当时是靠哪条规则推的」 |
| 849 | /// 需要它还在;而它不再出现在返回值里,据它推出来的事实由下面的对账作废。 |
| 850 | /// 规则一个库也就几条,留着不占地方。 |
| 851 | async fn compile_rules( |
| 852 | pool: &PgPool, |
| 853 | kb_id: Uuid, |
| 854 | ax: &HashMap<Uuid, Axioms>, |
| 855 | ) -> AppResult<HashMap<(Uuid, RuleKind), Uuid>> { |
| 856 | let mut want: Vec<(Uuid, RuleKind)> = Vec::new(); |
| 857 | for (&pred, a) in ax { |
| 858 | if a.transitive { |
| 859 | want.push((pred, "transitive")); |
| 860 | } |
| 861 | if a.symmetric { |
| 862 | want.push((pred, "symmetric")); |
| 863 | } |
| 864 | // 后两种是迁移 0016(a_relation_can_name_its_inverse)补上的规则源。**规则挂在「有声明的那一侧」**—— |
| 865 | // 归一化过的逆两边都有声明,所以两个方向各得一条规则,与它们各自 |
| 866 | // 推出的派生对得上 |
| 867 | if a.inverse_of.is_some() { |
| 868 | want.push((pred, "inverse")); |
| 869 | } |
| 870 | if a.sub_property_of.is_some() { |
| 871 | want.push((pred, "sub_property")); |
| 872 | } |
| 873 | } |
| 874 | want.sort(); |
| 875 | let mut out = HashMap::new(); |
| 876 | for (pred, kind) in want { |
| 877 | sqlx::query( |
| 878 | "INSERT INTO rules (id, kb_id, predicate_id, kind) VALUES ($1, $2, $3, $4) |
| 879 | ON CONFLICT (kb_id, predicate_id, kind) DO NOTHING", |
| 880 | ) |
| 881 | .bind(Uuid::now_v7()) |
| 882 | .bind(kb_id) |
| 883 | .bind(pred) |
| 884 | .bind(kind) |
| 885 | .execute(pool) |
| 886 | .await?; |
| 887 | let (id,): (Uuid,) = sqlx::query_as( |
| 888 | "SELECT id FROM rules WHERE kb_id = $1 AND predicate_id = $2 AND kind = $3", |
| 889 | ) |
| 890 | .bind(kb_id) |
| 891 | .bind(pred) |
| 892 | .bind(kind) |
| 893 | .fetch_one(pool) |
| 894 | .await?; |
| 895 | out.insert((pred, kind), id); |
| 896 | } |
| 897 | Ok(out) |
| 898 | } |
| 899 | |
| 900 | /// 取边时一并拿回来的随行信息(精度与置信度,落库要用)。 |
| 901 | type EdgeRow = ( |
| 902 | Uuid, |
| 903 | Uuid, |
| 904 | Uuid, |
| 905 | Uuid, |
| 906 | Option<chrono::DateTime<chrono::Utc>>, |
| 907 | Option<chrono::DateTime<chrono::Utc>>, |
| 908 | Option<String>, |
| 909 | Option<String>, |
| 910 | f32, |
| 911 | ); |
| 912 | |
| 913 | type LiveRow = ( |
| 914 | Uuid, |
| 915 | Uuid, |
| 916 | Uuid, |
| 917 | Uuid, |
| 918 | Option<chrono::DateTime<chrono::Utc>>, |
| 919 | Option<chrono::DateTime<chrono::Utc>>, |
| 920 | ); |
| 921 | |
| 922 | /// 推一遍,把派生事实落进账本。 |
| 923 | /// |
| 924 | /// **调用方负责检查 `materialize_inferences` 开关。** 这一层不判——它也被 |
| 925 | /// 「预览一下会推出什么」那条路用,而预览不该受开关约束。 |
| 926 | pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport> { |
| 927 | let ax = axioms(pool, kb_id).await?; |
| 928 | let rules = compile_rules(pool, kb_id, &ax).await?; |
| 929 | let (edges, spans, meta) = timed_edges(pool, kb_id).await?; |
| 930 | |
| 931 | let derivation = utopia_reason::derive::derive(&edges, &ax); |
| 932 | // asserted > derived 是硬性的(0002):撞上断言的派生不落地。人认可过并存的 |
| 933 | // 除外;派生之间互撞的两边都不落,认可与否只影响报不报(0017) |
| 934 | let clashes = utopia_reason::derive::contradictions(&derivation, &edges, &ax, &spans); |
| 935 | let accepted = accepted_clashes(pool, kb_id).await?; |
| 936 | let mut blocked: HashSet<usize> = HashSet::new(); |
| 937 | for c in &clashes.with_assertions { |
| 938 | let d = &derivation.facts[c.derived]; |
| 939 | if !accepted.contains(&(d.subject, d.predicate, d.object, c.against)) { |
| 940 | blocked.insert(c.derived); |
| 941 | } |
| 942 | } |
| 943 | for rc in &clashes.between_derivations { |
| 944 | for (i, j) in &rc.pairs { |
| 945 | blocked.insert(*i); |
| 946 | blocked.insert(*j); |
| 947 | } |
| 948 | } |
| 949 | let mut report = DeriveReport { |
| 950 | rules: rules.len(), |
| 951 | edges: edges.len(), |
| 952 | derived: derivation.facts.len(), |
| 953 | capped: derivation.capped.len(), |
| 954 | blocked: blocked.len(), |
| 955 | ..Default::default() |
| 956 | }; |
| 957 | |
| 958 | let mut wanted: HashMap<DerivedKey, &utopia_reason::derive::Derived> = HashMap::new(); |
| 959 | for (i, d) in derivation.facts.iter().enumerate() { |
| 960 | if blocked.contains(&i) { |
| 961 | continue; |
| 962 | } |
| 963 | let Some((from, to)) = utopia_reason::derive::validity(&d.premises, &spans) else { |
| 964 | continue; |
| 965 | }; |
| 966 | wanted.insert((d.subject, d.predicate, d.object, from, to), d); |
| 967 | } |
| 968 | |
| 969 | let mut tx = pool.begin().await?; |
| 970 | let live: Vec<LiveRow> = sqlx::query_as( |
| 971 | "SELECT id, subject_id, predicate_id, object_id, valid_from, valid_to |
| 972 | FROM derived_facts |
| 973 | WHERE kb_id = $1 AND invalidated_at IS NULL", |
| 974 | ) |
| 975 | .bind(kb_id) |
| 976 | .fetch_all(&mut *tx) |
| 977 | .await?; |
| 978 | |
| 979 | let mut stale: Vec<Uuid> = Vec::new(); |
| 980 | for (id, s, p, o, from, to) in &live { |
| 981 | let key = ( |
| 982 | *s, |
| 983 | *p, |
| 984 | *o, |
| 985 | from.map(|x| x.timestamp()), |
| 986 | to.map(|x| x.timestamp()), |
| 987 | ); |
| 988 | if wanted.remove(&key).is_none() { |
| 989 | stale.push(*id); |
| 990 | } |
| 991 | } |
| 992 | |
| 993 | // 前提没了 → 派生跟着失效。**置 invalidated_at 而不是删**:与拒绝一条事实 |
| 994 | // 完全同构,记录轴上留下「我们曾据此推出,后来前提没了」,实体历史页面 |
| 995 | // 直接就能展示(0002 第 3 节) |
| 996 | if !stale.is_empty() { |
| 997 | sqlx::query("UPDATE derived_facts SET invalidated_at = now() WHERE id = ANY($1)") |
| 998 | .bind(&stale) |
| 999 | .execute(&mut *tx) |
| 1000 | .await?; |
| 1001 | report.invalidated = stale.len(); |
| 1002 | } |
| 1003 | |
| 1004 | for ((subject, predicate, object, from, to), d) in wanted { |
| 1005 | // **按 `via` 查,不是 `predicate`。** 规则行是给「声明了公理的那个 |
| 1006 | // 谓词」编的;跨谓词的两条规则里,派生出来的谓词是另一个。 |
| 1007 | // 原先按 predicate 查,前两条规则一直对(两者相同),加了 inverse / |
| 1008 | // sub_property 之后查不到规则就 `continue`——推出来了却不落库 |
| 1009 | let Some(&rule_id) = rules.get(&(d.via, d.rule.as_str())) else { |
| 1010 | // 查不到规则是**编译与推导不一致**,不是正常情况。数出来, |
| 1011 | // 别再让它静默消失一次 |
| 1012 | report.unruled += 1; |
| 1013 | continue; |
| 1014 | }; |
| 1015 | // 精度与置信度都取前提里最保守的那一个 |
| 1016 | let mut fp: Option<String> = None; |
| 1017 | let mut tp: Option<String> = None; |
| 1018 | let mut conf = 1.0f32; |
| 1019 | for p in &d.premises { |
| 1020 | if let Some((pf, pt, pc)) = meta.get(p) { |
| 1021 | fp = coarsest(fp.as_deref(), pf.as_deref()); |
| 1022 | tp = coarsest(tp.as_deref(), pt.as_deref()); |
| 1023 | conf = conf.min(*pc); |
| 1024 | } |
| 1025 | } |
| 1026 | // 约束是「有日期才有精度」——交集把某一端算成无界时,那一端的精度也得清掉 |
| 1027 | let fp = from.and(fp); |
| 1028 | let tp = to.and(tp); |
| 1029 | let id = Uuid::now_v7(); |
| 1030 | sqlx::query( |
| 1031 | "INSERT INTO derived_facts (id, kb_id, subject_id, predicate_id, object_id, |
| 1032 | valid_from, valid_to, |
| 1033 | valid_from_precision, valid_to_precision, |
| 1034 | confidence, rule_id) |
| 1035 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)", |
| 1036 | ) |
| 1037 | .bind(id) |
| 1038 | .bind(kb_id) |
| 1039 | .bind(subject) |
| 1040 | .bind(predicate) |
| 1041 | .bind(object) |
| 1042 | .bind(from.map(stamp)) |
| 1043 | .bind(to.map(stamp)) |
| 1044 | .bind(&fp) |
| 1045 | .bind(&tp) |
| 1046 | .bind(conf) |
| 1047 | .bind(rule_id) |
| 1048 | .execute(&mut *tx) |
| 1049 | .await?; |
| 1050 | for (seq, premise) in d.premises.iter().enumerate() { |
| 1051 | sqlx::query( |
| 1052 | "INSERT INTO fact_derivations (derived_fact_id, premise_fact_id, seq) |
| 1053 | VALUES ($1, $2, $3)", |
| 1054 | ) |
| 1055 | .bind(id) |
| 1056 | .bind(premise) |
| 1057 | .bind(seq as i32) |
| 1058 | .execute(&mut *tx) |
| 1059 | .await?; |
| 1060 | } |
| 1061 | report.inserted += 1; |
| 1062 | } |
| 1063 | tx.commit().await?; |
| 1064 | Ok(report) |
| 1065 | } |
| 1066 | |
| 1067 | fn stamp(secs: i64) -> chrono::DateTime<chrono::Utc> { |
| 1068 | chrono::DateTime::from_timestamp(secs, 0).unwrap_or_default() |
| 1069 | } |
| 1070 | |
| 1071 | /// Review 页要看的本体缺陷,连同标签。 |
| 1072 | /// |
| 1073 | /// 标签在 SQL 里取而不是回来再查:`subject` 那一列同一列指两张表(谓词或类), |
| 1074 | /// 分开查就要先按 kind 分组、再发两批查询,而一次 LEFT JOIN 两张表就够—— |
| 1075 | /// 一个 id 只可能命中其中一张。 |
| 1076 | pub async fn open_defects( |
| 1077 | pool: &PgPool, |
| 1078 | kb_id: Uuid, |
| 1079 | limit: i64, |
| 1080 | offset: i64, |
| 1081 | ) -> AppResult<Vec<OntologyDefect>> { |
| 1082 | Ok(sqlx::query_as( |
| 1083 | "SELECT d.id, d.kind, d.detail, |
| 1084 | COALESCE(st.label, sr.label) AS subject_label, |
| 1085 | COALESCE(ot.label, orr.label) AS other_label, |
| 1086 | COALESCE( |
| 1087 | (SELECT array_agg(t.label ORDER BY x.ord) |
| 1088 | FROM unnest(d.path) WITH ORDINALITY AS x(id, ord) |
| 1089 | JOIN entity_types t ON t.id = x.id), |
| 1090 | ARRAY[]::text[] |
| 1091 | ) AS path_labels, |
| 1092 | d.detected_at |
| 1093 | FROM ontology_defects d |
| 1094 | LEFT JOIN entity_types st ON st.id = d.subject |
| 1095 | LEFT JOIN relation_types sr ON sr.id = d.subject |
| 1096 | LEFT JOIN entity_types ot ON ot.id = d.other |
| 1097 | LEFT JOIN relation_types orr ON orr.id = d.other |
| 1098 | WHERE d.kb_id = $1 AND d.status = 'open' |
| 1099 | ORDER BY d.detected_at DESC |
| 1100 | LIMIT $2 OFFSET $3", |
| 1101 | ) |
| 1102 | .bind(kb_id) |
| 1103 | .bind(limit) |
| 1104 | .bind(offset) |
| 1105 | .fetch_all(pool) |
| 1106 | .await?) |
| 1107 | } |
| 1108 | |
| 1109 | /// 人对一处本体缺陷表态。 |
| 1110 | /// |
| 1111 | /// 两个出路而不是三个:本体缺陷没有「数据错了」这一条——它压根没看数据。 |
| 1112 | /// `fixed` 是「我去改了本体」,`accepted` 是「看过,不必改」。 |
| 1113 | pub async fn decide_defect( |
| 1114 | pool: &PgPool, |
| 1115 | kb_id: Uuid, |
| 1116 | defect_id: Uuid, |
| 1117 | resolution: &str, |
| 1118 | actor: Uuid, |
| 1119 | ) -> AppResult<()> { |
| 1120 | let res = sqlx::query( |
| 1121 | "UPDATE ontology_defects |
| 1122 | SET status = 'resolved', resolution = $3, decided_by = $4, decided_at = now() |
| 1123 | WHERE id = $2 AND kb_id = $1 AND status = 'open'", |
| 1124 | ) |
| 1125 | .bind(kb_id) |
| 1126 | .bind(defect_id) |
| 1127 | .bind(resolution) |
| 1128 | .bind(actor) |
| 1129 | .execute(pool) |
| 1130 | .await?; |
| 1131 | if res.rows_affected() == 0 { |
| 1132 | return Err(utopia_core::AppError::NotFound); |
| 1133 | } |
| 1134 | Ok(()) |
| 1135 | } |
| 1136 | |
| 1137 | /// 到点该重推的库。 |
| 1138 | /// |
| 1139 | /// 与来源同步同一个形状:一个间隔 + 一个上次时间。**从没推过的算到期**—— |
| 1140 | /// 刚打开开关的库不该等一个周期才第一次推。 |
| 1141 | pub async fn due_for_inference(pool: &PgPool) -> AppResult<Vec<Uuid>> { |
| 1142 | Ok(sqlx::query_scalar( |
| 1143 | "SELECT id FROM knowledge_bases |
| 1144 | WHERE materialize_inferences |
| 1145 | AND (last_inference_at IS NULL |
| 1146 | OR last_inference_at < now() |
| 1147 | - make_interval(mins => inference_interval_minutes))", |
| 1148 | ) |
| 1149 | .fetch_all(pool) |
| 1150 | .await?) |
| 1151 | } |
| 1152 | |
| 1153 | /// 记下这一轮推完的时间。 |
| 1154 | /// |
| 1155 | /// **推完就记,哪怕什么都没变**:这一列答的是「上次看过没有」,不是「上次改过 |
| 1156 | /// 没有」。不记的话没变化的库会每分钟被扫起来重算一遍。 |
| 1157 | pub async fn mark_inference_ran(pool: &PgPool, kb_id: Uuid) -> AppResult<()> { |
| 1158 | sqlx::query("UPDATE knowledge_bases SET last_inference_at = now() WHERE id = $1") |
| 1159 | .bind(kb_id) |
| 1160 | .execute(pool) |
| 1161 | .await?; |
| 1162 | Ok(()) |
| 1163 | } |
| 1164 | |
| 1165 | /// 一条派生事实的证明,展开到原句(0002 R2)。 |
| 1166 | /// |
| 1167 | /// `fact_derivations` 只记直接前提,而前提一律是断言,所以「递归展开」在这里 |
| 1168 | /// 退化成一条链:派生 → 按 `seq` 的断言 → 每条断言的证据。叶子是 chunk, |
| 1169 | /// 界面上一路点到文档。**撤了的前提照样列出并打上标记**:派生随前提失效, |
| 1170 | /// 但「当时靠的是什么」要读得出来,那正是记录轴存在的理由。 |
| 1171 | /// |
| 1172 | /// 派生已失效或不存在时回 None——不是错误,界面据此收起。 |
| 1173 | pub async fn proof( |
| 1174 | pool: &PgPool, |
| 1175 | kb_id: Uuid, |
| 1176 | derived_id: Uuid, |
| 1177 | ) -> AppResult<Option<utopia_core::models::Proof>> { |
| 1178 | let Some(derived) = derived_one(pool, kb_id, derived_id).await? else { |
| 1179 | return Ok(None); |
| 1180 | }; |
| 1181 | let premises: Vec<Uuid> = sqlx::query_scalar( |
| 1182 | "SELECT premise_fact_id FROM fact_derivations WHERE derived_fact_id = $1 ORDER BY seq", |
| 1183 | ) |
| 1184 | .bind(derived_id) |
| 1185 | .fetch_all(pool) |
| 1186 | .await?; |
| 1187 | let steps = steps_for(pool, &premises).await?; |
| 1188 | Ok(Some(utopia_core::models::Proof { derived, steps })) |
| 1189 | } |
| 1190 | |
| 1191 | /// 一串前提展开成证明的步:三元组、区间、撤没撤、证据。 |
| 1192 | /// |
| 1193 | /// 落了地的派生(`fact_derivations`)与没落地的(`axiom_violations.path`)都从这里 |
| 1194 | /// 走——前提是同一种东西,证明链没有理由长两个样 |
| 1195 | async fn steps_for( |
| 1196 | pool: &PgPool, |
| 1197 | premises: &[Uuid], |
| 1198 | ) -> AppResult<Vec<utopia_core::models::ProofStep>> { |
| 1199 | #[allow(clippy::type_complexity)] |
| 1200 | let rows: Vec<( |
| 1201 | i64, |
| 1202 | Uuid, |
| 1203 | Uuid, |
| 1204 | String, |
| 1205 | Option<Uuid>, |
| 1206 | Option<String>, |
| 1207 | Option<Uuid>, |
| 1208 | Option<String>, |
| 1209 | Option<chrono::DateTime<chrono::Utc>>, |
| 1210 | Option<chrono::DateTime<chrono::Utc>>, |
| 1211 | f32, |
| 1212 | bool, |
| 1213 | )> = sqlx::query_as( |
| 1214 | "SELECT x.ord - 1, f.id, f.subject_id, s.canonical_name, |
| 1215 | f.predicate_id, r.label, f.object_id, o.canonical_name, |
| 1216 | f.valid_from, f.valid_to, f.confidence, |
| 1217 | f.invalidated_at IS NOT NULL |
| 1218 | FROM unnest($1::uuid[]) WITH ORDINALITY AS x(id, ord) |
| 1219 | JOIN facts f ON f.id = x.id |
| 1220 | JOIN entities s ON s.id = f.subject_id |
| 1221 | LEFT JOIN relation_types r ON r.id = f.predicate_id |
| 1222 | LEFT JOIN entities o ON o.id = f.object_id |
| 1223 | ORDER BY x.ord", |
| 1224 | ) |
| 1225 | .bind(premises) |
| 1226 | .fetch_all(pool) |
| 1227 | .await?; |
| 1228 | let mut steps = Vec::with_capacity(rows.len()); |
| 1229 | for ( |
| 1230 | seq, |
| 1231 | fact_id, |
| 1232 | subject_id, |
| 1233 | subject, |
| 1234 | predicate_id, |
| 1235 | predicate, |
| 1236 | object_id, |
| 1237 | object, |
| 1238 | valid_from, |
| 1239 | valid_to, |
| 1240 | confidence, |
| 1241 | retracted, |
| 1242 | ) in rows |
| 1243 | { |
| 1244 | // 一条链最多 MAX_DEPTH 步,逐条取证据是可数的几次往返 |
| 1245 | let evidence = crate::graph::fact_evidence(pool, fact_id).await?; |
| 1246 | steps.push(utopia_core::models::ProofStep { |
| 1247 | seq: seq as i32, |
| 1248 | fact_id, |
| 1249 | subject_id, |
| 1250 | subject, |
| 1251 | predicate_id, |
| 1252 | predicate, |
| 1253 | object_id, |
| 1254 | object, |
| 1255 | valid_from, |
| 1256 | valid_to, |
| 1257 | confidence, |
| 1258 | retracted, |
| 1259 | evidence, |
| 1260 | }); |
| 1261 | } |
| 1262 | Ok(steps) |
| 1263 | } |
| 1264 | |
| 1265 | /// 没落地的派生里,与这个实体有关的那些(0017 §3)——面板「推出来的」一档的 |
| 1266 | /// 「没落地的」小节。 |
| 1267 | pub async fn blocked_for_entity( |
| 1268 | pool: &PgPool, |
| 1269 | kb_id: Uuid, |
| 1270 | entity_id: Uuid, |
| 1271 | ) -> AppResult<Vec<utopia_core::models::BlockedDerivation>> { |
| 1272 | Ok(sqlx::query_as( |
| 1273 | "SELECT v.id AS violation_id, |
| 1274 | (v.detail->>'subject_id')::uuid AS subject_id, |
| 1275 | COALESCE(v.detail->>'subject', '?') AS subject, |
| 1276 | (v.detail->>'object_id')::uuid AS object_id, |
| 1277 | COALESCE(v.detail->>'object', '?') AS object, |
| 1278 | COALESCE(v.detail->>'predicate', '?') AS predicate, |
| 1279 | COALESCE(v.detail->>'rule', '?') AS rule, |
| 1280 | COALESCE(v.detail->>'via_label', '?') AS via_label, |
| 1281 | (v.detail->>'valid_from')::timestamptz AS valid_from, |
| 1282 | (v.detail->>'valid_to')::timestamptz AS valid_to, |
| 1283 | v.left_fact AS against_fact, |
| 1284 | s.canonical_name || ' · ' |
| 1285 | || COALESCE(r.label, fact_surface_predicate(f.id), '?') || ' · ' |
| 1286 | || COALESCE(o.canonical_name, '?') AS against_text, |
| 1287 | v.path AS premises |
| 1288 | FROM axiom_violations v |
| 1289 | JOIN facts f ON f.id = v.left_fact |
| 1290 | JOIN entities s ON s.id = f.subject_id |
| 1291 | LEFT JOIN relation_types r ON r.id = f.predicate_id |
| 1292 | LEFT JOIN entities o ON o.id = f.object_id |
| 1293 | WHERE v.kb_id = $1 AND v.kind = 'derived_contradiction' AND v.status = 'open' |
| 1294 | AND (v.detail->>'subject_id' = $2::text OR v.detail->>'object_id' = $2::text) |
| 1295 | ORDER BY v.detected_at DESC", |
| 1296 | ) |
| 1297 | .bind(kb_id) |
| 1298 | .bind(entity_id) |
| 1299 | .fetch_all(pool) |
| 1300 | .await?) |
| 1301 | } |
| 1302 | |
| 1303 | /// 没落地的派生的证明链:它的前提就在违规的 `path` 里。找不到那条违规时 `None` |
| 1304 | pub async fn blocked_proof( |
| 1305 | pool: &PgPool, |
| 1306 | kb_id: Uuid, |
| 1307 | violation_id: Uuid, |
| 1308 | ) -> AppResult<Option<Vec<utopia_core::models::ProofStep>>> { |
| 1309 | let path: Option<(Vec<Uuid>,)> = sqlx::query_as( |
| 1310 | "SELECT path FROM axiom_violations |
| 1311 | WHERE id = $1 AND kb_id = $2 AND kind = 'derived_contradiction'", |
| 1312 | ) |
| 1313 | .bind(violation_id) |
| 1314 | .bind(kb_id) |
| 1315 | .fetch_optional(pool) |
| 1316 | .await?; |
| 1317 | match path { |
| 1318 | None => Ok(None), |
| 1319 | Some((p,)) => Ok(Some(steps_for(pool, &p).await?)), |
| 1320 | } |
| 1321 | } |
| 1322 | |
| 1323 | /// 按 id 取一条派生(失效的也取:证明要能回看)。 |
| 1324 | async fn derived_one( |
| 1325 | pool: &PgPool, |
| 1326 | kb_id: Uuid, |
| 1327 | derived_id: Uuid, |
| 1328 | ) -> AppResult<Option<DerivedFactView>> { |
| 1329 | Ok(sqlx::query_as( |
| 1330 | "SELECT d.id, |
| 1331 | d.subject_id, s.canonical_name AS subject, |
| 1332 | d.object_id, o.canonical_name AS object, |
| 1333 | r.label AS predicate, |
| 1334 | ru.kind AS rule, |
| 1335 | d.valid_from, d.valid_to, d.confidence, d.derived_at, |
| 1336 | COALESCE( |
| 1337 | (SELECT array_agg( |
| 1338 | ps.canonical_name || ' · ' |
| 1339 | || COALESCE(pr.label, '?') || ' · ' |
| 1340 | || COALESCE(po.canonical_name, '?') |
| 1341 | ORDER BY fd.seq) |
| 1342 | FROM fact_derivations fd |
| 1343 | JOIN facts pf ON pf.id = fd.premise_fact_id |
| 1344 | JOIN entities ps ON ps.id = pf.subject_id |
| 1345 | LEFT JOIN relation_types pr ON pr.id = pf.predicate_id |
| 1346 | LEFT JOIN entities po ON po.id = pf.object_id |
| 1347 | WHERE fd.derived_fact_id = d.id), |
| 1348 | ARRAY[]::text[] |
| 1349 | ) AS premises |
| 1350 | FROM derived_facts d |
| 1351 | JOIN entities s ON s.id = d.subject_id |
| 1352 | JOIN entities o ON o.id = d.object_id |
| 1353 | JOIN relation_types r ON r.id = d.predicate_id |
| 1354 | JOIN rules ru ON ru.id = d.rule_id |
| 1355 | WHERE d.kb_id = $1 AND d.id = $2", |
| 1356 | ) |
| 1357 | .bind(kb_id) |
| 1358 | .bind(derived_id) |
| 1359 | .fetch_optional(pool) |
| 1360 | .await?) |
| 1361 | } |
| 1362 | |
| 1363 | /// 一条派生事实,配好展示与证明所需的文本(实体面板的「推出来的」那一档)。 |
| 1364 | /// |
| 1365 | /// **证明一起取回来**:这一档存在的理由就是「这条边不是谁说的,是这么推出来的」, |
| 1366 | /// 而不给出前提的话它跟一条普通的边看不出区别——那正是用户担心的污染。 |
| 1367 | pub async fn derived_for_entity( |
| 1368 | pool: &PgPool, |
| 1369 | kb_id: Uuid, |
| 1370 | entity_id: Uuid, |
| 1371 | ) -> AppResult<Vec<DerivedFactView>> { |
| 1372 | Ok(sqlx::query_as( |
| 1373 | "SELECT d.id, |
| 1374 | d.subject_id, s.canonical_name AS subject, |
| 1375 | d.object_id, o.canonical_name AS object, |
| 1376 | r.label AS predicate, |
| 1377 | ru.kind AS rule, |
| 1378 | d.valid_from, d.valid_to, d.confidence, d.derived_at, |
| 1379 | COALESCE( |
| 1380 | (SELECT array_agg( |
| 1381 | ps.canonical_name || ' · ' |
| 1382 | || COALESCE(pr.label, '?') || ' · ' |
| 1383 | || COALESCE(po.canonical_name, '?') |
| 1384 | ORDER BY fd.seq) |
| 1385 | FROM fact_derivations fd |
| 1386 | JOIN facts pf ON pf.id = fd.premise_fact_id |
| 1387 | JOIN entities ps ON ps.id = pf.subject_id |
| 1388 | LEFT JOIN relation_types pr ON pr.id = pf.predicate_id |
| 1389 | LEFT JOIN entities po ON po.id = pf.object_id |
| 1390 | WHERE fd.derived_fact_id = d.id), |
| 1391 | ARRAY[]::text[] |
| 1392 | ) AS premises |
| 1393 | FROM derived_facts d |
| 1394 | JOIN entities s ON s.id = d.subject_id |
| 1395 | JOIN entities o ON o.id = d.object_id |
| 1396 | JOIN relation_types r ON r.id = d.predicate_id |
| 1397 | JOIN rules ru ON ru.id = d.rule_id |
| 1398 | WHERE d.kb_id = $1 AND d.invalidated_at IS NULL |
| 1399 | AND (d.subject_id = $2 OR d.object_id = $2) |
| 1400 | ORDER BY d.derived_at DESC", |
| 1401 | ) |
| 1402 | .bind(kb_id) |
| 1403 | .bind(entity_id) |
| 1404 | .fetch_all(pool) |
| 1405 | .await?) |
| 1406 | } |