Skip to content

World's first open-source enterprise world model.

Export what is contested: fact conflicts and axiom violations in RDF (#922)

Ansonnm06768aa08c0c
diff --git a/crates/utopia-cli/src/main.rs b/crates/utopia-cli/src/main.rs
index 70377ae3..75ac55b4 100644
--- a/crates/utopia-cli/src/main.rs
+++ b/crates/utopia-cli/src/main.rs
@@ -82,7 +82,7 @@ struct ManifestDataDir {
/// not a side effect of a code change.
// 是迁移文件的**个数**,不是最大的编号(守卫 `schema_version_policy_compares_against_current`
// 按个数比):编号有空缺时两者不同——0071 由一个开放 PR 占着,0072 先落,个数是 71
-const CURRENT_SCHEMA_VERSION: u32 = 80;
+const CURRENT_SCHEMA_VERSION: u32 = 81;
fn main() -> anyhow::Result<()> {
dotenvy::dotenv().ok();
diff --git a/crates/utopia-server/src/api/export_routes.rs b/crates/utopia-server/src/api/export_routes.rs
index 6c995a0b..4f1ca0f5 100644
--- a/crates/utopia-server/src/api/export_routes.rs
+++ b/crates/utopia-server/src/api/export_routes.rs
@@ -73,6 +73,9 @@ pub async fn export(
// 也不能把别库的对象安上本库的 IRI——那份文件看着完整、实则悬空。
// 在流开始之前拦下:客户端拿到的是确定性的错误,不是一截断掉的文件
utopia_store::export::provenance_integrity(&mut tx, kb_id).await?;
+ // 认知状态同一条纪律(0062):越库引用、词表以外的存储值、以及 open
+ // 违规上解不开的判据,都在发第一个字节之前拦下
+ utopia_store::export::contest_integrity(&mut tx, kb_id).await?;
let stream = async_stream::try_stream! {
let buf = SharedBuf::default();
@@ -136,6 +139,29 @@ pub async fn export(
yield axum::body::Bytes::from(buf.take());
}
+ // 认知状态(0062):争议与违规都指着事实的 IRI,放在事实与派生之后
+ let mut after = None;
+ loop {
+ let page = utopia_store::export::fact_conflicts_page(&mut tx, kb_id, after).await.map_err(io)?;
+ let Some(last) = page.last() else { break };
+ after = Some(last.id);
+ for c in &page {
+ rdf::emit_fact_conflict(&mut sink, &names, c)?;
+ }
+ yield axum::body::Bytes::from(buf.take());
+ }
+
+ let mut after = None;
+ loop {
+ let page = utopia_store::export::axiom_violations_page(&mut tx, kb_id, after).await.map_err(io)?;
+ let Some(last) = page.last() else { break };
+ after = Some(last.id);
+ for v in &page {
+ rdf::emit_axiom_violation(&mut sink, &names, &vocab, v)?;
+ }
+ yield axum::body::Bytes::from(buf.take());
+ }
+
sink.finish()?;
yield axum::body::Bytes::from(buf.take());
};
diff --git a/crates/utopia-server/src/api/kbs.rs b/crates/utopia-server/src/api/kbs.rs
index 89a4a71d..df1339da 100644
--- a/crates/utopia-server/src/api/kbs.rs
+++ b/crates/utopia-server/src/api/kbs.rs
@@ -394,6 +394,9 @@ pub async fn audit_log(
///
/// 没有默认包(#580):注册建的 General 库与对话框里新建的库都空着起步,
/// 装哪个包是建库的人选的。
+/// 只被 `create_kb` 调(0062 的前提):新库没有事实就没有违规可对账,
+/// 所以这里不像 `apply_import` 那样做基线 + 判据对账。哪天它被复用到
+/// 既有库上,这条注释就不再成立——先把对账补上再复用
pub(super) async fn install_packs(
state: &AppState,
kb_id: Uuid,
diff --git a/crates/utopia-server/src/api/mcp_tests.rs b/crates/utopia-server/src/api/mcp_tests.rs
index 3fba687d..57fa1cff 100644
--- a/crates/utopia-server/src/api/mcp_tests.rs
+++ b/crates/utopia-server/src/api/mcp_tests.rs
@@ -312,6 +312,331 @@ async fn record_axis_subseconds_survive_authenticated_rdf_export() -> anyhow::Re
result.and(cleanup)
}
+/// 争议与违规要作为**独立的资源**进导出(0062),而不是把争议藏进事实的注脚;
+/// 导出本身是只读的——跑完一遍,库里那两行原样还在
+#[tokio::test]
+async fn contest_state_survives_authenticated_rdf_export() -> anyhow::Result<()> {
+ use axum::body::{to_bytes, Body};
+ use axum::http::{Request, StatusCode};
+ use oxrdf::Term;
+ use tower::ServiceExt;
+
+ let Some(f) = Fixture::new().await? else {
+ return Ok(());
+ };
+ async fn check(f: &Fixture) -> anyhow::Result<()> {
+ let (conflict, settled, violation, retired, cycle) = (
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ );
+ sqlx::raw_sql(&format!(
+ "INSERT INTO fact_conflicts (id, kb_id, old_fact_id, new_fact_id, reason)
+ VALUES ('{conflict}', '{kb}', '{fact}', '{corrected}', 'simultaneous');
+ INSERT INTO fact_conflicts
+ (id, kb_id, old_fact_id, new_fact_id, reason, status, resolution, resolved_at)
+ VALUES ('{settled}', '{kb}', '{attribute}', '{corrected}', 'no_time',
+ 'resolved', 'kept_both', '2026-03-21');
+ INSERT INTO axiom_violations (id, kb_id, kind, left_fact, right_fact)
+ VALUES ('{violation}', '{kb}', 'asymmetry', '{fact}', '{corrected}');
+ INSERT INTO axiom_violations
+ (id, kb_id, kind, left_fact, right_fact, status, resolution, decided_at)
+ VALUES ('{retired}', '{kb}', 'functional', '{fact}', '{fact}',
+ 'resolved', 'criterion_changed', '2026-03-22');
+ INSERT INTO axiom_violations (id, kb_id, kind, left_fact, right_fact, path)
+ VALUES ('{cycle}', '{kb}', 'cycle', '{fact}', '{attribute}',
+ '{{{fact},{corrected},{attribute}}}');",
+ kb = f.kb,
+ fact = f.fact,
+ corrected = f.corrected,
+ attribute = f.attribute,
+ ))
+ .execute(&f.state.pool)
+ .await?;
+ // 导出不许碰这两张表:它是只读快照,不是清陈的扳机
+ let snapshot_sql = "SELECT jsonb_build_array(
+ (SELECT jsonb_agg(to_jsonb(t) ORDER BY id) FROM fact_conflicts t WHERE kb_id=$1),
+ (SELECT jsonb_agg(to_jsonb(t) ORDER BY id) FROM axiom_violations t WHERE kb_id=$1))";
+ let before: Value = sqlx::query_scalar(snapshot_sql)
+ .bind(f.kb)
+ .fetch_one(&f.state.pool)
+ .await?;
+ let auth = utopia_store::tokens::authenticate(&f.state.pool, &f.token).await?;
+ let jwt = crate::auth::issue_token(&f.state, auth.user_id)?;
+ let app = crate::api::router(f.state.clone(), &Default::default());
+ let names = crate::rdf::Names::new(f.kb, None).map_err(anyhow::Error::msg)?;
+ let rdf_type = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
+ let has = |quads: &std::collections::HashSet<oxrdf::Quad>,
+ s: &oxrdf::NamedNode,
+ p: &str,
+ o: &str| {
+ quads.iter().any(|q| {
+ q.subject == s.clone().into()
+ && q.predicate.as_str() == p
+ && (q.object.to_string() == o || q.object.to_string() == format!("<{o}>"))
+ })
+ };
+ for (format, parser_format) in [
+ ("turtle", oxrdfio::RdfFormat::Turtle),
+ (
+ "jsonld",
+ oxrdfio::RdfFormat::JsonLd {
+ profile: oxrdfio::JsonLdProfileSet::empty(),
+ },
+ ),
+ ] {
+ let response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri(format!("/api/v1/kbs/{}/export?format={format}", f.kb))
+ .header("authorization", format!("Bearer {jwt}"))
+ .body(Body::empty())?,
+ )
+ .await?;
+ anyhow::ensure!(response.status() == StatusCode::OK, "export rejected");
+ let bytes = to_bytes(response.into_body(), 1024 * 1024).await?;
+ let quads = oxrdfio::RdfParser::from_format(parser_format)
+ .for_slice(&bytes)
+ .collect::<Result<std::collections::HashSet<_>, _>>()?;
+
+ // 争议:两类资源各自成类,各连两条事实;open 违规指回它的判据
+ let c = names.fact_conflict(conflict);
+ anyhow::ensure!(has(&quads, &c, rdf_type, "urn:utopia:ns:FactConflict"));
+ for (pred, fact) in [
+ ("priorStatement", f.fact),
+ ("incomingStatement", f.corrected),
+ ] {
+ anyhow::ensure!(
+ has(
+ &quads,
+ &c,
+ &format!("urn:utopia:ns:{pred}"),
+ &names.fact(fact).to_string()
+ ),
+ "conflict lost its {pred}"
+ );
+ }
+ let s = names.fact_conflict(settled);
+ anyhow::ensure!(
+ has(&quads, &s, "urn:utopia:ns:resolution", "\"kept_both\""),
+ "resolved conflict lost its disposition"
+ );
+
+ let v = names.axiom_violation(violation);
+ anyhow::ensure!(has(&quads, &v, rdf_type, "urn:utopia:ns:AxiomViolation"));
+ anyhow::ensure!(has(
+ &quads,
+ &v,
+ "urn:utopia:ns:onStatement",
+ &names.fact(f.fact).to_string()
+ ));
+ anyhow::ensure!(
+ has(
+ &quads,
+ &v,
+ "urn:utopia:ns:criterion",
+ "http://www.w3.org/2002/07/owl#AsymmetricProperty"
+ ),
+ "open violation lost its criterion"
+ );
+ // fixture 的 works_for 没有导入 IRI,判据挂在它自己的稳定标识上
+ let relation_iri = format!("urn:utopia:kb:{}:relation:works_for", f.kb);
+ anyhow::ensure!(
+ has(&quads, &v, "urn:utopia:ns:onRelation", &relation_iri),
+ "open violation lost the relation its criterion lives on"
+ );
+ // 结案的行不报判据:促成它的本体版本可能已经不在了
+ let r = names.axiom_violation(retired);
+ anyhow::ensure!(
+ quads.iter().all(|q| {
+ !(q.subject == r.clone().into()
+ && (q.predicate.as_str() == "urn:utopia:ns:criterion"
+ || q.predicate.as_str() == "urn:utopia:ns:onRelation"))
+ }),
+ "resolved violation claimed a criterion"
+ );
+
+ // 环的 path 是有序证据:顺着 rdf:List 走一遍,次序不许变
+ let cy = names.axiom_violation(cycle);
+ let mut node = quads
+ .iter()
+ .find(|q| {
+ q.subject == cy.clone().into()
+ && q.predicate.as_str() == "urn:utopia:ns:evidencePath"
+ })
+ .map(|q| q.object.clone())
+ .ok_or_else(|| anyhow::anyhow!("cycle lost its path"))?;
+ let nil = Term::from(oxrdf::NamedNode::new_unchecked(
+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#nil",
+ ));
+ let mut walked = Vec::new();
+ while node != nil {
+ let first = quads
+ .iter()
+ .find(|q| {
+ q.subject.to_string() == node.to_string()
+ && q.predicate.as_str()
+ == "http://www.w3.org/1999/02/22-rdf-syntax-ns#first"
+ })
+ .map(|q| q.object.clone())
+ .ok_or_else(|| anyhow::anyhow!("list node without first"))?;
+ walked.push(first.to_string());
+ node = quads
+ .iter()
+ .find(|q| {
+ q.subject.to_string() == node.to_string()
+ && q.predicate.as_str()
+ == "http://www.w3.org/1999/02/22-rdf-syntax-ns#rest"
+ })
+ .map(|q| q.object.clone())
+ .ok_or_else(|| anyhow::anyhow!("list node without rest"))?;
+ }
+ let expected: Vec<String> = [f.fact, f.corrected, f.attribute]
+ .iter()
+ .map(|x| names.fact(*x).to_string())
+ .collect();
+ anyhow::ensure!(walked == expected, "cycle order did not survive {format}");
+
+ // 争着的事实照旧是普通事实:争议是旁边的一份资源,不是标签
+ for fact in [f.fact, f.corrected] {
+ anyhow::ensure!(
+ has(
+ &quads,
+ &names.fact(fact),
+ rdf_type,
+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement"
+ ),
+ "contested fact stopped being a statement"
+ );
+ }
+ }
+ let after: Value = sqlx::query_scalar(snapshot_sql)
+ .bind(f.kb)
+ .fetch_one(&f.state.pool)
+ .await?;
+ anyhow::ensure!(before == after, "export changed conflict/violation records");
+ Ok(())
+ }
+ let result = check(&f).await;
+ let cleanup = f.clean().await;
+ result.and(cleanup)
+}
+
+/// `criterion_changed` 是系统写的东西(0062:本体改动的事务收编旧判据的行),
+/// 不是人递得进来的裁决——裁决口收下它就等于让人替机器签名
+#[tokio::test]
+async fn criterion_changed_is_not_a_human_disposition() -> anyhow::Result<()> {
+ use axum::body::Body;
+ use axum::http::{Request, StatusCode};
+ use tower::ServiceExt;
+
+ let Some(f) = Fixture::new().await? else {
+ return Ok(());
+ };
+ async fn check(f: &Fixture) -> anyhow::Result<()> {
+ // 裁决要编辑权——fixture 里的成员是 viewer
+ sqlx::query("UPDATE kb_members SET role = 'editor' WHERE kb_id = $1")
+ .bind(f.kb)
+ .execute(&f.state.pool)
+ .await?;
+ let violation = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO axiom_violations (id, kb_id, kind, left_fact, right_fact)
+ VALUES ($1, $2, 'functional', $3, $3)",
+ )
+ .bind(violation)
+ .bind(f.kb)
+ .bind(f.fact)
+ .execute(&f.state.pool)
+ .await?;
+ let auth = utopia_store::tokens::authenticate(&f.state.pool, &f.token).await?;
+ let jwt = crate::auth::issue_token(&f.state, auth.user_id)?;
+ let app = crate::api::router(f.state.clone(), &Default::default());
+ let response = app
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri(format!(
+ "/api/v1/kbs/{}/review/violations/{violation}",
+ f.kb
+ ))
+ .header("authorization", format!("Bearer {jwt}"))
+ .header("content-type", "application/json")
+ .body(Body::from(r#"{"resolution":"criterion_changed"}"#))?,
+ )
+ .await?;
+ anyhow::ensure!(
+ response.status() == StatusCode::UNPROCESSABLE_ENTITY,
+ "a system disposition was accepted as a human decision: {}",
+ response.status()
+ );
+ let still_open: bool = sqlx::query_scalar(
+ "SELECT EXISTS(SELECT 1 FROM axiom_violations
+ WHERE id = $1 AND status = 'open' AND resolution IS NULL)",
+ )
+ .bind(violation)
+ .fetch_one(&f.state.pool)
+ .await?;
+ anyhow::ensure!(still_open, "rejected decision still touched the row");
+ Ok(())
+ }
+ let result = check(&f).await;
+ let cleanup = f.clean().await;
+ result.and(cleanup)
+}
+
+/// open 违规上解不开的判据让整份导出被拒绝(0062):带着悬空判据的资源
+/// 发出去,读的人会拿到一个指不到任何关系的 criterion——宁可是确定性错误
+/// 也不是一份半个谎的文件
+#[tokio::test]
+async fn an_unresolvable_criterion_fails_the_export_closed() -> anyhow::Result<()> {
+ use axum::http::{Request, StatusCode};
+ use tower::ServiceExt;
+
+ let Some(f) = Fixture::new().await? else {
+ return Ok(());
+ };
+ async fn check(f: &Fixture) -> anyhow::Result<()> {
+ // detail.predicate_id 指着一个不存在的谓词:open 行的判据解不出来,
+ // contest_integrity 要在第一个字节之前拦下
+ let dangling = Uuid::now_v7();
+ sqlx::query(&format!(
+ "INSERT INTO axiom_violations (id, kb_id, kind, left_fact, right_fact, detail)
+ VALUES ('{}', '{}', 'derived_contradiction', '{}', '{}',
+ '{{\"axiom\":\"self_loop\",\"predicate_id\":\"{dangling}\"}}'::jsonb)",
+ Uuid::now_v7(),
+ f.kb,
+ f.fact,
+ f.fact,
+ ))
+ .execute(&f.state.pool)
+ .await?;
+ let auth = utopia_store::tokens::authenticate(&f.state.pool, &f.token).await?;
+ let jwt = crate::auth::issue_token(&f.state, auth.user_id)?;
+ let app = crate::api::router(f.state.clone(), &Default::default());
+ let response = app
+ .oneshot(
+ Request::builder()
+ .uri(format!("/api/v1/kbs/{}/export?format=turtle", f.kb))
+ .header("authorization", format!("Bearer {jwt}"))
+ .body(axum::body::Body::empty())?,
+ )
+ .await?;
+ anyhow::ensure!(
+ response.status() == StatusCode::UNPROCESSABLE_ENTITY,
+ "expected the contested-state contract to refuse the export, got {}",
+ response.status()
+ );
+ Ok(())
+ }
+ let result = check(&f).await;
+ let cleanup = f.clean().await;
+ result.and(cleanup)
+}
+
/// 每个导出的快照事务活满整个流——它占住一条连接直到文件发完。台账如果排在
/// 事务之后写,就是在「已经占了一条」的情况下再向池子要第二条:支持的最小池
/// (2 条连接)上两个并发导出会互相把对方的审计饿死到超时。所以顺序必须是:
diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rs
index 6a4eeaf4..976a0882 100644
--- a/crates/utopia-server/src/api/ontology_routes.rs
+++ b/crates/utopia-server/src/api/ontology_routes.rs
@@ -194,6 +194,8 @@ pub async fn update_entity_type(
std::time::Duration::from_secs(5),
)
.await;
+ // 对账可能在同一事务里收/开过违规行——审核队列变了,说一声(0062)
+ state.emit_review(kb_id);
Ok(Json(json!({ "ok": true })))
}
@@ -214,6 +216,8 @@ pub async fn delete_entity_type(
json!({}),
)
.await;
+ // 对账可能在同一事务里收/开过违规行——审核队列变了,说一声(0062)
+ state.emit_review(kb_id);
Ok(Json(json!({ "ok": true })))
}
@@ -257,14 +261,14 @@ pub struct RelationTypeReq {
#[serde(default)]
pub kind: Option<String>,
/// 可以当主语的类。attribute 至少一个;relation 留空 = 不限。
- /// **更新时缺省 = 不动**,所以是 Option 而不是 Vec——不管 domain 的
- /// 调用方(属性表单)不该因为一次改名就把 domain 清空
+ /// **两者都缺省才是不动**:签名是一组一起提交的——只送 ranges 会把
+ /// domains 清空,不是「ranges 动、domains 留」
#[serde(default)]
pub domains: Option<Vec<Uuid>>,
/// 这条关系的边能带哪些属性(0037):属性定义的 id。None = 不动
#[serde(default)]
pub qualifiers: Option<Vec<Uuid>>,
- /// 可以当宾语的类。只对 relation 有意义
+ /// 可以当宾语的类。只对 relation 有意义;与 domains 同一条成组提交规矩
#[serde(default)]
pub ranges: Option<Vec<Uuid>>,
/// attribute 专用:text | number | date | bool
@@ -395,6 +399,8 @@ pub async fn update_relation_type(
"description": req.description }),
)
.await;
+ // 对账可能在同一事务里收/开过违规行——审核队列变了,说一声(0062)
+ state.emit_review(kb_id);
Ok(Json(json!({ "ok": true })))
}
@@ -415,6 +421,8 @@ pub async fn delete_relation_type(
json!({}),
)
.await;
+ // 对账可能在同一事务里收/开过违规行——审核队列变了,说一声(0062)
+ state.emit_review(kb_id);
Ok(Json(json!({ "ok": true })))
}
@@ -1299,18 +1307,45 @@ pub async fn apply_import(
) -> ApiResult<Json<serde_json::Value>> {
require_kb(&state, &user, kb_id, Role::Editor).await?;
let (filename, bytes) = read_upload(multipart).await?;
+ // 导入会改判据(公理链、domain/range、父边):先把旧本体下会检出的违规
+ // 记下来(0062),apply 落库后按新本体对账——在旧判据下检出过的陈行以
+ // criterion_changed 收场,不是整批抹掉;对账失败如实报错,不假装干净
+ // 基线跑在同一条事务里:autocommit 连接上每条语句各看一个快照,
+ // 半途有别的提交进来会把两个时刻混成一份基线
+ let mut baseline_tx = state.pool.begin().await?;
+ let was_detected = utopia_store::reasoning::detection_keys(&mut baseline_tx, kb_id).await?;
+ baseline_tx.commit().await?;
let (import_id, plan) =
- crate::owl_import::apply(&state, kb_id, user.id, &filename, &bytes).await?;
- // 公理刚变,这是最该重算一致性的时刻——用户导进来的正是判据本身。
- // 失败不影响导入本身:本体已经落库了,检查跑不动是另一件事,
- // Review 页那个按钮还能再跑一次
- let violations = match utopia_store::reasoning::run(&state.pool, kb_id).await {
- Ok(r) => r.found,
- Err(e) => {
- tracing::warn!(?e, "导入后的一致性检查没跑成");
- 0
- }
- };
+ match crate::owl_import::apply(&state, kb_id, user.id, &filename, &bytes).await {
+ Ok(v) => v,
+ Err(e) => {
+ // apply 是多笔提交:中途失败时一部分判据已经落了。尽力对账——
+ // 已提交的判据是「当前本体」,open 行不能带着旧判据过夜。对账
+ // 自身失败只记告警,原错误照样返回,不吞
+ match state.pool.begin().await {
+ Ok(mut tx) => {
+ if let Err(re) = utopia_store::reasoning::reconcile_ontology(
+ &mut tx,
+ kb_id,
+ &was_detected,
+ )
+ .await
+ {
+ tracing::warn!(error = ?re, "导入失败后的违规对账也没跑成");
+ } else if let Err(ce) = tx.commit().await {
+ tracing::warn!(error = ?ce, "导入失败后的违规对账提交失败");
+ }
+ }
+ Err(be) => tracing::warn!(error = ?be, "导入失败后连对账事务都开不了"),
+ }
+ return Err(e.into());
+ }
+ };
+ // apply 自己分多笔提交,这笔事务只做对账:`open` 的意思是对账于当前本体
+ let mut tx = state.pool.begin().await?;
+ let violations =
+ utopia_store::reasoning::reconcile_ontology(&mut tx, kb_id, &was_detected).await?;
+ tx.commit().await?;
state.emit_review(kb_id);
Ok(Json(
json!({ "import_id": import_id, "plan": plan, "violations": violations }),
@@ -1407,6 +1442,8 @@ async fn adopt_attribute(
"remapped": done.remapped, "unconvertible": done.unconvertible }),
)
.await;
+ // 空关系改判会跑判据对账(0062),队列可能刚变过
+ state.emit_review(kb_id);
// unconvertible 要回给调用方:改写了 3 条、丢下 2 条,界面得说得出后半句
Ok(Json(json!({
"id": done.attribute_id, "batch": done.batch_id,
diff --git a/crates/utopia-server/src/rdf.rs b/crates/utopia-server/src/rdf.rs
index 363069a6..a0e20a05 100644
--- a/crates/utopia-server/src/rdf.rs
+++ b/crates/utopia-server/src/rdf.rs
@@ -20,7 +20,8 @@ use chrono::{DateTime, Utc};
use oxrdf::vocab::{rdf, rdfs, xsd};
use oxrdf::{Literal, NamedNode, NamedNodeRef, Term, TripleRef};
use utopia_store::export::{
- ExportClass, ExportDerived, ExportDocument, ExportEntity, ExportFact, ExportRelation,
+ ExportAxiomViolation, ExportClass, ExportDerived, ExportDocument, ExportEntity, ExportFact,
+ ExportFactConflict, ExportRelation,
};
use uuid::Uuid;
@@ -105,6 +106,14 @@ impl Names {
pub fn rule(&self, id: Uuid) -> NamedNode {
self.mint("rule", &id.to_string())
}
+ /// 事实争议(0062):`…:conflict:{uuid}`
+ pub fn fact_conflict(&self, id: Uuid) -> NamedNode {
+ self.mint("conflict", &id.to_string())
+ }
+ /// 公理违规发现(0062):`…:violation:{uuid}`
+ pub fn axiom_violation(&self, id: Uuid) -> NamedNode {
+ self.mint("violation", &id.to_string())
+ }
/// 本体自己长出来的类/关系用 **key** 而不是 uuid:key 是这个库内部就在用的
/// 标识(`UNIQUE (kb_id, key)`,抽取提示词和 API 用的都是它),文件因此读得懂。
/// 导入来的一律用原 IRI
@@ -637,6 +646,123 @@ pub fn emit_derived(
Ok(())
}
+/// 一条事实争议(0062):同一槽位上的两条断言互不相让。
+///
+/// `status` 照原样给:open 是「还在争」;resolved + `utopia:resolution` 是人的
+/// 裁决;`withdrawn` 不是裁决——一边作废了题就没了,`utopia:closedAt` 记的是
+/// 作废时刻(0051),不是有人打开过审核页的时刻
+pub fn emit_fact_conflict(
+ sink: &mut Sink,
+ names: &Names,
+ c: &ExportFactConflict,
+) -> std::io::Result<()> {
+ let iri = names.fact_conflict(c.id);
+ sink.r(&iri, &nn(rdf::TYPE.as_str()), &utopia("FactConflict"))?;
+ // 两席分清方向:压着的断言与新到的那条不是对称的(0062)
+ for (pred, fact) in [
+ (utopia("priorStatement"), c.old_fact_id),
+ (utopia("incomingStatement"), c.new_fact_id),
+ ] {
+ sink.r(&iri, &pred, &names.fact(fact))?;
+ }
+ sink.l(&iri, &utopia("reason"), &text(c.reason.clone()))?;
+ sink.l(&iri, &utopia("status"), &text(c.status.clone()))?;
+ if let Some(r) = &c.resolution {
+ sink.l(&iri, &utopia("resolution"), &text(r.clone()))?;
+ }
+ sink.l(&iri, &prov("generatedAtTime"), &dt(c.created_at))?;
+ if let Some(t) = c.resolved_at {
+ sink.l(&iri, &utopia("closedAt"), &dt(t))?;
+ }
+ Ok(())
+}
+
+/// 一条公理违规发现(0062)。这是**可变的当前状态**,不是历史:`open` 的意思是
+/// 已对账于当前本体——所以判据只连在 open 行上,resolved 的行不假装知道自己是
+/// 按哪一版本体结案的
+pub fn emit_axiom_violation(
+ sink: &mut Sink,
+ names: &Names,
+ vocab: &Vocabulary,
+ v: &ExportAxiomViolation,
+) -> std::io::Result<()> {
+ let iri = names.axiom_violation(v.id);
+ sink.r(&iri, &nn(rdf::TYPE.as_str()), &utopia("AxiomViolation"))?;
+ sink.l(&iri, &utopia("kind"), &text(v.kind.clone()))?;
+ // self_loop/signature 的左右是同一事实——RDF 集合语义下重发无害,但 Turtle
+ // 文件里会是一条重复三元组
+ let endpoints: &[Uuid] = if v.left_fact == v.right_fact {
+ &[v.left_fact]
+ } else {
+ &[v.left_fact, v.right_fact]
+ };
+ for fact in endpoints {
+ sink.r(&iri, &utopia("onStatement"), &names.fact(*fact))?;
+ }
+ // 环是有序的证据链(0054):拍扁成一组无序的 facts,「A→B→C→A」就读不回来了。
+ // rdf:List 是 Turtle/JSON-LD 都认的保序结构
+ if !v.path.is_empty() {
+ let items: Vec<Term> = v.path.iter().map(|f| names.fact(*f).into()).collect();
+ let head = emit_list(sink, &items)?;
+ sink.triple(TripleRef::new(
+ iri.as_ref(),
+ utopia("evidencePath").as_ref(),
+ head.as_ref(),
+ ))?;
+ }
+ sink.l(&iri, &utopia("status"), &text(v.status.clone()))?;
+ if let Some(r) = &v.resolution {
+ sink.l(&iri, &utopia("resolution"), &text(r.clone()))?;
+ }
+ sink.l(&iri, &utopia("detectedAt"), &dt(v.detected_at))?;
+ if let Some(t) = v.decided_at {
+ sink.l(&iri, &utopia("closedAt"), &dt(t))?;
+ }
+ // 判据(0062 §4):open = 已对账于当前本体,必然指得回一条关系与一个
+ // OWL/rdfs 词。signature 的判据是一对签名,两个词都发(行不记哪一侧破的)。
+ // resolved 的行不发——它的判据可能早已不在本体里
+ if v.status == "open" {
+ for term in v.criterion_terms().unwrap_or(&[]) {
+ sink.r(&iri, &utopia("criterion"), &criterion_node(term))?;
+ }
+ if let Some(rel) = v
+ .criterion_predicate
+ .and_then(|p| vocab.relation(p))
+ .cloned()
+ {
+ sink.r(&iri, &utopia("onRelation"), &rel)?;
+ }
+ }
+ Ok(())
+}
+
+/// `utopia:criterion` 的词项:`criterion_terms` 只产 `owl:`/`rdfs:` 两种,
+/// 其余值不可能走到这里(export 侧已经拒导)
+fn criterion_node(term: &str) -> NamedNode {
+ if let Some(t) = term.strip_prefix("owl:") {
+ owl(t)
+ } else {
+ match term {
+ "rdfs:domain" => rdfs::DOMAIN.into(),
+ "rdfs:range" => rdfs::RANGE.into(),
+ _ => unreachable!("criterion_terms 只产 owl:/rdfs: 词"),
+ }
+ }
+}
+
+/// 一串有序资源写成 rdf:List,返回表头节点(空表返回 rdf:nil)。
+/// 从尾往前搭:每个空白节点落地时就知道自己的 rest
+fn emit_list(sink: &mut Sink, items: &[Term]) -> std::io::Result<Term> {
+ let mut head: Term = nn(rdf::NIL.as_str()).into();
+ for item in items.iter().rev() {
+ let node = oxrdf::BlankNode::default();
+ sink.triple(TripleRef::new(node.as_ref(), rdf::FIRST, item.as_ref()))?;
+ sink.triple(TripleRef::new(node.as_ref(), rdf::REST, head.as_ref()))?;
+ head = node.into();
+ }
+ Ok(head)
+}
+
fn emit_validity(
sink: &mut Sink,
stmt: &NamedNode,
@@ -1551,4 +1677,263 @@ mod tests {
assert!(Names::new(kb(), Some("javascript:alert(1)")).is_err());
assert!(Names::new(kb(), Some("https://acme.example/a b")).is_err());
}
+
+ const CONFLICT: &str = "<urn:utopia:kb:01a06dc4-f40a-7013-b09f-1b499e2e7441:conflict:07070707-0707-0707-0707-070707070707>";
+ const VIOLATION: &str = "<urn:utopia:kb:01a06dc4-f40a-7013-b09f-1b499e2e7441:violation:08080808-0808-0808-0808-080808080808>";
+
+ fn conflict(status: &str, resolution: Option<&str>) -> ExportFactConflict {
+ ExportFactConflict {
+ id: id(7),
+ old_fact_id: id(5),
+ new_fact_id: id(6),
+ reason: "simultaneous".into(),
+ created_at: at("2026-03-10T00:00:00Z"),
+ status: status.into(),
+ resolution: resolution.map(str::to_string),
+ resolved_at: (status != "open").then(|| at("2026-03-20T00:00:00Z")),
+ old_fact_kb: Some(kb()),
+ new_fact_kb: Some(kb()),
+ }
+ }
+
+ fn violation(
+ kind: &str,
+ status: &str,
+ resolution: Option<&str>,
+ path: Vec<Uuid>,
+ ) -> ExportAxiomViolation {
+ ExportAxiomViolation {
+ id: id(8),
+ kind: kind.into(),
+ left_fact: id(5),
+ right_fact: id(6),
+ path,
+ status: status.into(),
+ resolution: resolution.map(str::to_string),
+ detected_at: at("2026-03-15T00:00:00Z"),
+ decided_at: (status != "open").then(|| at("2026-03-20T00:00:00Z")),
+ criterion_predicate: (status == "open").then_some(id(2)),
+ criterion_axiom: (status == "open").then_some(kind.to_string()),
+ left_kb: Some(kb()),
+ right_kb: Some(kb()),
+ criterion_predicate_kb: Some(kb()),
+ foreign_path: false,
+ }
+ }
+
+ #[test]
+ fn a_contest_names_both_sides_and_its_disposition() {
+ let open = conflict("open", None);
+ let quads = export(Format::Turtle, |sink, names, _| {
+ emit_fact_conflict(sink, names, &open).unwrap();
+ });
+ assert!(has(
+ &quads,
+ CONFLICT,
+ rdf::TYPE.as_str(),
+ "urn:utopia:ns:FactConflict"
+ ));
+ let names = Names::new(kb(), None).unwrap();
+ // 两席有方向:旧断言是 prior,新到的是 incoming
+ assert_eq!(
+ objects(&quads, CONFLICT, "urn:utopia:ns:priorStatement"),
+ vec![names.fact(id(5)).to_string()]
+ );
+ assert_eq!(
+ objects(&quads, CONFLICT, "urn:utopia:ns:incomingStatement"),
+ vec![names.fact(id(6)).to_string()]
+ );
+ assert_eq!(
+ objects(&quads, CONFLICT, "urn:utopia:ns:reason"),
+ vec!["\"simultaneous\""]
+ );
+ assert_eq!(
+ objects(&quads, CONFLICT, "urn:utopia:ns:status"),
+ vec!["\"open\""]
+ );
+ assert!(objects(&quads, CONFLICT, "urn:utopia:ns:resolution").is_empty());
+ assert!(!objects(
+ &quads,
+ CONFLICT,
+ "http://www.w3.org/ns/prov#generatedAtTime"
+ )
+ .is_empty());
+ assert!(objects(&quads, CONFLICT, "urn:utopia:ns:closedAt").is_empty());
+
+ // 人裁过的带裁决词;作废的不是裁决——closedAt 记的是作废时刻(0051),
+ // 不带 resolution
+ for (status, resolution) in [("resolved", Some("kept_both")), ("withdrawn", None)] {
+ let c = conflict(status, resolution);
+ let quads = export(Format::Turtle, |sink, names, _| {
+ emit_fact_conflict(sink, names, &c).unwrap();
+ });
+ assert_eq!(
+ objects(&quads, CONFLICT, "urn:utopia:ns:status"),
+ vec![format!("\"{status}\"")]
+ );
+ assert_eq!(
+ objects(&quads, CONFLICT, "urn:utopia:ns:resolution"),
+ resolution
+ .map(|r| vec![format!("\"{r}\"")])
+ .unwrap_or_default()
+ );
+ assert!(!objects(&quads, CONFLICT, "urn:utopia:ns:closedAt").is_empty());
+ }
+ }
+
+ #[test]
+ fn an_open_violation_points_at_its_criterion() {
+ let v = violation("asymmetry", "open", None, vec![]);
+ let quads = export(Format::Turtle, |sink, names, vocab| {
+ emit_axiom_violation(sink, names, vocab, &v).unwrap();
+ });
+ assert!(has(
+ &quads,
+ VIOLATION,
+ rdf::TYPE.as_str(),
+ "urn:utopia:ns:AxiomViolation"
+ ));
+ assert_eq!(
+ objects(&quads, VIOLATION, "urn:utopia:ns:kind"),
+ vec!["\"asymmetry\""]
+ );
+ assert_eq!(
+ objects(&quads, VIOLATION, "urn:utopia:ns:onStatement").len(),
+ 2,
+ "违规必须指回两条事实"
+ );
+ // 判据 = OWL 词 + 住在哪条关系上(0062)
+ assert_eq!(
+ objects(&quads, VIOLATION, "urn:utopia:ns:criterion"),
+ vec!["<http://www.w3.org/2002/07/owl#AsymmetricProperty>"]
+ );
+ assert_eq!(
+ objects(&quads, VIOLATION, "urn:utopia:ns:onRelation"),
+ vec![format!("<{WORKS_FOR}>")]
+ );
+ assert!(!objects(&quads, VIOLATION, "urn:utopia:ns:detectedAt").is_empty());
+ assert!(objects(&quads, VIOLATION, "urn:utopia:ns:closedAt").is_empty());
+ }
+
+ #[test]
+ fn a_signature_violation_points_at_the_whole_signature() {
+ // signature 的判据是 domain+range 这一对(0062):行不记哪一侧破的,
+ // 合同也就不装知道——两个词都发
+ let v = violation("signature", "open", None, vec![]);
+ let quads = export(Format::Turtle, |sink, names, vocab| {
+ emit_axiom_violation(sink, names, vocab, &v).unwrap();
+ });
+ let mut criterion = objects(&quads, VIOLATION, "urn:utopia:ns:criterion");
+ criterion.sort();
+ assert_eq!(
+ criterion,
+ vec![
+ "<http://www.w3.org/2000/01/rdf-schema#domain>".to_string(),
+ "<http://www.w3.org/2000/01/rdf-schema#range>".to_string()
+ ]
+ );
+ assert_eq!(
+ objects(&quads, VIOLATION, "urn:utopia:ns:onRelation"),
+ vec![format!("<{WORKS_FOR}>")]
+ );
+ }
+
+ #[test]
+ fn a_closed_violation_does_not_claim_a_criterion() {
+ // resolved 的行不连判据:促成它结案的本体可能早已不在(0062)
+ let v = violation("signature", "resolved", Some("criterion_changed"), vec![]);
+ let quads = export(Format::Turtle, |sink, names, vocab| {
+ emit_axiom_violation(sink, names, vocab, &v).unwrap();
+ });
+ assert!(objects(&quads, VIOLATION, "urn:utopia:ns:criterion").is_empty());
+ assert!(objects(&quads, VIOLATION, "urn:utopia:ns:onRelation").is_empty());
+ assert_eq!(
+ objects(&quads, VIOLATION, "urn:utopia:ns:resolution"),
+ vec!["\"criterion_changed\""]
+ );
+ assert!(!objects(&quads, VIOLATION, "urn:utopia:ns:closedAt").is_empty());
+ }
+
+ /// 顺着 rdf:List 走一遍,把成员按序收回来
+ fn list_items(quads: &[Quad], violation_iri: &str) -> Vec<String> {
+ let nil: Term = nn(rdf::NIL.as_str()).into();
+ let head = quads
+ .iter()
+ .find(|q| {
+ q.subject.to_string() == violation_iri
+ && q.predicate.as_str() == "urn:utopia:ns:evidencePath"
+ })
+ .map(|q| q.object.clone())
+ .expect("环必须带着 path");
+ let mut items = Vec::new();
+ let mut node = head;
+ while node != nil {
+ let first = quads
+ .iter()
+ .find(|q| {
+ q.subject.to_string() == node.to_string()
+ && q.predicate.as_str() == rdf::FIRST.as_str()
+ })
+ .map(|q| q.object.clone())
+ .expect("list 节点必有 first");
+ items.push(first.to_string());
+ node = quads
+ .iter()
+ .find(|q| {
+ q.subject.to_string() == node.to_string()
+ && q.predicate.as_str() == rdf::REST.as_str()
+ })
+ .map(|q| q.object.clone())
+ .expect("list 节点必有 rest");
+ }
+ items
+ }
+
+ #[test]
+ fn a_cycle_keeps_its_facts_in_order() {
+ let path = vec![id(5), id(9), id(6)];
+ let v = violation("cycle", "open", None, path.clone());
+ let names = Names::new(kb(), None).unwrap();
+ let expected: Vec<String> = path.iter().map(|f| names.fact(*f).to_string()).collect();
+ for format in [Format::Turtle, Format::JsonLd] {
+ let quads = export(format, |sink, names, vocab| {
+ emit_axiom_violation(sink, names, vocab, &v).unwrap();
+ });
+ assert_eq!(
+ list_items(&quads, VIOLATION),
+ expected,
+ "{format:?} 里环的顺序丢了"
+ );
+ }
+ }
+
+ #[test]
+ fn contest_and_finding_survive_both_formats() {
+ let emit = |sink: &mut Sink, names: &Names, vocab: &Vocabulary| {
+ emit_fact_conflict(sink, names, &conflict("resolved", Some("rejected_new"))).unwrap();
+ emit_axiom_violation(
+ sink,
+ names,
+ vocab,
+ &violation("asymmetry", "open", None, vec![id(5), id(9)]),
+ )
+ .unwrap();
+ };
+ let ttl = export(Format::Turtle, emit);
+ let jsonld = export(Format::JsonLd, emit);
+ assert_eq!(
+ ttl.len(),
+ jsonld.len(),
+ "两种格式是同一张图的两种写法,三元组数目必须一样"
+ );
+ // 空白节点在两种写法里各自匿名,集合同比不了——比所有非匿名的角,
+ // 环那份证据的顺序交给 a_cycle_keeps_its_facts_in_order 按格式各验一遍
+ let named = |qs: &[Quad]| {
+ qs.iter()
+ .filter(|q| q.subject.is_named_node() && !matches!(q.object, Term::BlankNode(_)))
+ .cloned()
+ .collect::<std::collections::HashSet<_>>()
+ };
+ assert_eq!(named(&ttl), named(&jsonld));
+ }
}
diff --git a/crates/utopia-store/src/export.rs b/crates/utopia-store/src/export.rs
index 8e688ece..b372984c 100644
--- a/crates/utopia-store/src/export.rs
+++ b/crates/utopia-store/src/export.rs
@@ -753,3 +753,352 @@ pub async fn documents_page(
.fetch_all(&mut **tx)
.await?)
}
+
+/* ---- 认知状态(0062)----
+ *
+ * 两张表两种东西,不合成一类:
+ * fact_conflicts 同一槽位上两条断言互不相让——数据里有争议,判据没毛病
+ * axiom_violations 当前数据撞上当前判据——数据或本体至少一边要动
+ *
+ * 只读:不走 `temporal::list_conflicts` 那种带惰性清理的读面(0051 已把它删了),
+ * 也不触发检出。导出的是库里记下的状态。 */
+
+/// 两条事实争同一个槽位。`resolved` 的行也在——它记的是有过的争议,不是
+/// 待办;`withdrawn` 的是事实作废后由触发器退场的(0051),`resolved_at` 记的是
+/// 作废时刻,不是有人开过页面
+#[derive(Debug, Clone, sqlx::FromRow)]
+pub struct ExportFactConflict {
+ pub id: Uuid,
+ pub old_fact_id: Uuid,
+ pub new_fact_id: Uuid,
+ /// 争议怎么被记下的:no_time | simultaneous | low_confidence | described_evidence
+ /// (此列无 CHECK,库里的旧值也可能进来;合同词表以 contest_integrity 为准)
+ pub reason: String,
+ pub created_at: DateTime<Utc>,
+ /// open | resolved | withdrawn
+ pub status: String,
+ /// closed | kept_both | rejected_new;只在 resolved 时有
+ pub resolution: Option<String>,
+ /// resolved:裁决时刻;withdrawn:先作废那一边的时刻(0051)
+ pub resolved_at: Option<DateTime<Utc>>,
+ /// 两条事实的 kb,随行原子地一并选出:越库/悬空 → 拒导
+ pub old_fact_kb: Option<Uuid>,
+ pub new_fact_kb: Option<Uuid>,
+}
+
+pub async fn fact_conflicts_page(
+ tx: &mut Transaction<'_, Postgres>,
+ kb_id: Uuid,
+ after: Option<Uuid>,
+) -> AppResult<Vec<ExportFactConflict>> {
+ let page: Vec<ExportFactConflict> = sqlx::query_as(
+ "SELECT c.id, c.old_fact_id, c.new_fact_id, c.reason, c.created_at,
+ c.status, c.resolution, c.resolved_at,
+ of_.kb_id AS old_fact_kb, nf.kb_id AS new_fact_kb
+ FROM fact_conflicts c
+ LEFT JOIN facts of_ ON of_.id = c.old_fact_id
+ LEFT JOIN facts nf ON nf.id = c.new_fact_id
+ WHERE c.kb_id = $1 AND ($2 IS NULL OR c.id > $2)
+ ORDER BY c.id LIMIT $3",
+ )
+ .bind(kb_id)
+ .bind(after)
+ .bind(PAGE)
+ .fetch_all(&mut **tx)
+ .await?;
+ let mut violations = Vec::new();
+ for c in &page {
+ tally(
+ &mut violations,
+ "conflict.old_fact",
+ foreign(c.old_fact_kb, kb_id) as i64,
+ );
+ tally(
+ &mut violations,
+ "conflict.new_fact",
+ foreign(c.new_fact_kb, kb_id) as i64,
+ );
+ }
+ if !violations.is_empty() {
+ return Err(cross_kb_error(&violations));
+ }
+ Ok(page)
+}
+
+/// 一条「当前数据与当前判据不一致」的发现。`open` 意味着它已对账于**当前**
+/// 本体(0062)——改判据的那笔事务把它收编或重检出过了。
+///
+/// 行是**可变的当前状态**,不是追加历史:resolved 之后又被算出来的同一处
+/// 违规会重开,`detected_at` 记的是最近一次检出/重开的时刻;更早的循环
+/// 不留在行里,导出也就照实不说它。
+#[derive(Debug, Clone, sqlx::FromRow)]
+pub struct ExportAxiomViolation {
+ pub id: Uuid,
+ pub kind: String,
+ pub left_fact: Uuid,
+ pub right_fact: Uuid,
+ /// 环按顺序的完整事实链(其余种类存检出的证据,自环/签名为空)
+ pub path: Vec<Uuid>,
+ pub status: String,
+ /// fact_retracted | fact_closed | axiom_relaxed | accepted | criterion_changed
+ pub resolution: Option<String>,
+ /// 最近一次检出或重开的时刻(不是第一次发现)
+ pub detected_at: DateTime<Utc>,
+ /// 不再是 open 的时刻(收编或人裁)
+ pub decided_at: Option<DateTime<Utc>>,
+ /// 以下两列**只在 open 行上解析**(0062):open = 已按当前本体对账,
+ /// 判据必然指得回去;resolved 的行不连判据——促成它结案的本体可能早已不在
+ pub criterion_predicate: Option<Uuid>,
+ /// 判据的词:kind 本身,或 derived_contradiction 记下的 detail.axiom
+ /// (self_loop | asymmetry | cycle | functional | inverse_functional | signature)
+ pub criterion_axiom: Option<String>,
+ /// 被引行的 kb,随行原子地一并选出
+ pub left_kb: Option<Uuid>,
+ pub right_kb: Option<Uuid>,
+ pub criterion_predicate_kb: Option<Uuid>,
+ /// path 里是否有越库或悬空的事实(环的证据链会按序铸成 IRI)
+ pub foreign_path: bool,
+}
+
+/// detail.predicate_id 存成 JSON 文本,落到 uuid 前先验形——
+/// 畸形的值宁可解析失败(→ 拒导)也不能静默指错关系
+const UUID_TEXT_RE: &str =
+ "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$";
+
+/// open 行的判据谓词解析式:derived_contradiction 的判据挂在 detail 记下的
+/// **派生谓词**上(axiom 声明在它那里);其余种类就是 left_fact 的谓词。
+/// 分页与预检共用同一串——两处各写一份迟早漂移
+fn criterion_predicate_sql() -> String {
+ format!(
+ "CASE WHEN v.kind = 'derived_contradiction'
+ THEN CASE WHEN v.detail->>'predicate_id' ~ '{UUID_TEXT_RE}'
+ THEN (v.detail->>'predicate_id')::uuid END
+ ELSE lf.predicate_id END"
+ )
+}
+
+/// open 行的判据词解析式:derived_contradiction 看 detail.axiom,其余看 kind
+const CRITERION_AXIOM_SQL: &str =
+ "CASE WHEN v.kind = 'derived_contradiction' THEN v.detail->>'axiom' ELSE v.kind END";
+
+/// kind / detail.axiom 的存储值 → 判据该用的词(0062 §4)。
+/// signature 的判据是一对签名(行不记哪一侧破的,合同也不装知道)。
+/// None = 不认识的存储值——open 行撞上它就要拒导,不能静默丢判据
+fn criterion_terms(axiom: &str) -> Option<&'static [&'static str]> {
+ Some(match axiom {
+ "self_loop" => &["owl:IrreflexiveProperty"],
+ "asymmetry" => &["owl:AsymmetricProperty"],
+ "cycle" => &["owl:TransitiveProperty"],
+ "functional" => &["owl:FunctionalProperty"],
+ "inverse_functional" => &["owl:InverseFunctionalProperty"],
+ "signature" => &["rdfs:domain", "rdfs:range"],
+ _ => return None,
+ })
+}
+
+impl ExportAxiomViolation {
+ /// 判据的 RDF 词项(`utopia:criterion` 的宾语,可能不止一个)。
+ /// open 行必然取得到——取不到说明存储值进了合同不认识的东西,拒导而不是瞎编
+ pub fn criterion_terms(&self) -> Option<&'static [&'static str]> {
+ self.criterion_axiom.as_deref().and_then(criterion_terms)
+ }
+}
+
+pub async fn axiom_violations_page(
+ tx: &mut Transaction<'_, Postgres>,
+ kb_id: Uuid,
+ after: Option<Uuid>,
+) -> AppResult<Vec<ExportAxiomViolation>> {
+ let page: Vec<ExportAxiomViolation> = sqlx::query_as(&format!(
+ "SELECT v.id, v.kind, v.left_fact, v.right_fact, v.path, v.status, v.resolution,
+ v.detected_at, v.decided_at,
+ CASE WHEN v.status = 'open' THEN {criterion_predicate}
+ END AS criterion_predicate,
+ CASE WHEN v.status = 'open' THEN {criterion_axiom}
+ END AS criterion_axiom,
+ lf.kb_id AS left_kb, rf.kb_id AS right_kb, cp.kb_id AS criterion_predicate_kb,
+ EXISTS(SELECT 1 FROM unnest(v.path) AS member(fact_id)
+ WHERE NOT EXISTS(SELECT 1 FROM facts pf
+ WHERE pf.id = member.fact_id
+ AND pf.kb_id = v.kb_id)) AS foreign_path
+ FROM axiom_violations v
+ LEFT JOIN facts lf ON lf.id = v.left_fact
+ LEFT JOIN facts rf ON rf.id = v.right_fact
+ LEFT JOIN relation_types cp ON cp.id =
+ CASE WHEN v.status = 'open' THEN {criterion_predicate} END
+ WHERE v.kb_id = $1 AND ($2 IS NULL OR v.id > $2)
+ ORDER BY v.id LIMIT $3",
+ criterion_predicate = criterion_predicate_sql(),
+ criterion_axiom = CRITERION_AXIOM_SQL,
+ ))
+ .bind(kb_id)
+ .bind(after)
+ .bind(PAGE)
+ .fetch_all(&mut **tx)
+ .await?;
+ let mut violations = Vec::new();
+ let mut unresolvable = Vec::new();
+ for v in &page {
+ tally(
+ &mut violations,
+ "violation.left_fact",
+ foreign(v.left_kb, kb_id) as i64,
+ );
+ tally(
+ &mut violations,
+ "violation.right_fact",
+ foreign(v.right_kb, kb_id) as i64,
+ );
+ tally(&mut violations, "violation.path", v.foreign_path as i64);
+ if v.status == "open" {
+ // open 的承诺是「已按当前本体对账」:判据指不回去,这份导出就在
+ // 替一个坏掉的不变式背书——拒导与越库同一条纪律
+ if v.criterion_predicate.is_none() || v.criterion_terms().is_none() {
+ unresolvable.push(CrossKbViolation {
+ edge: "violation.criterion".into(),
+ rows: 1,
+ });
+ } else {
+ tally(
+ &mut violations,
+ "violation.criterion",
+ foreign(v.criterion_predicate_kb, kb_id) as i64,
+ );
+ }
+ }
+ }
+ if !violations.is_empty() {
+ return Err(cross_kb_error(&violations));
+ }
+ if !unresolvable.is_empty() {
+ let detail = unresolvable
+ .iter()
+ .map(|v| format!("{}: {} row(s)", v.edge, v.rows))
+ .collect::<Vec<_>>()
+ .join("; ");
+ return Err(AppError::invalid_detail(
+ "unresolvable_criterion",
+ "export refused: an open axiom violation has no governing criterion to link",
+ detail,
+ ));
+ }
+ Ok(page)
+}
+
+/// 认知状态的**流前预检**(0062):分页查询里也带同一批检查,但那时文件头
+/// 已经发出去,只能截断——所以先在这里数一遍,有一行就整份拒。
+///
+/// 三类问题:
+/// - **越库/悬空**:conflict 的两条事实、violation 的 left/right/path 成员必须
+/// 是本库的 facts 行(悬空=铸出不存在的 IRI,与越库同罪)
+/// - **合同外的值**:status/resolution/kind/reason 落进词表以外、或
+/// status↔resolution 不自洽(open 带着 resolution 之类)的脏行——
+/// `fact_conflicts.reason` 没有 CHECK 挡着,其余列有但 CHECK 只在新写时
+/// 生效,存量脏行一样照实拒,不 echo 出去
+/// - **open 行判据不可解析**:open = 已对账于当前本体,判据必然指得回本库
+/// 一条关系与一个合同认识的词(derived_contradiction 的 detail.predicate_id
+/// 畸形也算——静默退到 left_fact 的谓词等于瞎指)
+pub async fn contest_integrity(tx: &mut Transaction<'_, Postgres>, kb_id: Uuid) -> AppResult<()> {
+ #[derive(sqlx::FromRow)]
+ struct ContestViolation {
+ edge: String,
+ kind: String,
+ rows: i64,
+ }
+ let violations: Vec<ContestViolation> = sqlx::query_as(&format!(
+ "SELECT edge, kind, count(*) AS rows FROM (
+ SELECT 'conflict.old_fact' AS edge, 'cross_kb' AS kind
+ FROM fact_conflicts c LEFT JOIN facts f ON f.id = c.old_fact_id
+ WHERE c.kb_id = $1 AND f.kb_id IS DISTINCT FROM c.kb_id
+ UNION ALL
+ SELECT 'conflict.new_fact', 'cross_kb'
+ FROM fact_conflicts c LEFT JOIN facts f ON f.id = c.new_fact_id
+ WHERE c.kb_id = $1 AND f.kb_id IS DISTINCT FROM c.kb_id
+ UNION ALL
+ SELECT 'conflict.vocabulary', 'contract'
+ FROM fact_conflicts c
+ WHERE c.kb_id = $1 AND (
+ COALESCE(c.status, '') NOT IN ('open', 'resolved', 'withdrawn')
+ OR COALESCE(c.reason, '') NOT IN
+ ('no_time', 'simultaneous', 'low_confidence', 'described_evidence')
+ OR c.resolution IS NOT NULL
+ AND c.resolution NOT IN ('closed', 'kept_both', 'rejected_new')
+ -- 0051:resolved=人裁了(resolution 必有值),其余状态不该有
+ OR c.status = 'resolved' AND c.resolution IS NULL
+ OR c.status IN ('open', 'withdrawn') AND c.resolution IS NOT NULL)
+ UNION ALL
+ SELECT 'violation.left_fact', 'cross_kb'
+ FROM axiom_violations v LEFT JOIN facts f ON f.id = v.left_fact
+ WHERE v.kb_id = $1 AND f.kb_id IS DISTINCT FROM v.kb_id
+ UNION ALL
+ SELECT 'violation.right_fact', 'cross_kb'
+ FROM axiom_violations v LEFT JOIN facts f ON f.id = v.right_fact
+ WHERE v.kb_id = $1 AND f.kb_id IS DISTINCT FROM v.kb_id
+ UNION ALL
+ SELECT 'violation.path', 'cross_kb'
+ FROM axiom_violations v
+ WHERE v.kb_id = $1 AND EXISTS(
+ SELECT 1 FROM unnest(v.path) AS member(fact_id)
+ WHERE NOT EXISTS(SELECT 1 FROM facts pf
+ WHERE pf.id = member.fact_id
+ AND pf.kb_id = v.kb_id))
+ UNION ALL
+ SELECT 'violation.vocabulary', 'contract'
+ FROM axiom_violations v
+ WHERE v.kb_id = $1 AND (
+ COALESCE(v.kind, '') NOT IN
+ ('self_loop', 'asymmetry', 'cycle', 'functional',
+ 'inverse_functional', 'signature', 'derived_contradiction')
+ OR COALESCE(v.status, '') NOT IN ('open', 'resolved')
+ OR v.resolution IS NOT NULL AND v.resolution NOT IN
+ ('fact_retracted', 'fact_closed', 'axiom_relaxed', 'accepted',
+ 'criterion_changed')
+ -- 写路从来都是成对落(决定+时间戳);open 带着 resolution
+ -- 或 resolved 丢了 resolution 都是自相矛盾的脏行
+ OR v.status = 'resolved' AND v.resolution IS NULL
+ OR v.status = 'open' AND v.resolution IS NOT NULL)
+ UNION ALL
+ SELECT 'violation.criterion', 'unresolvable'
+ FROM axiom_violations v
+ LEFT JOIN facts lf ON lf.id = v.left_fact
+ WHERE v.kb_id = $1 AND v.status = 'open' AND (
+ COALESCE({criterion_axiom}, '') NOT IN
+ ('self_loop', 'asymmetry', 'cycle', 'functional',
+ 'inverse_functional', 'signature')
+ OR NOT EXISTS(
+ SELECT 1 FROM relation_types rt
+ WHERE rt.kb_id = v.kb_id
+ AND rt.id = {criterion_predicate}))
+ ) t GROUP BY edge, kind",
+ criterion_axiom = CRITERION_AXIOM_SQL,
+ criterion_predicate = criterion_predicate_sql(),
+ ))
+ .bind(kb_id)
+ .fetch_all(&mut **tx)
+ .await?;
+ let cross_kb: Vec<CrossKbViolation> = violations
+ .iter()
+ .filter(|v| v.kind == "cross_kb")
+ .map(|v| CrossKbViolation {
+ edge: v.edge.clone(),
+ rows: v.rows,
+ })
+ .collect();
+ if !cross_kb.is_empty() {
+ return Err(cross_kb_error(&cross_kb));
+ }
+ let rest: Vec<&ContestViolation> = violations.iter().filter(|v| v.kind != "cross_kb").collect();
+ if !rest.is_empty() {
+ let detail = rest
+ .iter()
+ .map(|v| format!("{}: {} row(s)", v.edge, v.rows))
+ .collect::<Vec<_>>()
+ .join("; ");
+ return Err(AppError::invalid_detail(
+ "contested_state_contract",
+ "export refused: contested-state rows fall outside the contract vocabulary or an open violation has no resolvable criterion",
+ detail,
+ ));
+ }
+ Ok(())
+}
diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rs
index 5b96f2eb..978c1223 100644
--- a/crates/utopia-store/src/ontology.rs
+++ b/crates/utopia-store/src/ontology.rs
@@ -1,7 +1,8 @@
//! 本体编辑器仓储:类型/关系 CRUD(带使用量与删除保护)+ 未匹配统计。
use pgvector::Vector;
-use sqlx::PgPool;
+use sqlx::{PgConnection, PgPool};
+use std::collections::HashSet;
use utopia_core::models::{
EntityInstance, EntityTypeView, OntologyImportView, OntologyMiss, RelationAxioms,
RelationTypeView, TypeCandidate,
@@ -171,7 +172,7 @@ pub async fn create_entity_type(
}
_ => AppError::Db(e),
})?;
- set_parents(pool, kb_id, id, parents).await?;
+ set_parents(&mut *pool.acquire().await?, kb_id, id, parents).await?;
Ok(id)
}
@@ -191,6 +192,21 @@ pub async fn update_entity_type(
description: &str,
) -> AppResult<()> {
validate_shape(shape)?;
+ let mut tx = pool.begin().await?;
+ // 父链是签名判据(0062):违规按祖先链算。只比父集——label、颜色那些
+ // 不改判据的字段照常写,不必跑检测
+ let old_parents: Vec<Uuid> =
+ sqlx::query_scalar("SELECT parent_id FROM entity_type_parents WHERE child_id = $1")
+ .bind(id)
+ .fetch_all(&mut *tx)
+ .await?;
+ let parents_changed =
+ parents.len() != old_parents.len() || !parents.iter().all(|p| old_parents.contains(p));
+ let was_detected = if parents_changed {
+ Some(crate::reasoning::detection_keys(&mut tx, kb_id).await?)
+ } else {
+ None
+ };
let res = sqlx::query(
"UPDATE entity_types SET label = $3, color = COALESCE($4, color), shape = $5,
description = $6, updated_at = now()
@@ -202,12 +218,16 @@ pub async fn update_entity_type(
.bind(color)
.bind(shape)
.bind(description)
- .execute(pool)
+ .execute(&mut *tx)
.await?;
if res.rows_affected() == 0 {
return Err(AppError::NotFound);
}
- set_parents(pool, kb_id, id, parents).await?;
+ set_parents(&mut tx, kb_id, id, parents).await?;
+ if let Some(was) = was_detected {
+ crate::reasoning::reconcile_ontology(&mut tx, kb_id, &was).await?;
+ }
+ tx.commit().await?;
Ok(())
}
@@ -216,8 +236,8 @@ pub async fn update_entity_type(
/// **先查环再写**。单父时代只需要挡自环,一条链天然不会成环;DAG 里 A→B→A
/// 完全可能,而 `type_matches_domain` 沿父链上溯,成环就是死循环。
/// SQL 拦不住这个——外键只挡自环,更长的要应用来查。
-pub async fn set_parents(
- pool: &PgPool,
+async fn set_parents(
+ conn: &mut PgConnection,
kb_id: Uuid,
child: Uuid,
parents: &[Uuid],
@@ -240,7 +260,7 @@ pub async fn set_parents(
)
.bind(child)
.bind(parents)
- .fetch_one(pool)
+ .fetch_one(&mut *conn)
.await?;
if cycles > 0 {
return Err(AppError::invalid(
@@ -251,7 +271,7 @@ pub async fn set_parents(
}
sqlx::query("DELETE FROM entity_type_parents WHERE child_id = $1")
.bind(child)
- .execute(pool)
+ .execute(&mut *conn)
.await?;
for (i, p) in parents.iter().enumerate() {
sqlx::query(
@@ -262,7 +282,7 @@ pub async fn set_parents(
.bind(p)
// 第一个当主父:界面上说明了"画在第一个下面",不再多一个控件
.bind(i == 0)
- .execute(pool)
+ .execute(&mut *conn)
.await?;
}
let _ = kb_id;
@@ -270,18 +290,38 @@ pub async fn set_parents(
}
pub async fn delete_entity_type(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<()> {
+ let mut tx = pool.begin().await?;
let (usage,): (i64,) = sqlx::query_as("SELECT count(*) FROM entities WHERE type_id = $1")
.bind(id)
- .fetch_one(pool)
+ .fetch_one(&mut *tx)
.await?;
if usage > 0 {
return Err(AppError::Conflict(format!(
"Cannot delete: {usage} entities use this type"
)));
}
+ // 这个类若牵着签名判据——是某个类的父类,或挂在某条关系的
+ // domain / range 上——删掉它就改了「哪些违规成立」(0062)。
+ // 动笔前把旧判据下的检出键集记下来,提交前对账
+ let affects_criteria: bool = sqlx::query_scalar(
+ "SELECT EXISTS(SELECT 1 FROM entity_type_parents WHERE parent_id = $1)
+ OR EXISTS(SELECT 1 FROM relation_type_domains WHERE entity_type_id = $1)
+ OR EXISTS(SELECT 1 FROM relation_type_ranges WHERE entity_type_id = $1)",
+ )
+ .bind(id)
+ .fetch_one(&mut *tx)
+ .await?;
+ let was_detected = if affects_criteria {
+ Some(crate::reasoning::detection_keys(&mut tx, kb_id).await?)
+ } else {
+ None
+ };
// 只剩这一个 domain 的属性随类一起走:属性必须挂在类上,
// 留一个没有 domain 的属性等于留一个不会出现在任何地方的死行。
- // 还挂在别的类上的则只掉一条关联(外键 CASCADE 负责)
+ // 还挂在别的类上的则只掉一条关联(外键 CASCADE 负责)。
+ // 连带效果(0070 的 FK CASCADE):属性没了 → 用它做谓词的事实没了 →
+ // 指向那些事实的违规行也被物理删掉。这些行不走 `criterion_changed`——
+ // 它们的判据没换,是事实本身没了,与 `run` 对消失事实的清陈同一条规矩
sqlx::query(
"DELETE FROM relation_types r
WHERE r.kind = 'attribute' AND r.kb_id = $1
@@ -292,18 +332,22 @@ pub async fn delete_entity_type(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResu
)
.bind(kb_id)
.bind(id)
- .execute(pool)
+ .execute(&mut *tx)
.await?;
let res = sqlx::query("DELETE FROM entity_types WHERE id = $2 AND kb_id = $1 AND NOT builtin")
.bind(kb_id)
.bind(id)
- .execute(pool)
+ .execute(&mut *tx)
.await?;
if res.rows_affected() == 0 {
return Err(AppError::Conflict(
"Built-in types cannot be deleted".into(),
));
}
+ if let Some(was) = was_detected {
+ crate::reasoning::reconcile_ontology(&mut tx, kb_id, &was).await?;
+ }
+ tx.commit().await?;
Ok(())
}
@@ -347,7 +391,7 @@ fn validate_attribute_fields(
/// 子属性不能是自己(DB 有 CHECK,但撞上去是 500,得在这里给出人话)。
/// 而**逆是自己允许**——那等于对称,R0 会提示改用 `symmetric` 更直白,不算错。
async fn validate_property_links(
- pool: &PgPool,
+ conn: &mut PgConnection,
kb_id: Uuid,
self_id: Option<Uuid>,
kind: &str,
@@ -374,7 +418,7 @@ async fn validate_property_links(
sqlx::query_as("SELECT kind FROM relation_types WHERE id = $1 AND kb_id = $2")
.bind(target)
.bind(kb_id)
- .fetch_optional(pool)
+ .fetch_optional(&mut *conn)
.await?;
match ok {
// 不区分「不存在」与「在别的库」:能问出哪个 UUID 存在于别处,
@@ -421,7 +465,7 @@ pub async fn create_relation_type(
validate_attribute_fields(kind, domains, datatype)?;
let label = &lower_camel(label);
// 新建的行 id 还不存在,指向自己无从谈起——所以 self_id 传 None
- validate_property_links(pool, kb_id, None, kind, ax).await?;
+ validate_property_links(&mut *pool.acquire().await?, kb_id, None, kind, ax).await?;
let is_attr = kind == "attribute";
let id = Uuid::now_v7();
sqlx::query(
@@ -461,14 +505,20 @@ pub async fn create_relation_type(
_ => AppError::Db(e),
})?;
// attribute 不写 range:它的值域是字面量类型,落在 datatype 上
- set_domains_ranges(pool, id, domains, if is_attr { &[] } else { ranges }).await?;
+ set_domains_ranges(
+ &mut *pool.acquire().await?,
+ id,
+ domains,
+ if is_attr { &[] } else { ranges },
+ )
+ .await?;
Ok(id)
}
/// 覆盖式写入 domain / range。**先删后插**,所以它既能用于新建也能用于重导入,
/// 且不会留下上一轮的残余。
async fn set_domains_ranges(
- pool: &PgPool,
+ conn: &mut PgConnection,
relation_type_id: Uuid,
domains: &[Uuid],
ranges: &[Uuid],
@@ -479,7 +529,7 @@ async fn set_domains_ranges(
] {
sqlx::query(&format!("DELETE FROM {table} WHERE relation_type_id = $1"))
.bind(relation_type_id)
- .execute(pool)
+ .execute(&mut *conn)
.await?;
if ids.is_empty() {
continue;
@@ -492,7 +542,7 @@ async fn set_domains_ranges(
))
.bind(relation_type_id)
.bind(ids)
- .execute(pool)
+ .execute(&mut *conn)
.await?;
}
Ok(())
@@ -602,11 +652,16 @@ pub async fn update_relation_type(
description: &str,
datatype: Option<&str>,
unit: Option<&str>,
- // None = 不动。不管 domain 的调用方(属性表单)传 None,
- // 否则一次不相干的改名就会把属性的 domain 清空
+ // 整组语义:两侧都 None = 签名不动;任一侧 Some = 两侧都按传入值重写
+ // (没传的那一侧清空)。不管签名的调用方(如纯改公理位)必须两侧都传
+ // None——`domains=Some(..)` + `ranges=None` 会把 range 清空
domains: Option<&[Uuid]>,
ranges: Option<&[Uuid]>,
) -> AppResult<()> {
+ // 整条改动进一条事务:判据变了的话,落笔前要先记下旧本体下检出的违规,
+ // 落笔后按新本体重检、收编旧判据的行——`open` 的意思是「已对账于当前本体」
+ //(0062),不许留一行只对旧判据成立的 open 违规走出提交点
+ let mut tx = pool.begin().await?;
// 名字属性是内建的(0041):标成 functional 会让每个第二个名字都成一条冲突、
// 甚至把本名关掉;改名、改时态也一样没有正当用途
let name_attribute: Option<(bool,)> = sqlx::query_as(
@@ -614,7 +669,7 @@ pub async fn update_relation_type(
)
.bind(id)
.bind(kb_id)
- .fetch_optional(pool)
+ .fetch_optional(&mut *tx)
.await?;
if name_attribute == Some((true,)) {
return Err(AppError::invalid(
@@ -634,22 +689,81 @@ pub async fn update_relation_type(
"datatype must be text / number / date / bool".into(),
));
}
+ // 旧判据先取下来:公理位、时态、两条关系链、domain/range 一起决定
+ // 「哪些违规成立」。行不在就是 NotFound——UPDATE 反正会空
+ let old: Option<OldCriteria> = sqlx::query_as(
+ "SELECT kind, temporal, functional, inverse_functional, is_transitive,
+ is_symmetric, is_asymmetric, is_irreflexive, inverse_of, sub_property_of
+ FROM relation_types WHERE id = $1 AND kb_id = $2",
+ )
+ .bind(id)
+ .bind(kb_id)
+ .fetch_optional(&mut *tx)
+ .await?;
+ let Some(old) = old else {
+ return Err(AppError::NotFound);
+ };
// 指向别的关系的两条要先问过库:目标在不在本库、是不是关系。
// 只在真的填了的时候查——清空(两个都 None)没有目标可验
if ax.inverse_of.is_some() || ax.sub_property_of.is_some() {
- let row: Option<(String,)> =
- sqlx::query_as("SELECT kind FROM relation_types WHERE id = $1 AND kb_id = $2")
- .bind(id)
- .bind(kb_id)
- .fetch_optional(pool)
- .await?;
- let (kind,) = row.ok_or(AppError::NotFound)?;
- validate_property_links(pool, kb_id, Some(id), &kind, ax).await?;
+ validate_property_links(&mut tx, kb_id, Some(id), &old.kind, ax).await?;
}
- // kind 不可变(改它会让存量事实语义错乱)。domain/range 可改——
- // 它们是签名不是身份,"这个属性也适用于承包商" 是个正当的编辑。
- // datatype/unit 只对 attribute 行生效,datatype 缺省保持原值
- //
+ // domain/range 可改——它们是签名不是身份,"这个属性也适用于承包商" 是个正当的
+ // 编辑。kind 不可变(改它会让存量事实语义错乱)
+ let signature_touched = domains.is_some() || ranges.is_some();
+ let mut signature_changed = false;
+ let next_domains: &[Uuid] = domains.unwrap_or(&[]);
+ let next_ranges: &[Uuid] = if old.kind == "attribute" {
+ // 属性没有 range:它的值域是字面量类型,落在 datatype 上
+ &[]
+ } else {
+ ranges.unwrap_or(&[])
+ };
+ if signature_touched {
+ if old.kind == "attribute" && next_domains.is_empty() {
+ return Err(AppError::invalid(
+ "attr_needs_class",
+ "An attribute needs a class (domain)",
+ ));
+ }
+ let old_domains: HashSet<Uuid> = sqlx::query_scalar(
+ "SELECT entity_type_id FROM relation_type_domains WHERE relation_type_id = $1",
+ )
+ .bind(id)
+ .fetch_all(&mut *tx)
+ .await?
+ .into_iter()
+ .collect();
+ let old_ranges: HashSet<Uuid> = sqlx::query_scalar(
+ "SELECT entity_type_id FROM relation_type_ranges WHERE relation_type_id = $1",
+ )
+ .bind(id)
+ .fetch_all(&mut *tx)
+ .await?
+ .into_iter()
+ .collect();
+ signature_changed = old_domains != next_domains.iter().copied().collect::<HashSet<_>>()
+ || old_ranges != next_ranges.iter().copied().collect::<HashSet<_>>();
+ }
+ // label / description / datatype / unit 不进这里:它们不动判据,
+ // 改了不值得跑一遍检测
+ let criteria_changed = old.temporal != temporal
+ || old.functional != ax.functional
+ || old.inverse_functional != ax.inverse_functional
+ || old.is_transitive != ax.transitive
+ || old.is_symmetric != ax.symmetric
+ || old.is_asymmetric != ax.asymmetric
+ || old.is_irreflexive != ax.irreflexive
+ || old.inverse_of != ax.inverse_of
+ || old.sub_property_of != ax.sub_property_of
+ || signature_changed;
+ // 检出必须在写入**之前**:此刻库里还是旧本体,记下的正是「旧判据下
+ // 会算出来的违规」,提交前对照用
+ let was_detected = if criteria_changed {
+ Some(crate::reasoning::detection_keys(&mut tx, kb_id).await?)
+ } else {
+ None
+ };
// 两条链**跟着六位公理一起覆盖式写**:缺省 = 清空,不是「不动」。
// 与 `is_transitive` 那几位同一条规矩——它们是同一个表单里同时提交的
// 一组声明,一半覆盖一半保留才是真正会出事的语义
@@ -679,55 +793,76 @@ pub async fn update_relation_type(
.bind(ax.irreflexive)
.bind(ax.inverse_of)
.bind(ax.sub_property_of)
- .execute(pool)
+ .execute(&mut *tx)
.await?;
if res.rows_affected() == 0 {
return Err(AppError::NotFound);
}
- if domains.is_some() || ranges.is_some() {
- let (kind,): (String,) = sqlx::query_as("SELECT kind FROM relation_types WHERE id = $1")
- .bind(id)
- .fetch_one(pool)
- .await?;
- let next_domains = domains.unwrap_or(&[]);
- if kind == "attribute" && next_domains.is_empty() {
- return Err(AppError::invalid(
- "attr_needs_class",
- "An attribute needs a class (domain)",
- ));
- }
- // 属性没有 range:它的值域是字面量类型,落在 datatype 上
- let next_ranges: &[Uuid] = if kind == "attribute" {
- &[]
- } else {
- ranges.unwrap_or(&[])
- };
- set_domains_ranges(pool, id, next_domains, next_ranges).await?;
+ if signature_touched {
+ set_domains_ranges(&mut tx, id, next_domains, next_ranges).await?;
+ }
+ if let Some(was) = was_detected {
+ crate::reasoning::reconcile_ontology(&mut tx, kb_id, &was).await?;
}
+ tx.commit().await?;
Ok(())
}
+/// `relation_types` 一行里跟「哪些违规成立」有关的列(0062 对账用的旧判据快照)。
+/// label / description / datatype / unit 不在——它们不动判据
+#[derive(sqlx::FromRow)]
+struct OldCriteria {
+ kind: String,
+ temporal: String,
+ functional: bool,
+ inverse_functional: bool,
+ is_transitive: bool,
+ is_symmetric: bool,
+ is_asymmetric: bool,
+ is_irreflexive: bool,
+ inverse_of: Option<Uuid>,
+ sub_property_of: Option<Uuid>,
+}
+
pub async fn delete_relation_type(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<()> {
+ let mut tx = pool.begin().await?;
let (usage,): (i64,) = sqlx::query_as("SELECT count(*) FROM facts WHERE predicate_id = $1")
.bind(id)
- .fetch_one(pool)
+ .fetch_one(&mut *tx)
.await?;
if usage > 0 {
return Err(AppError::Conflict(format!(
"Cannot delete: {usage} facts use this relation"
)));
}
+ // 判据贡献不只「有没有人引用它」这一半:这行自己的旗标与出向
+ // inverse_of/sub_property_of 链接喂着别的谓词的派生链,rules_disagree
+ // 缺陷行也以谓词 id 指着它。枚举哪些列算判据已被证明会漏——删除又足够
+ // 稀少,不为省检测设门槛,一律记下旧判据下的检出键集(0062)
+ let was_detected = crate::reasoning::detection_keys(&mut tx, kb_id).await?;
+ // 0070 把这两条外键建成 DEFERRABLE 的 SET NULL——级联动作提交时才落地,
+ // 而对账检测要看见改完的判据,所以先在事务里显式断链
+ sqlx::query("UPDATE relation_types SET inverse_of = NULL WHERE inverse_of = $1")
+ .bind(id)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query("UPDATE relation_types SET sub_property_of = NULL WHERE sub_property_of = $1")
+ .bind(id)
+ .execute(&mut *tx)
+ .await?;
let res =
sqlx::query("DELETE FROM relation_types WHERE id = $2 AND kb_id = $1 AND NOT builtin")
.bind(kb_id)
.bind(id)
- .execute(pool)
+ .execute(&mut *tx)
.await?;
if res.rows_affected() == 0 {
return Err(AppError::Conflict(
"Built-in relations cannot be deleted".into(),
));
}
+ crate::reasoning::reconcile_ontology(&mut tx, kb_id, &was_detected).await?;
+ tx.commit().await?;
Ok(())
}
@@ -948,7 +1083,7 @@ pub async fn create_attribute_with_iri(
let Some((new_id,)) = row else {
return Ok(None);
};
- set_domains_ranges(pool, new_id, domains, &[]).await?;
+ set_domains_ranges(&mut *pool.acquire().await?, new_id, domains, &[]).await?;
Ok(Some(new_id))
}
@@ -996,7 +1131,7 @@ pub async fn create_relation_with_iri(
let Some((new_id,)) = row else {
return Ok(None);
};
- set_domains_ranges(pool, new_id, domains, ranges).await?;
+ set_domains_ranges(&mut *pool.acquire().await?, new_id, domains, ranges).await?;
Ok(Some(new_id))
}
@@ -1029,7 +1164,7 @@ pub async fn update_relation_from_import(
let Some((id,)) = row else {
return Ok(false);
};
- set_domains_ranges(pool, id, domains, ranges).await?;
+ set_domains_ranges(&mut *pool.acquire().await?, id, domains, ranges).await?;
Ok(true)
}
@@ -1441,22 +1576,50 @@ pub async fn attribute_from_unused_relation(
unit: Option<&str>,
) -> AppResult<Option<Uuid>> {
validate_attribute_fields("attribute", domains, Some(datatype))?;
- let row: Option<(Uuid,)> = sqlx::query_as(
- "UPDATE relation_types SET kind = 'attribute', datatype = $3, unit = $4,
- inverse_of = NULL, sub_property_of = NULL
- WHERE kb_id = $1 AND key = $2 AND kind = 'relation'
- AND NOT EXISTS (SELECT 1 FROM facts f WHERE f.predicate_id = relation_types.id)
- RETURNING id",
+ let mut tx = pool.begin().await?;
+ // 零事实不等于零判据:公理旗标与 inverse_of/sub_property_of 会让这条关系
+ // 成为派生目标(违规的 detail.predicate_id 指到它)。改判清了那些贡献,
+ // 按同一条对账规矩走(0062)——先记旧判据下的检出,写完再对账
+ let candidate: Option<(Uuid,)> = sqlx::query_as(
+ "SELECT id FROM relation_types
+ WHERE kb_id = $1 AND key = $2 AND kind = 'relation'
+ AND NOT EXISTS (SELECT 1 FROM facts f WHERE f.predicate_id = relation_types.id)",
)
.bind(kb_id)
.bind(key)
+ .fetch_optional(&mut *tx)
+ .await?;
+ let Some((id,)) = candidate else {
+ tx.rollback().await?;
+ return Ok(None);
+ };
+ let was_detected = crate::reasoning::detection_keys(&mut tx, kb_id).await?;
+ // 属性不声明判据:旗标与双向链接都清掉(axioms() 不按 kind 过滤,
+ // 留着它们等於留着一套无人问的公理)
+ sqlx::query(
+ "UPDATE relation_types SET kind = 'attribute', datatype = $2, unit = $3,
+ inverse_of = NULL, sub_property_of = NULL,
+ is_transitive = false, is_symmetric = false, is_asymmetric = false,
+ is_irreflexive = false, functional = false, inverse_functional = false
+ WHERE id = $1",
+ )
+ .bind(id)
.bind(datatype)
.bind(unit)
- .fetch_optional(pool)
+ .execute(&mut *tx)
.await?;
- let Some((id,)) = row else { return Ok(None) };
+ sqlx::query("UPDATE relation_types SET inverse_of = NULL WHERE inverse_of = $1")
+ .bind(id)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query("UPDATE relation_types SET sub_property_of = NULL WHERE sub_property_of = $1")
+ .bind(id)
+ .execute(&mut *tx)
+ .await?;
// domain / range 在各自的表里,不是列。属性没有 range——值域落在 datatype 上
- set_domains_ranges(pool, id, domains, &[]).await?;
+ set_domains_ranges(&mut tx, id, domains, &[]).await?;
+ crate::reasoning::reconcile_ontology(&mut tx, kb_id, &was_detected).await?;
+ tx.commit().await?;
Ok(Some(id))
}
diff --git a/crates/utopia-store/src/reasoning.rs b/crates/utopia-store/src/reasoning.rs
index 391ce6e6..0db87acd 100644
--- a/crates/utopia-store/src/reasoning.rs
+++ b/crates/utopia-store/src/reasoning.rs
@@ -13,7 +13,7 @@
//! 什么都不做——已经在库里的那一行,无论 open 还是 resolved,都按原样留着。
use serde_json::json;
-use sqlx::PgPool;
+use sqlx::{PgConnection, PgPool, Postgres, Transaction};
use std::collections::{HashMap, HashSet};
use utopia_core::models::{AxiomViolation, DerivedFactView, OntologyDefect};
/// 规则种类的字面量。用 &'static str 而不是枚举:它直接进 SQL 也直接做键
@@ -60,7 +60,7 @@ const MAX_CLASHES_PER_PREDICATE: usize = 50;
/// 会跳过),白白占内存。而且这个条数本身有意义——它是「有没有判据」的度量,
/// 报告里要用。
#[allow(clippy::type_complexity)]
-async fn axioms(pool: &PgPool, kb_id: Uuid) -> AppResult<HashMap<Uuid, Axioms>> {
+async fn axioms(conn: &mut PgConnection, kb_id: Uuid) -> AppResult<HashMap<Uuid, Axioms>> {
let rows: Vec<(
Uuid,
bool,
@@ -81,7 +81,7 @@ async fn axioms(pool: &PgPool, kb_id: Uuid) -> AppResult<HashMap<Uuid, Axioms>>
OR inverse_of IS NOT NULL OR sub_property_of IS NOT NULL)",
)
.bind(kb_id)
- .fetch_all(pool)
+ .fetch_all(&mut *conn)
.await?;
let mut map: HashMap<Uuid, Axioms> = rows
.into_iter()
@@ -147,7 +147,7 @@ async fn axioms(pool: &PgPool, kb_id: Uuid) -> AppResult<HashMap<Uuid, Axioms>>
///
/// `only` 给了就只看这些事实(合并之后对搬动过的那几条立刻查);None 是全量。
pub async fn signature_breaks(
- pool: &PgPool,
+ conn: &mut PgConnection,
kb_id: Uuid,
only: Option<&[Uuid]>,
) -> AppResult<Vec<Uuid>> {
@@ -182,7 +182,7 @@ pub async fn signature_breaks(
)
.bind(kb_id)
.bind(only)
- .fetch_all(pool)
+ .fetch_all(&mut *conn)
.await?;
Ok(rows.into_iter().map(|(id,)| id).collect())
}
@@ -214,8 +214,28 @@ pub async fn record_signature_breaks(
Ok(inserted)
}
-/// 跑一遍检查,把结果落库。
-pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {
+/// 一次检测的全部读侧产物:断言边与公理取进来、规则候选解完不动点、五类检查
+/// 算出来、第六类(派生撞上断言)带着人读的细节。**只读不写**——`run` 与本体
+/// 事务里的对账共用同一套取数与过滤(0062)。
+struct Detection {
+ /// 这一轮算出来的违规全集(还没扣掉人认可过的并存组)
+ violations: Vec<Violation>,
+ /// `derived_contradiction` 的 detail 按 (left, right) 放——它指着不存在的行,
+ /// 落库时才贴到对应违规上
+ details: HashMap<(Uuid, Uuid), serde_json::Value>,
+ /// 环没搜完的谓词(#642):它们的 open 环行这一轮不判陈
+ cycles_capped: Vec<Uuid>,
+ /// 人认可过并存的互斥组:(种类, 组里的事实集)
+ accepted: Vec<(String, HashSet<Uuid>)>,
+ derivation: Derivation,
+ clashes: Contradictions,
+ names: Names,
+ edges: usize,
+ predicates_with_axioms: usize,
+ contradictions_capped: usize,
+}
+
+async fn detect(conn: &mut PgConnection, kb_id: Uuid) -> AppResult<Detection> {
// 与 `materialize` 同一次求解:候选里有规则推出的关系边,被拦下的也在——
// 队列报的正是那边拦下的(0017,0047 决定 3)
let Resolved {
@@ -225,7 +245,7 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {
asserted_ids,
checked,
..
- } = resolve(pool, kb_id).await?;
+ } = resolve(conn, kb_id).await?;
let Checked {
candidates: derivation,
candidate_rule,
@@ -239,7 +259,7 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {
let mut violations = checked.violations;
// 第五类不在纯逻辑引擎里:它要看实体的类型与谓词的 domain / range,那是库里的
// 东西。算出来后与其它四类走同一条落库与清陈规矩
- for fact in signature_breaks(pool, kb_id, None).await? {
+ for fact in signature_breaks(conn, kb_id, None).await? {
violations.push(Violation {
kind: Kind::Signature,
left: fact,
@@ -250,7 +270,7 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {
// 第六类(0017):推出来却落不了地的派生。与 `materialize` 用同一个函数算,
// 所以这里报的正是那边拦下的——两边各算一套的话,队列会跟图对不上
- let names = names_for(pool, &derivation, &clashes).await?;
+ let names = names_for(conn, &derivation, &clashes).await?;
let mut details: HashMap<(Uuid, Uuid), serde_json::Value> = HashMap::new();
let mut per_pred: HashMap<Uuid, usize> = HashMap::new();
let mut contradictions_capped = 0usize;
@@ -259,6 +279,8 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {
// 键与外键都要 `facts` 里的行。链经过规则推出的关系边时,最后一条前提是
// 它的临时 id——每轮都不同——退到链上最后一条断言;自环的 `against` 也是它
let Some(&last) = d.premises.iter().rev().find(|p| asserted_ids.contains(p)) else {
+ // 整条前提链都是规则推出的临时 id:没有可落库的键与外键(队列的行
+ // 必须回到 `facts`),这个撞法不落行——`check` 的 blocked 侧仍然拦它
continue;
};
let against = if asserted_ids.contains(&c.against) {
@@ -301,46 +323,66 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {
kind: Kind::DerivedContradiction,
left: against,
right: last,
- path: d.premises.clone(),
+ // 证据链只留断言 id:链经规则推出的关系边时 premises 里混着那一轮的
+ // 临时 id(0047 决定 3)——它不属于任何表,出库后永远解析不出。落库的
+ // path 是给人看、给导出点名的证据链,成员必须回得到 `facts` 的行
+ path: d
+ .premises
+ .iter()
+ .copied()
+ .filter(|p| asserted_ids.contains(p))
+ .collect(),
});
}
- let mut report = Report {
+ let accepted = accepted_groups(conn, kb_id).await?;
+ Ok(Detection {
edges: timed.len(),
predicates_with_axioms: axioms.len(),
- found: violations.len(),
- contradictions: details.len(),
contradictions_capped,
- rules_disagree: clashes.between_derivations.len(),
- cycles_capped: cycles_capped.len(),
- ..Default::default()
- };
+ cycles_capped,
+ accepted,
+ derivation,
+ clashes,
+ names,
+ violations,
+ details,
+ })
+}
- let accepted = accepted_groups(pool, kb_id).await?;
+/// 人认可过「这几条可以并存」,这一轮的组又全在那几条里——比如其中一条后来
+/// 撤了,剩下的组首尾变了、键也变了——仍然是那句认可管着,不再端上来。
+/// 组里有一条认可时没见过的,就不拦:那是新情况
+fn suppressed(v: &Violation, accepted: &[(String, HashSet<Uuid>)]) -> bool {
+ is_grouped(v.kind)
+ && accepted
+ .iter()
+ .any(|(k, facts)| k == v.kind.as_str() && v.path.iter().all(|f| facts.contains(f)))
+}
- // 事务里做,否则「插新的」与「清陈旧的」之间有个窗口,那一瞬间 Review 页
- // 会短暂地少东西
- let mut tx = pool.begin().await?;
- let mut fresh: Vec<Uuid> = Vec::with_capacity(violations.len());
- for v in &violations {
+/// 一轮检测的落库侧:违规按行键 upsert(证据刷成这一轮的),resolved 的破约行
+/// 重开;**没算出来的 open 行不在这一层处置**——`run` 删掉它们,本体事务里的
+/// 对账把它们分档(0062)。返回「这一轮仍成立」的行 id 与 (新插, 重开) 计数。
+async fn settle_violations(
+ tx: &mut Transaction<'_, Postgres>,
+ kb_id: Uuid,
+ det: &Detection,
+) -> AppResult<(Vec<Uuid>, usize, usize)> {
+ let mut fresh: Vec<Uuid> = Vec::with_capacity(det.violations.len());
+ let mut inserted = 0usize;
+ let mut reopened = 0usize;
+ for v in &det.violations {
let Violation {
kind,
left,
right,
path,
} = v;
- let grouped = is_grouped(*kind);
- // 人认可过「这几条可以并存」,这一轮的组又全在那几条里——比如其中一条后来
- // 撤了,剩下的组首尾变了、键也变了——仍然是那句认可管着,不再端上来。
- // 组里有一条认可时没见过的,就不在这里拦:那是新情况
- if grouped
- && accepted
- .iter()
- .any(|(k, facts)| k == kind.as_str() && path.iter().all(|f| facts.contains(f)))
- {
+ if suppressed(v, &det.accepted) {
continue;
}
- let detail = details
+ let detail = det
+ .details
.get(&(*left, *right))
.cloned()
.unwrap_or_else(|| json!({}));
@@ -360,8 +402,9 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {
//
// 无论新插的还是本来就在的,都算「这一轮仍然成立」。
// 本来就在而且 resolved 的要再看一眼:`fact_retracted` / `fact_closed` /
- // `axiom_relaxed` 都是「世界会变」的承诺——事实没了、区间闭了、公理放宽了,
- // 违规就不该再算出来。又算出来了,承诺就是没兑现,那行回到 open,人再看一次。
+ // `axiom_relaxed` / `criterion_changed` 都是「世界会变」的承诺——事实没了、
+ // 区间闭了、判据换了,违规就不该再算出来。又算出来了,承诺就是没兑现,
+ // 那行回到 open,人再看一次。
// `accepted` 是有意并存,重算多少次都沉默(#202)——只要还是认可时那几条。
// 互斥的组走到这里说明上面没拦住:同一个键下多了一条,那行也回到 open
// 两条部分唯一索引各管一类,冲突目标要把索引的 WHERE 原样写出来才推断得到
@@ -389,13 +432,14 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {
.bind(right)
.bind(path)
.bind(&detail)
- .fetch_one(&mut *tx)
+ .fetch_one(&mut **tx)
.await?;
if is_new {
- report.inserted += 1;
+ inserted += 1;
}
+ let grouped = is_grouped(*kind);
let broken = match resolution.as_deref() {
- Some("fact_retracted" | "fact_closed" | "axiom_relaxed") => true,
+ Some("fact_retracted" | "fact_closed" | "axiom_relaxed" | "criterion_changed") => true,
Some("accepted") => grouped,
_ => false,
};
@@ -407,9 +451,9 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {
WHERE id = $1",
)
.bind(keep)
- .execute(&mut *tx)
+ .execute(&mut **tx)
.await?;
- report.reopened += 1;
+ reopened += 1;
}
fresh.push(keep);
}
@@ -417,7 +461,7 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {
// 环没搜完的谓词,上一轮的 open 环这一轮不清(#642):没搜到不等于不存在。
// 撞上上限时报出的是按数据排定的那一批,数据不变就是同一批;数据变了,旧的那几行
// 也宁可留着等人看,不能因为这一轮搜不到就当它没了
- if !cycles_capped.is_empty() {
+ if !det.cycles_capped.is_empty() {
let kept: Vec<Uuid> = sqlx::query_scalar(
"SELECT v.id FROM axiom_violations v
JOIN facts f ON f.id = v.left_fact
@@ -425,37 +469,32 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {
AND f.predicate_id = ANY($2)",
)
.bind(kb_id)
- .bind(&cycles_capped)
- .fetch_all(&mut *tx)
+ .bind(&det.cycles_capped)
+ .fetch_all(&mut **tx)
.await?;
fresh.extend(kept);
}
+ Ok((fresh, inserted, reopened))
+}
- // 这一轮没算出来的 open 行是陈的:事实被撤了,或者公理放宽了。
- // resolved 的不动——那是人的决定,不是派生状态
- let cleared = sqlx::query(
- "DELETE FROM axiom_violations
- WHERE kb_id = $1 AND status = 'open' AND NOT (id = ANY($2))",
- )
- .bind(kb_id)
- .bind(&fresh)
- .execute(&mut *tx)
- .await?;
- report.cleared = cleared.rows_affected() as usize;
-
- // 派生之间互撞的按规则对进 `ontology_defects`——根子是那两条声明,不是哪条事实。
- // 同一对谓词上可能有几种撞法(functional 与 asymmetric 各撞各的),唯一键只到
- // 谓词对,所以合成一行,几种撞法都写进 detail
+/// 派生之间互撞的按规则对进 `ontology_defects`——根子是那两条声明,不是哪条事实。
+/// 同一对谓词上可能有几种撞法(functional 与 asymmetric 各撞各的),唯一键只到
+/// 谓词对,所以合成一行,几种撞法都写进 detail
+async fn settle_defects(
+ tx: &mut Transaction<'_, Postgres>,
+ kb_id: Uuid,
+ det: &Detection,
+) -> AppResult<()> {
let mut by_pair: HashMap<(Uuid, Uuid), Vec<serde_json::Value>> = HashMap::new();
let mut order: Vec<(Uuid, Uuid)> = Vec::new();
- for rc in &clashes.between_derivations {
+ for rc in &det.clashes.between_derivations {
let triple = |i: usize| {
- let d = &derivation.facts[i];
+ let d = &det.derivation.facts[i];
format!(
"{} · {} · {}",
- names.entity(d.subject),
- names.predicate(d.predicate),
- names.entity(d.object)
+ det.names.entity(d.subject),
+ det.names.predicate(d.predicate),
+ det.names.entity(d.object)
)
};
let examples: Vec<serde_json::Value> = rc
@@ -470,9 +509,9 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {
}
by_pair.entry(key).or_default().push(json!({
"rule_a": rc.a.1.as_str(),
- "via_a": names.predicate(rc.a.0),
+ "via_a": det.names.predicate(rc.a.0),
"rule_b": rc.b.1.as_str(),
- "via_b": names.predicate(rc.b.0),
+ "via_b": det.names.predicate(rc.b.0),
"axiom": rc.axiom.as_str(),
"count": rc.pairs.len(),
"examples": examples,
@@ -497,7 +536,7 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {
.bind(key.0)
.bind(key.1)
.bind(json!({ "count": count, "rules": rules }))
- .fetch_one(&mut *tx)
+ .fetch_one(&mut **tx)
.await?;
fresh_defects.push(id);
}
@@ -508,12 +547,144 @@ pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {
)
.bind(kb_id)
.bind(&fresh_defects)
+ .execute(&mut **tx)
+ .await?;
+ Ok(())
+}
+
+/// 跑一遍检查,把结果落库。
+pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {
+ // 检测与落库进同一条事务:读侧看见的是这条事务启动后每条语句前的最新提交,
+ // 与原先池上各取一条连接等价;写侧则没有「插新的」与「清陈旧的」之间的窗口
+ let mut tx = pool.begin().await?;
+ let det = detect(&mut tx, kb_id).await?;
+ let mut report = Report {
+ edges: det.edges,
+ predicates_with_axioms: det.predicates_with_axioms,
+ found: det.violations.len(),
+ contradictions: det.details.len(),
+ contradictions_capped: det.contradictions_capped,
+ rules_disagree: det.clashes.between_derivations.len(),
+ cycles_capped: det.cycles_capped.len(),
+ ..Default::default()
+ };
+
+ let (fresh, inserted, reopened) = settle_violations(&mut tx, kb_id, &det).await?;
+ report.inserted = inserted;
+ report.reopened = reopened;
+
+ // 这一轮没算出来的 open 行是陈的:事实被撤了,或者公理放宽了。
+ // resolved 的不动——那是人的决定,不是派生状态
+ let cleared = sqlx::query(
+ "DELETE FROM axiom_violations
+ WHERE kb_id = $1 AND status = 'open' AND NOT (id = ANY($2))",
+ )
+ .bind(kb_id)
+ .bind(&fresh)
.execute(&mut *tx)
.await?;
+ report.cleared = cleared.rows_affected() as usize;
+
+ settle_defects(&mut tx, kb_id, &det).await?;
tx.commit().await?;
Ok(report)
}
+/// 一处违规在库里的身份:与两条唯一索引同形状——环按整条 `path`,其余按
+/// `(kind, left_fact, right_fact)`(0054)。
+///
+/// **分档归一化**:非环种类的 `path` 存的是这一轮的证据(前提集/组员),
+/// 检出重算时它可以变而行还是那一处违规——拿它分档会把「旧判据下确实检出」
+/// 的行误认成「早就陈了」,从 `criterion_changed` 掉成硬删。所以对账键
+/// 里非环行的 path 一律归成空
+pub type ViolationKey = (String, Uuid, Uuid, Vec<Uuid>);
+
+fn partition_key(kind: &str, left: Uuid, right: Uuid, path: &[Uuid]) -> ViolationKey {
+ (
+ kind.to_string(),
+ left,
+ right,
+ if kind == "cycle" {
+ path.to_vec()
+ } else {
+ Vec::new()
+ },
+ )
+}
+
+/// 当前本体下**会算出来**的违规键集(0062)。不改违规状态——但 `detect` 沿
+/// `resolve` 会顺手把确定性编译出的规则行补齐(`INSERT ... ON CONFLICT DO
+/// NOTHING`),所以它不是字面上的只读。改判据的那条事务在动笔之前调它,
+/// 拿到的就是旧本体下的基线。
+pub async fn detection_keys(
+ conn: &mut PgConnection,
+ kb_id: Uuid,
+) -> AppResult<HashSet<ViolationKey>> {
+ let det = detect(conn, kb_id).await?;
+ Ok(det
+ .violations
+ .iter()
+ .filter(|v| !suppressed(v, &det.accepted))
+ .map(|v| partition_key(v.kind.as_str(), v.left, v.right, &v.path))
+ .collect())
+}
+
+/// 判据在同一条事务里刚被改过(0062):按新本体重新检出、落库,
+/// 然后给陈旧的 open 行一个诚实的下场——
+///
+/// - 旧基线里有的:它的判据在这次改动里被端掉了,以 `criterion_changed` 收场。
+/// 不是人裁的(`decided_by` 空),是公理/签名变了;下次又被算出来时重开规矩
+/// 与 `axiom_relaxed` 同一支
+/// - 旧基线里没有的:它在改动前就已经陈了(事实没了之类),照旧删掉,与
+/// `run` 同一条清陈规矩
+///
+/// 保住的不变式:`status='open'` 的一行必然已对账于**当前**本体。
+/// 返回这一轮检出的违规数(与 `run` 的 `report.found` 同一口径)
+pub async fn reconcile_ontology(
+ tx: &mut Transaction<'_, Postgres>,
+ kb_id: Uuid,
+ was_detected: &HashSet<ViolationKey>,
+) -> AppResult<usize> {
+ let det = detect(tx, kb_id).await?;
+ let (fresh, _, _) = settle_violations(tx, kb_id, &det).await?;
+ let stale: Vec<(Uuid, String, Uuid, Uuid, Vec<Uuid>)> = sqlx::query_as(
+ "SELECT id, kind, left_fact, right_fact, path FROM axiom_violations
+ WHERE kb_id = $1 AND status = 'open' AND NOT (id = ANY($2))",
+ )
+ .bind(kb_id)
+ .bind(&fresh)
+ .fetch_all(&mut **tx)
+ .await?;
+ let mut disqualified: Vec<Uuid> = Vec::new();
+ let mut evaporated: Vec<Uuid> = Vec::new();
+ for (id, kind, left, right, path) in stale {
+ if was_detected.contains(&partition_key(&kind, left, right, &path)) {
+ disqualified.push(id);
+ } else {
+ evaporated.push(id);
+ }
+ }
+ if !disqualified.is_empty() {
+ sqlx::query(
+ "UPDATE axiom_violations
+ SET status = 'resolved', resolution = 'criterion_changed',
+ decided_by = NULL, decided_at = now()
+ WHERE id = ANY($1)",
+ )
+ .bind(&disqualified)
+ .execute(&mut **tx)
+ .await?;
+ }
+ if !evaporated.is_empty() {
+ sqlx::query("DELETE FROM axiom_violations WHERE id = ANY($1)")
+ .bind(&evaporated)
+ .execute(&mut **tx)
+ .await?;
+ }
+ settle_defects(tx, kb_id, &det).await?;
+ Ok(det.violations.len())
+}
+
/// 互斥的三类:一处违规是一组同时成立、彼此冲突的事实(`path` 是整组)。
fn is_grouped(kind: Kind) -> bool {
matches!(
@@ -526,14 +697,17 @@ fn is_grouped(kind: Kind) -> bool {
///
/// 认可说的是「这几条可以同时成立」,所以按事实集合比,不按键比——组里撤掉一条,
/// 剩下的首尾换了、键也换了,那句认可照样管着它们(#624)。
-async fn accepted_groups(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<(String, HashSet<Uuid>)>> {
+async fn accepted_groups(
+ conn: &mut PgConnection,
+ kb_id: Uuid,
+) -> AppResult<Vec<(String, HashSet<Uuid>)>> {
let rows: Vec<(String, Uuid, Uuid, Vec<Uuid>)> = sqlx::query_as(
"SELECT kind, left_fact, right_fact, path FROM axiom_violations
WHERE kb_id = $1 AND status = 'resolved' AND resolution = 'accepted'
AND kind IN ('asymmetry', 'functional', 'inverse_functional')",
)
.bind(kb_id)
- .fetch_all(pool)
+ .fetch_all(&mut *conn)
.await?;
Ok(rows
.into_iter()
@@ -569,7 +743,7 @@ impl Names {
}
async fn names_for(
- pool: &PgPool,
+ conn: &mut PgConnection,
derivation: &Derivation,
clashes: &Contradictions,
) -> AppResult<Names> {
@@ -600,12 +774,12 @@ async fn names_for(
let entities: Vec<(Uuid, String)> =
sqlx::query_as("SELECT id, canonical_name FROM entities WHERE id = ANY($1)")
.bind(&ents)
- .fetch_all(pool)
+ .fetch_all(&mut *conn)
.await?;
let predicates: Vec<(Uuid, String)> =
sqlx::query_as("SELECT id, label FROM relation_types WHERE id = ANY($1)")
.bind(&preds)
- .fetch_all(pool)
+ .fetch_all(&mut *conn)
.await?;
Ok(Names {
entities: entities.into_iter().collect(),
@@ -738,7 +912,7 @@ fn hint_for(r: &ViolationRow) -> Option<&'static str> {
/// 人裁决一处违规。
///
-/// **三个出路,不是两个。** 时态冲突问「哪条对」,而这里可能是定义错了——
+/// **四个出路,不是两个。** 时态冲突问「哪条对」,而这里可能是定义错了——
/// 用户导的本体把某个属性声明成反对称,而他自己的语料里那关系其实双向。
/// `axiom_relaxed` 记的就是这种:该改的是本体,不是二十条事实。
///
@@ -839,7 +1013,7 @@ pub struct OntologyReport {
/// 与 [`run`] 同一套重跑规矩:`open` 是派生状态、可以被重算掉,`resolved`
/// 是人的决定、一行不动。
pub async fn check_ontology(pool: &PgPool, kb_id: Uuid) -> AppResult<OntologyReport> {
- let ax = axioms(pool, kb_id).await?;
+ let ax = axioms(&mut *pool.acquire().await?, kb_id).await?;
let parents: Vec<(Uuid, Uuid)> = sqlx::query_as(
"SELECT child_id, parent_id FROM entity_type_parents p
JOIN entity_types t ON t.id = p.child_id
@@ -1106,7 +1280,7 @@ fn read_span(
(f, t, from_anchored, to_anchored)
}
-async fn timed_edges(pool: &PgPool, kb_id: Uuid) -> AppResult<TimedEdges> {
+async fn timed_edges(conn: &mut PgConnection, kb_id: Uuid) -> AppResult<TimedEdges> {
// 输入**只有断言**。派生住在另一张表,所以这里连过滤都不必写——那正是
// 分表买到的东西:忘了排除的后果是推不出东西,不是把自己的输出喂回自己
let rows: Vec<EdgeRow> = sqlx::query_as(
@@ -1120,14 +1294,14 @@ async fn timed_edges(pool: &PgPool, kb_id: Uuid) -> AppResult<TimedEdges> {
AND object_id IS NOT NULL",
)
.bind(kb_id)
- .fetch_all(pool)
+ .fetch_all(&mut *conn)
.await?;
// 谓词的时间语义(0031):事件按它的桶读,恒常两端开放。一次取全,按谓词查
let temporal_of: HashMap<Uuid, crate::graph::Temporal> = sqlx::query_as::<_, (Uuid, String)>(
"SELECT id, temporal FROM relation_types WHERE kb_id = $1",
)
.bind(kb_id)
- .fetch_all(pool)
+ .fetch_all(&mut *conn)
.await?
.into_iter()
.map(|(id, t)| (id, crate::graph::Temporal::parse(&t)))
@@ -1168,7 +1342,7 @@ async fn timed_edges(pool: &PgPool, kb_id: Uuid) -> AppResult<TimedEdges> {
/// 人认可过并存的(派生三元组, 断言)对:这些派生下一轮照常落地(0017 §2)。
async fn accepted_clashes(
- pool: &PgPool,
+ conn: &mut PgConnection,
kb_id: Uuid,
) -> AppResult<HashSet<(Uuid, Uuid, Uuid, Uuid)>> {
let rows: Vec<(Uuid, serde_json::Value)> = sqlx::query_as(
@@ -1176,7 +1350,7 @@ async fn accepted_clashes(
WHERE kb_id = $1 AND kind = 'derived_contradiction' AND resolution = 'accepted'",
)
.bind(kb_id)
- .fetch_all(pool)
+ .fetch_all(&mut *conn)
.await?;
let id = |v: &serde_json::Value, k: &str| {
v.get(k)
@@ -1277,7 +1451,7 @@ fn coarsest(a: Option<&str>, b: Option<&str>) -> Option<String> {
/// 需要它还在;而它不再出现在返回值里,据它推出来的事实由下面的对账作废。
/// 规则一个库也就几条,留着不占地方。
async fn compile_rules(
- pool: &PgPool,
+ conn: &mut PgConnection,
kb_id: Uuid,
ax: &HashMap<Uuid, Axioms>,
) -> AppResult<HashMap<(Uuid, RuleKind), Uuid>> {
@@ -1310,7 +1484,7 @@ async fn compile_rules(
.bind(kb_id)
.bind(pred)
.bind(kind)
- .execute(pool)
+ .execute(&mut *conn)
.await?;
let (id,): (Uuid,) = sqlx::query_as(
"SELECT id FROM rules WHERE kb_id = $1 AND predicate_id = $2 AND kind = $3",
@@ -1318,7 +1492,7 @@ async fn compile_rules(
.bind(kb_id)
.bind(pred)
.bind(kind)
- .fetch_one(pool)
+ .fetch_one(&mut *conn)
.await?;
out.insert((pred, kind), id);
}
@@ -1395,7 +1569,7 @@ type RuleDefRow = (
/// 取业务规则。条件形状不合法的规则**整条跳过而不是报错退出**——一条写坏的
/// 规则不该让整轮物化停摆,而它不产出这件事在报告的条数里看得见。
-async fn attribute_rules(pool: &PgPool, kb_id: Uuid) -> AppResult<LoadedRules> {
+async fn attribute_rules(conn: &mut PgConnection, kb_id: Uuid) -> AppResult<LoadedRules> {
use utopia_reason::rules::{BusinessRule, Conclusion, Condition, Op};
// **按 id 排序**:规则之间撞上同一个结论时留下的是先到的那条证明,而
@@ -1413,7 +1587,7 @@ async fn attribute_rules(pool: &PgPool, kb_id: Uuid) -> AppResult<LoadedRules> {
ORDER BY r.id",
)
.bind(kb_id)
- .fetch_all(pool)
+ .fetch_all(&mut *conn)
.await?;
if rows.is_empty() {
return Ok(LoadedRules {
@@ -1428,7 +1602,7 @@ async fn attribute_rules(pool: &PgPool, kb_id: Uuid) -> AppResult<LoadedRules> {
let type_rows: Vec<(Uuid, Option<String>, Option<String>)> =
sqlx::query_as("SELECT id, iri, key FROM entity_types WHERE kb_id = $1")
.bind(kb_id)
- .fetch_all(pool)
+ .fetch_all(&mut *conn)
.await?;
let mut class_ids: HashMap<String, Uuid> = HashMap::new();
let mut class_name: HashMap<Uuid, String> = HashMap::new();
@@ -1443,7 +1617,7 @@ async fn attribute_rules(pool: &PgPool, kb_id: Uuid) -> AppResult<LoadedRules> {
let is_a: Option<(Uuid,)> =
sqlx::query_as("SELECT id FROM relation_types WHERE kb_id = $1 AND key = 'is_a'")
.bind(kb_id)
- .fetch_optional(pool)
+ .fetch_optional(&mut *conn)
.await?;
let ids: Vec<Uuid> = rows.iter().map(|r| r.0).collect();
@@ -1455,7 +1629,7 @@ async fn attribute_rules(pool: &PgPool, kb_id: Uuid) -> AppResult<LoadedRules> {
ORDER BY rule_id, group_seq, seq",
)
.bind(&ids)
- .fetch_all(pool)
+ .fetch_all(&mut *conn)
.await?;
let mut by_rule: HashMap<Uuid, Vec<Condition>> = HashMap::new();
let mut broken: HashSet<Uuid> = HashSet::new();
@@ -1541,7 +1715,7 @@ async fn attribute_rules(pool: &PgPool, kb_id: Uuid) -> AppResult<LoadedRules> {
}
_ => continue,
};
- let subject_types = descendants_of(pool, kb_id, subject_type).await?;
+ let subject_types = descendants_of(&mut *conn, kb_id, subject_type).await?;
let subject_classes = subject_types
.iter()
.filter_map(|t| class_name.get(t).cloned())
@@ -1637,7 +1811,7 @@ fn parse_operand(
}
/// 一个类连同它的全部子类。规则写在 `Well` 上,`HorizontalWell` 的实体也该被看。
-async fn descendants_of(pool: &PgPool, kb_id: Uuid, root: Uuid) -> AppResult<Vec<Uuid>> {
+async fn descendants_of(conn: &mut PgConnection, kb_id: Uuid, root: Uuid) -> AppResult<Vec<Uuid>> {
let rows: Vec<(Uuid,)> = sqlx::query_as(
"WITH RECURSIVE sub AS (
SELECT id FROM entity_types WHERE id = $2 AND kb_id = $1
@@ -1648,7 +1822,7 @@ async fn descendants_of(pool: &PgPool, kb_id: Uuid, root: Uuid) -> AppResult<Vec
)
.bind(kb_id)
.bind(root)
- .fetch_all(pool)
+ .fetch_all(&mut *conn)
.await?;
Ok(rows.into_iter().map(|(id,)| id).collect())
}
@@ -1675,7 +1849,7 @@ type AttrFactRow = (
/// 与 `timed_edges` 是对偶的一份——那边取 `object_id IS NOT NULL` 的边,
/// 这边取 `object_value IS NOT NULL` 的字面值。两边都只看断言。
async fn attribute_facts(
- pool: &PgPool,
+ conn: &mut PgConnection,
kb_id: Uuid,
) -> AppResult<(
Vec<utopia_reason::rules::AttrFact>,
@@ -1696,7 +1870,7 @@ async fn attribute_facts(
AND e.merged_into IS NULL",
)
.bind(kb_id)
- .fetch_all(pool)
+ .fetch_all(&mut *conn)
.await?;
let mut facts = Vec::with_capacity(rows.len());
@@ -1932,12 +2106,12 @@ struct Resolved {
rule_rounds_capped: bool,
}
-async fn resolve(pool: &PgPool, kb_id: Uuid) -> AppResult<Resolved> {
- let axioms = axioms(pool, kb_id).await?;
- let rules = compile_rules(pool, kb_id, &axioms).await?;
- let (edges, mut spans, mut meta) = timed_edges(pool, kb_id).await?;
- let accepted = accepted_clashes(pool, kb_id).await?;
- let loaded = attribute_rules(pool, kb_id).await?;
+async fn resolve(conn: &mut PgConnection, kb_id: Uuid) -> AppResult<Resolved> {
+ let axioms = axioms(&mut *conn, kb_id).await?;
+ let rules = compile_rules(&mut *conn, kb_id, &axioms).await?;
+ let (edges, mut spans, mut meta) = timed_edges(&mut *conn, kb_id).await?;
+ let accepted = accepted_clashes(&mut *conn, kb_id).await?;
+ let loaded = attribute_rules(&mut *conn, kb_id).await?;
let mut asserted_ids: HashSet<Uuid> = edges.iter().map(|e| e.edge.fact).collect();
let mut wanted: HashMap<DerivedKey, Wanted> = HashMap::new();
@@ -1951,7 +2125,7 @@ async fn resolve(pool: &PgPool, kb_id: Uuid) -> AppResult<Resolved> {
// 落库那边的陈旧对账扫的是整张 `derived_facts`,两趟各做各的 diff 会把对方
// 落的行每一轮都判成陈旧
if !loaded.rules.is_empty() {
- let (asserted, attr_spans, attr_meta, type_of) = attribute_facts(pool, kb_id).await?;
+ let (asserted, attr_spans, attr_meta, type_of) = attribute_facts(&mut *conn, kb_id).await?;
asserted_ids.extend(asserted.iter().map(|f| f.id));
// 前提的精度与置信度:落地那一段与不动点这一段共用,所以两份 meta 先合起来;
// 区间也要——认出派生的哪一端是被前提的锚点顶上来的,靠的就是它
@@ -2269,7 +2443,7 @@ pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport>
rounds,
rule_rounds_capped,
..
- } = resolve(pool, kb_id).await?;
+ } = resolve(&mut *pool.acquire().await?, kb_id).await?;
let Checked {
candidates,
axiom_count,
diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rs
index 49f25722..d17854a0 100644
--- a/crates/utopia-store/src/resolution.rs
+++ b/crates/utopia-store/src/resolution.rs
@@ -2074,7 +2074,9 @@ pub async fn merge_entities(
// 只报:对搬动过的事实查一遍 domain / range,违反的进 `axiom_violations`
//(kind = signature),与其它公理违规同一个队列、同样三个出路。
// 放在事务之后:目标实体的类型在事务里刚调和过,提交了才看得见
- match crate::reasoning::signature_breaks(pool, kb_id, Some(&moved_all)).await {
+ match crate::reasoning::signature_breaks(&mut *pool.acquire().await?, kb_id, Some(&moved_all))
+ .await
+ {
Ok(broken) if !broken.is_empty() => {
if let Err(e) = crate::reasoning::record_signature_breaks(pool, kb_id, &broken).await {
tracing::warn!(%kb_id, error = %e, "合并后的签名违规没能入库");
diff --git a/crates/utopia-store/tests/store/a_signature_holds_on_every_path.rs b/crates/utopia-store/tests/store/a_signature_holds_on_every_path.rs
index b9eecb64..624d8645 100644
--- a/crates/utopia-store/tests/store/a_signature_holds_on_every_path.rs
+++ b/crates/utopia-store/tests/store/a_signature_holds_on_every_path.rs
@@ -285,8 +285,11 @@ async fn adoption_and_merge_respect_the_signature() -> anyhow::Result<()> {
.bind(f.alice)
.execute(&pool)
.await?;
+ let mut conn = pool.acquire().await?;
assert!(
- utopia_store::reasoning::signature_breaks(&pool, f.kb, None).await?.is_empty(),
+ utopia_store::reasoning::signature_breaks(&mut conn, f.kb, None)
+ .await?
+ .is_empty(),
"an untyped subject is unknown, not wrong"
);
let _ = (f.company, f.person);
diff --git a/crates/utopia-store/tests/store/an_axiom_that_moved_closes_its_findings.rs b/crates/utopia-store/tests/store/an_axiom_that_moved_closes_its_findings.rs
new file mode 100644
index 00000000..48f9a065
--- /dev/null
+++ b/crates/utopia-store/tests/store/an_axiom_that_moved_closes_its_findings.rs
@@ -0,0 +1,786 @@
+//! 判据一动,靠着它的 open 违规就得当场对账(#564 / 0062)。
+//!
+//! `axiom_violations.status = 'open'` 的承诺是「已对账于**当前**本体」。
+//! 从前 `update_relation_type` 只管写:放宽一条公理,上一轮检出的 open 行
+//! 原样留着——下一次导出会把一个只在旧判据下成立的发现说成是现在的。
+//! 这里钉的是同一条事务里做完的三件事:
+//!
+//! 1. **旧判据下的检出先记下来**——动笔之前库里还是旧本体
+//! 2. **写完后按新本体重检出**——新的违规同一份提交里进来
+//! 3. **只在旧判据下成立的 open 行收 `criterion_changed`**——不是人裁的
+//! (decided_by 空),是公理/签名换了;早就不成立的照旧删掉,与
+//! `reasoning::run` 同一条清陈规矩
+//!
+//! 没动判据的编辑(label、描述)不跑检测——那是对账不必付的价。
+
+use sqlx::PgPool;
+use utopia_core::models::RelationAxioms;
+use utopia_store::{ontology, reasoning};
+use uuid::Uuid;
+
+struct Fixture {
+ org: Uuid,
+ kb: Uuid,
+ thing: Uuid,
+ person: Uuid,
+ /// state + asymmetric
+ reports_to: Uuid,
+ /// state,带 domain=[person]
+ works_for: Uuid,
+}
+
+const NONE: RelationAxioms = RelationAxioms {
+ functional: false,
+ inverse_functional: false,
+ transitive: false,
+ symmetric: false,
+ asymmetric: false,
+ irreflexive: false,
+ inverse_of: None,
+ sub_property_of: None,
+};
+
+fn ax() -> RelationAxioms {
+ RelationAxioms {
+ asymmetric: true,
+ ..NONE
+ }
+}
+
+async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {
+ let (org, ws, kb, thing, person, reports_to, works_for) = (
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ );
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'moved-axiom')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'moved-axiom')")
+ .bind(ws)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'moved-axiom')",
+ )
+ .bind(kb)
+ .bind(ws)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO entity_types (id, kb_id, key, label) VALUES
+ ($1, $2, 'thing', 'Thing'), ($3, $2, 'person', 'Person')",
+ )
+ .bind(thing)
+ .bind(kb)
+ .bind(person)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO relation_types
+ (id, kb_id, key, label, temporal, is_asymmetric)
+ VALUES ($1, $2, 'reports_to', 'reportsTo', 'state', TRUE)",
+ )
+ .bind(reports_to)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO relation_types (id, kb_id, key, label, temporal)
+ VALUES ($1, $2, 'works_for', 'worksFor', 'state')",
+ )
+ .bind(works_for)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO relation_type_domains (relation_type_id, entity_type_id)
+ VALUES ($1, $2)",
+ )
+ .bind(works_for)
+ .bind(person)
+ .execute(pool)
+ .await?;
+ Ok(Fixture {
+ org,
+ kb,
+ thing,
+ person,
+ reports_to,
+ works_for,
+ })
+}
+
+async fn entity(pool: &PgPool, f: &Fixture, ty: Uuid, name: &str) -> anyhow::Result<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",
+ )
+ .bind(id)
+ .bind(f.kb)
+ .bind(ty)
+ .bind(name)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+async fn fact(pool: &PgPool, f: &Fixture, (s, p, o): (Uuid, Uuid, Uuid)) -> anyhow::Result<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id)
+ VALUES ($1, $2, $3, $4, $5)",
+ )
+ .bind(id)
+ .bind(f.kb)
+ .bind(s)
+ .bind(p)
+ .bind(o)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+/// 某一行的现状:(status, resolution, decided_at)
+async fn row_state(
+ pool: &PgPool,
+ id: Uuid,
+) -> anyhow::Result<Option<(String, Option<String>, bool)>> {
+ Ok(sqlx::query_as::<_, (String, Option<String>, bool)>(
+ "SELECT status, resolution, decided_at IS NOT NULL FROM axiom_violations WHERE id = $1",
+ )
+ .bind(id)
+ .fetch_optional(pool)
+ .await?)
+}
+
+async fn open_count(pool: &PgPool, f: &Fixture) -> anyhow::Result<i64> {
+ Ok(sqlx::query_scalar(
+ "SELECT count(*) FROM axiom_violations WHERE kb_id = $1 AND status = 'open'",
+ )
+ .bind(f.kb)
+ .fetch_one(pool)
+ .await?)
+}
+
+async fn cleanup(pool: &PgPool, f: &Fixture) -> anyhow::Result<()> {
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 放宽一条公理:open 行收 criterion_changed,不是删也不是继续开着;
+/// 把公理改回去,同一行重开——`criterion_changed` 是破约家族的一员
+#[tokio::test]
+async fn relaxing_an_axiom_closes_its_finding_and_reinstating_reopens_it() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let result = async {
+ let (a, b) = (
+ entity(&pool, &f, f.thing, "A").await?,
+ entity(&pool, &f, f.thing, "B").await?,
+ );
+ fact(&pool, &f, (a, f.reports_to, b)).await?;
+ fact(&pool, &f, (b, f.reports_to, a)).await?;
+ let r = reasoning::run(&pool, f.kb).await?;
+ anyhow::ensure!(r.found == 1, "expected one asymmetry finding, got {r:?}");
+ let (id,): (Uuid,) =
+ sqlx::query_as("SELECT id FROM axiom_violations WHERE kb_id = $1 AND status = 'open'")
+ .bind(f.kb)
+ .fetch_one(&pool)
+ .await?;
+
+ // 改判据:asymmetric 关掉。同一事务里这行该被收编成 criterion_changed
+ ontology::update_relation_type(
+ &pool,
+ f.kb,
+ f.reports_to,
+ "reportsTo",
+ "state",
+ NONE,
+ "",
+ None,
+ None,
+ None,
+ None,
+ )
+ .await?;
+ anyhow::ensure!(
+ open_count(&pool, &f).await? == 0,
+ "open finding outlived its axiom"
+ );
+ let (status, resolution, decided) = row_state(&pool, id).await?.unwrap();
+ anyhow::ensure!(
+ status == "resolved" && resolution.as_deref() == Some("criterion_changed"),
+ "finding was not closed as criterion_changed: {status}/{resolution:?}"
+ );
+ anyhow::ensure!(decided, "decided_at should mark when it stopped being open");
+
+ // 改回来:同一处矛盾又成立,同一行重开——不是另插一行
+ ontology::update_relation_type(
+ &pool,
+ f.kb,
+ f.reports_to,
+ "reportsTo",
+ "state",
+ ax(),
+ "",
+ None,
+ None,
+ None,
+ None,
+ )
+ .await?;
+ let (status, resolution, _) = row_state(&pool, id).await?.unwrap();
+ anyhow::ensure!(
+ status == "open" && resolution.is_none(),
+ "finding should reopen under the restored axiom, got {status}/{resolution:?}"
+ );
+ anyhow::ensure!(open_count(&pool, &f).await? == 1);
+ Ok(())
+ }
+ .await;
+ let cleanup = cleanup(&pool, &f).await;
+ result.and(cleanup)
+}
+
+/// domain 换了签名就换:原来开着的 signature 违规按新判据收场
+#[tokio::test]
+async fn a_domain_change_closes_the_signature_finding() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let result = async {
+ // works_for domain=person,而一个 thing 断言了它——signature 违规
+ let (acme, alice) = (
+ entity(&pool, &f, f.thing, "Acme").await?,
+ entity(&pool, &f, f.thing, "Alice").await?,
+ );
+ fact(&pool, &f, (alice, f.works_for, acme)).await?;
+ let r = reasoning::run(&pool, f.kb).await?;
+ anyhow::ensure!(
+ r.found == 1
+ && reasoning::open_violations(&pool, f.kb, 10, 0).await?[0].kind == "signature",
+ "expected one signature finding"
+ );
+
+ // domain 放宽到 thing:判据没了,这行收 criterion_changed
+ ontology::update_relation_type(
+ &pool,
+ f.kb,
+ f.works_for,
+ "worksFor",
+ "state",
+ NONE,
+ "",
+ None,
+ None,
+ Some(&[f.thing]),
+ None,
+ )
+ .await?;
+ anyhow::ensure!(
+ open_count(&pool, &f).await? == 0,
+ "signature finding outlived its domain"
+ );
+ let (status, resolution, _) = sqlx::query_as::<_, (String, Option<String>, bool)>(
+ "SELECT status, resolution, decided_at IS NOT NULL FROM axiom_violations
+ WHERE kb_id = $1 AND kind = 'signature'",
+ )
+ .bind(f.kb)
+ .fetch_one(&pool)
+ .await?;
+ anyhow::ensure!(
+ status == "resolved" && resolution.as_deref() == Some("criterion_changed"),
+ "signature finding was not closed as criterion_changed: {status}/{resolution:?}"
+ );
+ Ok(())
+ }
+ .await;
+ let cleanup = cleanup(&pool, &f).await;
+ result.and(cleanup)
+}
+
+/// 不动判据的编辑不跑对账:一条只在旧检测里才「成立过」的 open 行,
+/// 换 label 不碰它,真改判据时按早就陈掉的处置——删掉,不是 criterion_changed
+#[tokio::test]
+async fn a_label_edit_leaves_the_ledger_alone() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let result = async {
+ let (a, b) = (
+ entity(&pool, &f, f.thing, "A").await?,
+ entity(&pool, &f, f.thing, "B").await?,
+ );
+ let f1 = fact(&pool, &f, (a, f.works_for, b)).await?;
+ // 一行检出函数永远不会产出的 open 行(自环挂着 functional 键):
+ // 它早就陈了,下一次对账该删掉而不是收编
+ let stray = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO axiom_violations (id, kb_id, kind, left_fact, right_fact)
+ VALUES ($1, $2, 'functional', $3, $3)",
+ )
+ .bind(stray)
+ .bind(f.kb)
+ .bind(f1)
+ .execute(&pool)
+ .await?;
+
+ // 只改 label:判据没动,不跑检测——陈行原样留着(检出是有代价的,
+ // 不该为一次改名付)
+ ontology::update_relation_type(
+ &pool,
+ f.kb,
+ f.works_for,
+ "employs",
+ "state",
+ NONE,
+ "",
+ None,
+ None,
+ None,
+ None,
+ )
+ .await?;
+ anyhow::ensure!(
+ row_state(&pool, stray).await?.map(|r| r.0) == Some("open".into()),
+ "a label-only edit must not touch violation state"
+ );
+
+ // 真改判据(domain 从 person 换成 thing):这行不在旧基线里
+ //(检出从没产出过它)——删掉,与 run() 的清陈同一条规矩
+ ontology::update_relation_type(
+ &pool,
+ f.kb,
+ f.works_for,
+ "employs",
+ "state",
+ NONE,
+ "",
+ None,
+ None,
+ Some(&[f.thing]),
+ None,
+ )
+ .await?;
+ anyhow::ensure!(
+ row_state(&pool, stray).await?.is_none(),
+ "a stale row that never held under the old ontology should be deleted, not adjudicated"
+ );
+ Ok(())
+ }
+ .await;
+ let cleanup = cleanup(&pool, &f).await;
+ result.and(cleanup)
+}
+
+/// 父链也是判据:给类挂上父类后签名对上了,open 违规当场收编
+#[tokio::test]
+async fn a_new_parent_closes_the_signature_finding() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let result = async {
+ // works_for domain=person;thing ⊏ person——thing 断言它算违规
+ let (acme, alice) = (
+ entity(&pool, &f, f.thing, "Acme").await?,
+ entity(&pool, &f, f.thing, "Alice").await?,
+ );
+ fact(&pool, &f, (alice, f.works_for, acme)).await?;
+ reasoning::run(&pool, f.kb).await?;
+ anyhow::ensure!(open_count(&pool, &f).await? == 1);
+
+ // 给 thing 挂上 person 当父类:签名沿祖先链判,这就对上了
+ ontology::update_entity_type(
+ &pool,
+ f.kb,
+ f.thing,
+ "Thing",
+ None,
+ "circle",
+ &[f.person],
+ "",
+ )
+ .await?;
+ anyhow::ensure!(
+ open_count(&pool, &f).await? == 0,
+ "signature finding should close once the parent makes the signature hold"
+ );
+ let (status, resolution, _) = sqlx::query_as::<_, (String, Option<String>, bool)>(
+ "SELECT status, resolution, decided_at IS NOT NULL FROM axiom_violations
+ WHERE kb_id = $1 AND kind = 'signature'",
+ )
+ .bind(f.kb)
+ .fetch_one(&pool)
+ .await?;
+ anyhow::ensure!(
+ status == "resolved" && resolution.as_deref() == Some("criterion_changed"),
+ "finding was not closed as criterion_changed: {status}/{resolution:?}"
+ );
+ Ok(())
+ }
+ .await;
+ let cleanup = cleanup(&pool, &f).await;
+ result.and(cleanup)
+}
+
+/// 删掉被别人的 `sub_property_of` 指着的关系,也是一次判据变动:
+/// 0070 把那条外键建成 DEFERRABLE SET NULL——提交才落地,所以得在事务里
+/// 先显式断链再对账。断链之后靠它派生的发现不该还在
+#[tokio::test]
+async fn deleting_a_linked_relation_reconciles_what_depended_on_it() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let result = async {
+ // manages 是 functional 的超属性:supervises ⊑ manages——零断言,
+ // 只活在派生链上,所以它能被删
+ let (manages, supervises) = (Uuid::now_v7(), Uuid::now_v7());
+ sqlx::query(
+ "INSERT INTO relation_types (id, kb_id, key, label, temporal, functional)
+ VALUES ($1, $2, 'manages', 'manages', 'state', TRUE)",
+ )
+ .bind(manages)
+ .bind(f.kb)
+ .execute(&pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO relation_types (id, kb_id, key, label, temporal, sub_property_of)
+ VALUES ($1, $2, 'supervises', 'supervises', 'state', $3)",
+ )
+ .bind(supervises)
+ .bind(f.kb)
+ .bind(manages)
+ .execute(&pool)
+ .await?;
+ let (alice, carol, dave) = (
+ entity(&pool, &f, f.thing, "Alice").await?,
+ entity(&pool, &f, f.thing, "Carol").await?,
+ entity(&pool, &f, f.thing, "Dave").await?,
+ );
+ fact(&pool, &f, (alice, supervises, carol)).await?;
+ fact(&pool, &f, (alice, supervises, dave)).await?;
+ reasoning::run(&pool, f.kb).await?;
+ // supervises ⊑ manages 派生出 manages(alice→carol) 与 manages(alice→dave):
+ // 两条派生撞上 functional——规则对层的发现进 ontology_defects
+ let defects: i64 = sqlx::query_scalar(
+ "SELECT count(*) FROM ontology_defects
+ WHERE kb_id = $1 AND kind = 'rules_disagree'",
+ )
+ .bind(f.kb)
+ .fetch_one(&pool)
+ .await?;
+ anyhow::ensure!(
+ defects == 1,
+ "expected one rules_disagree defect, got {defects}"
+ );
+
+ // manages 零断言可以删:先断 supervises 的链再删再对账——发现随之消失,
+ // 不留「一条只对已删判据成立的发现」走出提交点
+ ontology::delete_relation_type(&pool, f.kb, manages).await?;
+ let left: i64 =
+ sqlx::query_scalar("SELECT count(*) FROM ontology_defects WHERE kb_id = $1")
+ .bind(f.kb)
+ .fetch_one(&pool)
+ .await?;
+ anyhow::ensure!(left == 0, "defect survived the deletion of its criterion");
+ let dangling: i64 =
+ sqlx::query_scalar("SELECT count(*) FROM relation_types WHERE sub_property_of = $1")
+ .bind(manages)
+ .fetch_one(&pool)
+ .await?;
+ anyhow::ensure!(
+ dangling == 0,
+ "deferred SET NULL would have hidden the link"
+ );
+ Ok(())
+ }
+ .await;
+ let cleanup = cleanup(&pool, &f).await;
+ result.and(cleanup)
+}
+
+/// 证据漂移不是身份漂移:行里留的 `path` 是上一轮拍下的组员集,检出重算
+/// 时它可以变——分档比的是 `(kind, left, right)`,不是那张旧照片。一条
+/// 旧判据下确实检得出的违规,不能因为存的证据换了组就当成「早就陈了」删掉
+#[tokio::test]
+async fn drifted_evidence_still_closes_as_criterion_changed() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let result = async {
+ let (a, b, c) = (
+ entity(&pool, &f, f.thing, "A").await?,
+ entity(&pool, &f, f.thing, "B").await?,
+ entity(&pool, &f, f.thing, "C").await?,
+ );
+ let f1 = fact(&pool, &f, (a, f.reports_to, b)).await?;
+ fact(&pool, &f, (b, f.reports_to, a)).await?;
+ let f3 = fact(&pool, &f, (a, f.reports_to, c)).await?;
+ reasoning::run(&pool, f.kb).await?;
+ let (id,): (Uuid,) =
+ sqlx::query_as("SELECT id FROM axiom_violations WHERE kb_id = $1 AND status = 'open'")
+ .bind(f.kb)
+ .fetch_one(&pool)
+ .await?;
+
+ // 模拟上一轮检出留下的旧证据:path 组员漂移过,端点没变——
+ // 这还是同一处违规(0054:非环种类按 (kind,left,right) 认身份)
+ sqlx::query("UPDATE axiom_violations SET path = $2 WHERE id = $1")
+ .bind(id)
+ .bind(&[f1, f3][..])
+ .execute(&pool)
+ .await?;
+
+ ontology::update_relation_type(
+ &pool,
+ f.kb,
+ f.reports_to,
+ "reportsTo",
+ "state",
+ NONE,
+ "",
+ None,
+ None,
+ None,
+ None,
+ )
+ .await?;
+ let (status, resolution, _) = row_state(&pool, id).await?.unwrap();
+ anyhow::ensure!(
+ status == "resolved" && resolution.as_deref() == Some("criterion_changed"),
+ "evidence drift must not turn a baseline finding into a deletion: \
+ {status}/{resolution:?} (drifted path had f3={f3})"
+ );
+ Ok(())
+ }
+ .await;
+ let cleanup = cleanup(&pool, &f).await;
+ result.and(cleanup)
+}
+
+/// 断链同样改判据:`update_relation_type` 把 `sub_property_of` 摘掉,
+/// 靠它派生的发现当场清掉——与 `delete_relation_type` 同一条规矩
+#[tokio::test]
+async fn unlinking_a_sub_property_reconciles_what_depended_on_it() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let result = async {
+ let (manages, supervises) = (Uuid::now_v7(), Uuid::now_v7());
+ sqlx::query(
+ "INSERT INTO relation_types (id, kb_id, key, label, temporal, functional)
+ VALUES ($1, $2, 'manages', 'manages', 'state', TRUE)",
+ )
+ .bind(manages)
+ .bind(f.kb)
+ .execute(&pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO relation_types (id, kb_id, key, label, temporal, sub_property_of)
+ VALUES ($1, $2, 'supervises', 'supervises', 'state', $3)",
+ )
+ .bind(supervises)
+ .bind(f.kb)
+ .bind(manages)
+ .execute(&pool)
+ .await?;
+ let (alice, carol, dave) = (
+ entity(&pool, &f, f.thing, "Alice").await?,
+ entity(&pool, &f, f.thing, "Carol").await?,
+ entity(&pool, &f, f.thing, "Dave").await?,
+ );
+ fact(&pool, &f, (alice, supervises, carol)).await?;
+ fact(&pool, &f, (alice, supervises, dave)).await?;
+ reasoning::run(&pool, f.kb).await?;
+ let defects: i64 = sqlx::query_scalar(
+ "SELECT count(*) FROM ontology_defects
+ WHERE kb_id = $1 AND kind = 'rules_disagree'",
+ )
+ .bind(f.kb)
+ .fetch_one(&pool)
+ .await?;
+ anyhow::ensure!(defects == 1, "expected one rules_disagree defect");
+
+ // 摘掉 supervises ⊑ manages:判据变了,派生链断——发现随提交一起清
+ ontology::update_relation_type(
+ &pool,
+ f.kb,
+ supervises,
+ "supervises",
+ "state",
+ NONE,
+ "",
+ None,
+ None,
+ None,
+ None,
+ )
+ .await?;
+ let left: i64 =
+ sqlx::query_scalar("SELECT count(*) FROM ontology_defects WHERE kb_id = $1")
+ .bind(f.kb)
+ .fetch_one(&pool)
+ .await?;
+ anyhow::ensure!(
+ left == 0,
+ "defect survived the unlinking of its derivation chain"
+ );
+ Ok(())
+ }
+ .await;
+ let cleanup = cleanup(&pool, &f).await;
+ result.and(cleanup)
+}
+
+/// 删掉一个牵着判据的类,同一事务里把靠着它的发现收掉
+#[tokio::test]
+async fn deleting_a_domain_class_closes_the_signature_finding() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let result = async {
+ let (acme, alice) = (
+ entity(&pool, &f, f.thing, "Acme").await?,
+ entity(&pool, &f, f.thing, "Alice").await?,
+ );
+ fact(&pool, &f, (alice, f.works_for, acme)).await?;
+ reasoning::run(&pool, f.kb).await?;
+ anyhow::ensure!(open_count(&pool, &f).await? == 1);
+
+ // person 是 works_for 的 domain:删掉它,判据跟着没了
+ ontology::delete_entity_type(&pool, f.kb, f.person).await?;
+ anyhow::ensure!(
+ open_count(&pool, &f).await? == 0,
+ "finding should close when its domain class is deleted"
+ );
+ let (status, resolution, _) = sqlx::query_as::<_, (String, Option<String>, bool)>(
+ "SELECT status, resolution, decided_at IS NOT NULL FROM axiom_violations
+ WHERE kb_id = $1 AND kind = 'signature'",
+ )
+ .bind(f.kb)
+ .fetch_one(&pool)
+ .await?;
+ anyhow::ensure!(
+ status == "resolved" && resolution.as_deref() == Some("criterion_changed"),
+ "finding was not closed as criterion_changed: {status}/{resolution:?}"
+ );
+ Ok(())
+ }
+ .await;
+ let cleanup = cleanup(&pool, &f).await;
+ result.and(cleanup)
+}
+
+/// 改判一条零事实的关系成属性:它挂着的公理旗标与双向链接是关系的判据
+/// 贡献,属性不该还留着——`axioms()` 不按 kind 过滤,留着等于留一套
+/// 无人问的公理。同一事务里旗标清掉、链接断开、检出键集照 0062 对账
+#[tokio::test]
+async fn a_demoted_relation_surrenders_its_axioms() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let result = async {
+ let (manages, supervises) = (Uuid::now_v7(), Uuid::now_v7());
+ sqlx::query(
+ "INSERT INTO relation_types (id, kb_id, key, label, temporal)
+ VALUES ($1, $2, 'supervises', 'supervises', 'state')",
+ )
+ .bind(supervises)
+ .bind(f.kb)
+ .execute(&pool)
+ .await?;
+ // manages:functional + inverse_of=supervises——零事实,够格被改判;
+ // supervises.sub_property_of 补一条入向引用,改判也要把它断开
+ sqlx::query(
+ "INSERT INTO relation_types
+ (id, kb_id, key, label, temporal, functional, is_transitive, inverse_of)
+ VALUES ($1, $2, 'manages', 'manages', 'state', TRUE, TRUE, $3)",
+ )
+ .bind(manages)
+ .bind(f.kb)
+ .bind(supervises)
+ .execute(&pool)
+ .await?;
+ sqlx::query("UPDATE relation_types SET sub_property_of = $2 WHERE id = $1")
+ .bind(supervises)
+ .bind(manages)
+ .execute(&pool)
+ .await?;
+
+ let converted = ontology::attribute_from_unused_relation(
+ &pool,
+ f.kb,
+ "manages",
+ &[f.thing],
+ "text",
+ None,
+ )
+ .await?
+ .expect("a zero-facts relation should convert");
+ anyhow::ensure!(converted == manages);
+ let row: (String, bool, bool, Option<Uuid>, Option<Uuid>) = sqlx::query_as(
+ "SELECT kind, functional, is_transitive, inverse_of, sub_property_of
+ FROM relation_types WHERE id = $1",
+ )
+ .bind(manages)
+ .fetch_one(&pool)
+ .await?;
+ anyhow::ensure!(row.0 == "attribute", "kind should flip: {}", row.0);
+ anyhow::ensure!(!row.1 && !row.2, "axiom flags survived the demotion");
+ anyhow::ensure!(
+ row.3.is_none() && row.4.is_none(),
+ "links survived the demotion"
+ );
+ // 入向引用同样断开:supervises 不再指向它(axioms() 的归一化不再
+ // 把一个属性当派生目标)
+ let still_linked: bool = sqlx::query_scalar(
+ "SELECT EXISTS(SELECT 1 FROM relation_types WHERE sub_property_of = $1)",
+ )
+ .bind(manages)
+ .fetch_one(&pool)
+ .await?;
+ anyhow::ensure!(!still_linked, "incoming sub_property_of survived");
+ Ok(())
+ }
+ .await;
+ let cleanup = cleanup(&pool, &f).await;
+ result.and(cleanup)
+}
diff --git a/crates/utopia-store/tests/store/main.rs b/crates/utopia-store/tests/store/main.rs
index b3e61a9c..78de844b 100644
--- a/crates/utopia-store/tests/store/main.rs
+++ b/crates/utopia-store/tests/store/main.rs
@@ -91,6 +91,7 @@ mod adopting_an_iri_adopts_the_shape;
mod an_agent_can_record;
mod an_amount_outlives_adoption;
mod an_automatic_merge_is_gated_by_what_it_can_undo;
+mod an_axiom_that_moved_closes_its_findings;
mod an_earlier_mention_keeps_the_stated_end;
mod an_end_date_closes_the_open_span;
mod an_event_holds_at_the_moment_it_names;
diff --git a/docs/decisions/0062-the-export-says-what-is-contested.md b/docs/decisions/0062-the-export-says-what-is-contested.md
new file mode 100644
index 00000000..000514c5
--- /dev/null
+++ b/docs/decisions/0062-the-export-says-what-is-contested.md
@@ -0,0 +1,111 @@
+# 0062 · The export says what is contested
+
+- **Status**: accepted 2026-09-26 (#922) · implements [#564](https://github.com/deeplethe/utopia/issues/564) · precondition: the current-ontology invariant described under [The `open` invariant](#the-open-invariant)
+- **Written**: 2026-09-25 (conventions in the [README](README.md))
+- **Related**: [0020](0020-an-auditor-reads-it-without-us.md) (the export this extends); [0012](0012-the-ontology-is-a-contract-not-a-suggestion.md) (axiom violations); [0017](0017-a-contradiction-points-upstream.md) (`derived_contradiction`); [#550](https://github.com/deeplethe/utopia/issues/550) (the export is the supported machine-readable read contract); #612, #613, #618, #619 (the storage-side findings this record had to respect)
+
+## Problem
+
+The export contains the assertions themselves but not the epistemic state the base has already established about them. A downstream reader gets two evidence-backed statements — "Acme revenue = 100M" and "Acme revenue = 130M" — with their provenance and intervals, and nothing that says Utopia considers them contested. The reader's options are to treat them as ordinary independent facts, or to re-implement the conflict detection Utopia already owns. Both are wrong in the way 0020 names: the export is the read contract, and the read contract has to carry what the ledger knows.
+
+## Decision
+
+The export carries the two findings tables as two distinct resource classes. Both already exist; nothing here invents a new state machine, and the export stays read-only — it selects from `fact_conflicts` and `axiom_violations` inside the same read-only `REPEATABLE READ` snapshot as every other page, and never through `temporal::list_conflicts` or a detection run.
+
+### Two classes, not one
+
+`utopia:FactConflict` and `utopia:AxiomViolation` stay separate because they are different claims:
+
+- A **fact conflict** says *two assertions disagree about the same ledger slot* — the ledger could not decide whether the new one closes the old one (`no_time`, `simultaneous`, `low_confidence`, `described_evidence`). Its adjudication is about the facts.
+- An **axiom violation** says *the data contradicts a rule the ontology currently declares*. Its adjudication is about whether the error is in the data or in the definition.
+
+Their resolution vocabularies are different for the same reason; flattening them into one class would force one column to mean two things.
+
+### `utopia:FactConflict`
+
+A conflict is addressable at `conflict:{uuid}` under the base namespace. It points **from** the conflict **to** the two statements by their existing fact IRIs — a consumer that ignores conflicts reads facts exactly as before:
+
+```
+<conflict> a utopia:FactConflict ;
+ utopia:reason "simultaneous" ; -- no_time | simultaneous | low_confidence | described_evidence
+ utopia:priorStatement <fact/old> ; -- the incumbent assertion
+ utopia:incomingStatement <fact/new> ; -- the arriving assertion
+ utopia:status "open" ; -- open | resolved | withdrawn
+ utopia:resolution "closed" ; -- only when resolved: closed | kept_both | rejected_new
+ prov:generatedAtTime "…" ; -- created_at: when the conflict was recorded
+ utopia:closedAt "…" . -- resolved_at, when set
+```
+
+`status` and `resolution` are contract vocabulary — `contest_integrity` validates stored values against the listed sets before the first byte is emitted, so the contract promises the listed values and nothing else. `withdrawn` (0051) is a status, not an adjudication: its `closedAt` is the moment one side was invalidated — which is when the conflict stopped applying — not a page-open timestamp. Rows keep their real timestamps because `GET /export` has no `as_of` parameter: "was this contested in March" is answered from the payload or not at all.
+
+### `utopia:AxiomViolation`
+
+A violation is addressable at `violation:{uuid}`:
+
+```
+<violation> a utopia:AxiomViolation ;
+ utopia:kind "functional" ; -- the finding kinds below
+ utopia:status "open" ; -- open | resolved
+ utopia:resolution "accepted" ; -- only when resolved
+ utopia:onStatement <fact/a> ; -- the statements the finding is about
+ utopia:onStatement <fact/b> ;
+ utopia:evidencePath ( <fact/a> <fact/mid> <fact/b> ) ; -- ordered, when the row carries a path
+ utopia:onRelation <relation> ; -- open rows only: the relation the criterion is declared on
+ utopia:criterion owl:FunctionalProperty ; -- open rows only: the criterion itself
+ utopia:detectedAt "…" ;
+ utopia:closedAt "…" .
+```
+
+The criterion link is what lets a reader re-derive the finding instead of trusting it. `kind` plus the relation names it exactly:
+
+| kind | criterion |
+|---|---|
+| `self_loop` | `owl:IrreflexiveProperty` |
+| `asymmetry` | `owl:AsymmetricProperty` |
+| `cycle` | `owl:TransitiveProperty` |
+| `functional` | `owl:FunctionalProperty` |
+| `inverse_functional` | `owl:InverseFunctionalProperty` |
+| `signature` | `rdfs:domain` and `rdfs:range`, together — the row does not retain which side broke, so the contract does not pretend |
+| `derived_contradiction` | the OWL term named by the row's retained `detail.axiom`, on the relation `detail.predicate_id` |
+
+Two rules keep the link honest:
+
+- **Open rows only.** A violation resolved as `axiom_relaxed` (or `criterion_changed`) names an axiom that was removed or widened — linking it into the current vocabulary would assert the opposite of what happened. `fact_retracted` and `fact_closed` do not touch the ontology, but the ontology can have moved since; one rule that stays true beats three that need checking. Resolved rows carry kind, resolution and timestamps and no criterion link.
+- **The ordered path is the evidence for a cycle.** `path` is emitted as an `rdf:List` of fact IRIs in traversal order; "A→B→C→A" is the finding, "A and C conflict" is not. The same list carries the premises of a `derived_contradiction` and the member set of a grouped exclusivity violation. Only asserted statements are addressable in the export: a premise chain that ran through a rule-derived edge keeps the asserted members of the chain, because a premise that is not itself a fact row has no IRI — the export never names a statement it does not contain.
+
+`detectedAt` says what the column says: when this row was recorded, and — because a re-found resolved row reopens with `detected_at` reset — when it was reopened. It is not "first detected": a row that stayed open keeps its original value, and the contract does not claim otherwise. `closedAt` is `decided_at`: when the row stopped being open.
+
+### The `open` invariant
+
+The criterion link on an open row is only true if `open` means *reconciled against the current ontology*. Today's `update_relation_type` can change axioms, domain and range and return without reconciling, leaving open rows whose criterion no longer exists — a state every consumer of the table, not only the export, can observe. The invariant is therefore owned by ontology mutation, not by the exporter:
+
+**When an ontology edit changes a criterion the consistency check reads — axiom flags, `inverse_of`, `sub_property_of`, `temporal`, domain, range, or the class hierarchy — the same transaction closes the open violations whose criterion no longer applies with `resolution = 'criterion_changed'` and re-detects under the new ontology.** `criterion_changed` (migration `0093`) is recorded as a resolution but not an adjudication: `decided_by` stays empty. A row that was already stale under the old criterion — one no detection under it would have found — is deleted as before, not re-labelled.
+
+Mechanically this is one detection pass before the write (the old-ontology baseline), the ontology write, and the existing detection + settle again, in one transaction. Rows a fresh detection no longer finds are partitioned against the baseline: found there → `criterion_changed`; absent there → gone. Reopened rows follow the existing rule — a `criterion_changed` row whose violation recurs reopens like `axiom_relaxed` does.
+
+What is deliberately not claimed:
+
+- The covered surface is every supported criterion mutation: `update_relation_type`, class-parent edits, class deletion, relation deletion that unlinks `inverse_of`/`sub_property_of`, and ontology **import** — which cannot share one transaction across its own batched writes, so it captures the old-ontology baseline before apply and reconciles after, giving retired rows the same `criterion_changed` end state. The interval inside apply's own commits is the pre-existing non-atomicity of import; no committed state after the request completes carries an open row valid only under the old ontology, and a failed reconciliation is an error, not a quiet pass.
+- Facts changing is a data event, not an ontology mutation; invalidation-facing cleanups continue to work as they did.
+
+### History the storage does not keep
+
+The two tables have different guarantees and the contract does not pretend otherwise:
+
+- `fact_conflicts` rows are durable contest records: a resolved or withdrawn row stays.
+- `axiom_violations` rows are **current state, recomputed**. A resolve-then-reopen leaves no trace; `detected_at` resets on reopen; open rows a run cannot re-find are removed. The export serialises the present; nothing in it should be read as an append-only violation history.
+- `path` / `detail` are the evidence as of the latest detection that recorded the row (refreshed per run since #619); they are not a proof reproduced at export time.
+
+If the contract later needs real adjudication history, the storage needs an append-only event rather than a mutable status column. That is a separate decision.
+
+### Out of scope — workflow is not epistemics
+
+None of this enters the contract, now or later, just because it exists in storage:
+
+- `pending_facts`, duplicate/entity-resolution review, mappings, agent proposals, and the rest of the Review UI's queue state;
+- `decided_by` and person identity — *that* it was decided, when, and to what is epistemic; *who clicked* is workflow;
+- an `as_of` export, a generic review-event stream, or a business-rule vocabulary.
+
+## Vocabulary added
+
+Everything without a standard spelling mints under `urn:utopia:ns:`: the classes `FactConflict` and `AxiomViolation`; the links `priorStatement`, `incomingStatement`, `onStatement`, `evidencePath`, `onRelation`, `criterion`; and the literals `reason`, `kind`, `status`, `resolution`, `detectedAt`, `closedAt`. The value sets above are the contract: readers should treat unknown values as a newer contract, not silently.
diff --git a/docs/decisions/README.md b/docs/decisions/README.md
index 8a8fb0e1..3e0a5623 100644
--- a/docs/decisions/README.md
+++ b/docs/decisions/README.md
@@ -81,6 +81,7 @@ The test for writing one: if someone (including us) looks at a piece of code in
| 0053 | [A phrase decision records the inputs it considered](0053-a-phrase-decision-records-the-inputs-it-considered.md) | Implemented 2026-09-23 · a decision stores a fingerprint of the ancestor closures and admitted candidates it saw; stale means the fingerprint of the current inputs differs, which is what timestamps could not see (#807, #795): inheritance, parent edges, edits during the request; no-candidate and overflow become recorded outcomes; requeue reads live signatures only, so orphaned rows stop looping · revised 2026-09-26: kind words fingerprinted too, read from one snapshot and compared again when a reply is accepted
| 0054 | [A source may push statements in the open contract](0054-a-source-may-push-statements-in-the-open-contract.md) | Proposed 2026-09-23 · cut 1 in its PR · a `statements` source accepts the open extraction contract (`e`/`s`/`n`) verbatim on `POST /sources/{id}/statements` with the `api` push's identity, versions and tombstones; the payload is stored as one chunk and extraction parses it instead of prompting a model, then runs the unchanged path, so a pushed statement is an open statement and reaches the typed graph only through alignment; there is no slot for a property or class; an update marks earlier statements stale, it does not close them; tables stay on the mount (0036)
| 0060 | [A rule's definition has a history](0060-a-rule-definition-has-a-history.md) | Implemented 2026-09-25 (#912, migration 0076) · A business rule was edited in place and a derivation pointed at the row, so an invalidated conclusion pointed at a rule that now said something else. Every edit that changes what a rule says opens a **version**, a full snapshot with a record time; a derivation names the version it was drawn under, a kept conclusion moves to the new one, and the proof, the rules panel and a versions endpoint read the history. Name, description and the switch open nothing. Exporting rule bodies per version is now honest and stays #902's second cut |
+| 0062 | [The export says what is contested](0062-the-export-says-what-is-contested.md) | Proposed 2026-09-25 · #564: the RDF export carries `fact_conflicts` and `axiom_violations` as two distinct resource classes — conflicts point at the prior and incoming statements, violations at the statements they are about and (open rows only) the governing criterion and its relation; an ordered `rdf:List` keeps cycle paths; precondition is the current-ontology invariant: `status = 'open'` means reconciled against the current ontology, so criterion-changing ontology edits settle superseded open rows with `criterion_changed` and re-detect in the same transaction
| | Record | Domain | Status |
|---|---|---|---|
@@ -139,6 +140,7 @@ The test for writing one: if someone (including us) looks at a piece of code in
| 0053 | [A phrase decision records the inputs it considered](0053-a-phrase-decision-records-the-inputs-it-considered.md) | ontology | current |
| 0054 | [A source may push statements in the open contract](0054-a-source-may-push-statements-in-the-open-contract.md) | sources | proposed |
| 0060 | [A rule's definition has a history](0060-a-rule-definition-has-a-history.md) | rules | current |
+| 0062 | [The export says what is contested](0062-the-export-says-what-is-contested.md) | ontology | proposed |
The status word is whether a later record has overtaken this one; what is built is in the record's own status line. Domains are the files of [../design/](../design/README.md), where every record is dated and the status words are defined.
diff --git a/migrations/0093_an_axiom_that_moved_closes_its_findings.sql b/migrations/0093_an_axiom_that_moved_closes_its_findings.sql
new file mode 100644
index 00000000..baf674ab
--- /dev/null
+++ b/migrations/0093_an_axiom_that_moved_closes_its_findings.sql
@@ -0,0 +1,34 @@
+-- 判据动了,靠着它开着的结论随之收场(0062 / #564)。
+--
+-- `axiom_violations.status = 'open'` 的约定从这条起收紧成「已对账于**当前**
+-- 本体」:`update_relation_type` 改掉公理或 domain / range 时,同一事务里
+-- 重新检出;只在旧判据下还成立的 open 行不能删——删掉就把「这条违规是在
+-- 哪条公理下结束」这件事抹了——也不能继续开着——开着就意味着当前本体还判它。
+-- 给它们一个收场理由 `criterion_changed`:不是人裁的(decided_by 空),是判据
+-- 换了。
+--
+-- 它在语义上是 `axiom_relaxed` 的邻铺:那条说的是「人承认这条公理写错了」,
+-- 这条说的是「公理改了,这个发现不再成立」。两者都承诺「世界变了所以违规不该
+-- 再算出来」——重开检查(`reasoning::run` 把 resolved 的破约行翻回 open)认它
+-- 同样的话。
+
+ALTER TABLE axiom_violations
+ DROP CONSTRAINT axiom_violations_resolution_check,
+ ADD CONSTRAINT axiom_violations_resolution_check CHECK (resolution IN (
+ 'fact_retracted', 'fact_closed', 'axiom_relaxed', 'accepted',
+ 'criterion_changed'
+ ));
+
+-- #861 起规则推出的关系边以临时 id 进前提链,`derived_contradiction` 的 `path`
+-- 曾把不属于任何表的 id 落了库。落库的 path 是导出的证据链,成员必须回得到
+-- 本库 `facts` 的行——把回不成的成员剔掉(顺序不动)
+UPDATE axiom_violations v
+ SET path = COALESCE((
+ SELECT array_agg(m ORDER BY ord)
+ FROM unnest(v.path) WITH ORDINALITY AS u(m, ord)
+ WHERE EXISTS (SELECT 1 FROM facts f WHERE f.id = m AND f.kb_id = v.kb_id)
+ ), '{}')
+ WHERE EXISTS (
+ SELECT 1 FROM unnest(v.path) AS m
+ WHERE NOT EXISTS (SELECT 1 FROM facts f WHERE f.id = m AND f.kb_id = v.kb_id)
+ );