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