Skip to content

World's first open-source enterprise world model.

The ontology can say what a relation's inverse is, and the engine uses it (#177)

WaylandYangcf01b5329f00
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index 025b9a00..d1bb5728 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -328,6 +328,10 @@ pub struct RelationTypeView {
pub is_symmetric: bool,
pub is_asymmetric: bool,
pub is_irreflexive: bool,
+ /// 指向另一个关系的两条。**必须回给界面**——下拉框要显示当前选的是谁,
+ /// 否则每次打开表单都是空的,编辑一次就把已声明的抹掉了
+ pub inverse_of: Option<Uuid>,
+ pub sub_property_of: Option<Uuid>,
pub builtin: bool,
pub description: String,
/// relation(宾语是实体)| attribute(宾语是字面值)
@@ -936,9 +940,13 @@ pub struct ReviewCounts {
/// 一个关系声明了哪些 OWL 公理。
///
-/// **六位打包成一个东西传,不是六个参数。** 它们本来就是同一族——推理机
+/// **打包成一个东西传,不是一串参数。** 它们本来就是同一族——推理机
/// (0002)拿它们当判据,界面上也该并排出现;散成参数表里的六个 bool,
/// 调用点迟早传错顺序,而 `bool` 之间编译器帮不上忙。
+///
+/// 后两位不是 bool:`inverseOf` 与 `subPropertyOf` 指向**另一个关系**,
+/// 界面上是下拉框而不是复选框。形状不同不改变它们属于这一族——推理机
+/// 的四种规则源正是这六位里的两条加上这两条(0002)。
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RelationAxioms {
/// 主语侧唯一(一个人一个出生地)
@@ -953,6 +961,11 @@ pub struct RelationAxioms {
pub asymmetric: bool,
/// 不存在 A→A
pub irreflexive: bool,
+ /// `p⁻¹ = q`:`A p B ⟹ B q A`。**单向存,双向用**——载入公理时归一化
+ /// (`reasoning::axioms`),所以只需在一侧声明,反向那条自动成立
+ pub inverse_of: Option<Uuid>,
+ /// `p ⊑ q`:`A p B ⟹ A q B`。断言了具体的,通用的也成立
+ pub sub_property_of: Option<Uuid>,
}
/// 文库的一页,连同这一页之外的统计。
@@ -968,3 +981,24 @@ pub struct DocumentPage {
pub extracting: i64,
pub failed: i64,
}
+
+/// 一枚个人访问令牌的元信息(0014)。**永远不含明文**——
+/// 明文只在 `tokens::issue` 返回的那一次存在,库里只有哈希。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct TokenView {
+ pub id: Uuid,
+ pub name: String,
+ /// 给人认的那一小截(`utp_pat_ab12`)。够对上配置文件里那一串,
+ /// 又不足以复原
+ pub token_prefix: String,
+ /// read | write。**上限不是授权**:有效权限 = 这个人的角色 ∩ 这个 scope
+ pub scope: String,
+ /// None = 这个人能进的全部库
+ pub kb_ids: Option<Vec<Uuid>>,
+ pub expires_at: Option<DateTime<Utc>>,
+ /// 「这把还在用吗」。撤之前要答得出,否则没人敢撤
+ pub last_used_at: Option<DateTime<Utc>>,
+ /// **撤销打戳不删行**:撤过这件事本身要留痕
+ pub revoked_at: Option<DateTime<Utc>>,
+ pub created_at: DateTime<Utc>,
+}
diff --git a/crates/utopia-ingest/src/ontology_rdf.rs b/crates/utopia-ingest/src/ontology_rdf.rs
index 9ea11c40..e9393f7f 100644
--- a/crates/utopia-ingest/src/ontology_rdf.rs
+++ b/crates/utopia-ingest/src/ontology_rdf.rs
@@ -43,6 +43,13 @@ pub struct OwlProperty {
pub symmetric: bool,
pub asymmetric: bool,
pub irreflexive: bool,
+ /// `owl:inverseOf` 的对端 IRI。**只按写的方向收**——归一化(补上反向)
+ /// 在读取公理时做(`reasoning::axioms`),那里绕不过去;
+ /// 在这里补会让「本体自己写了什么」和「我们推出来的」分不开
+ pub inverse_of: Option<String>,
+ /// `rdfs:subPropertyOf` 的父属性 IRI。多写几条只留第一条——
+ /// OWL 允许多父,而 R1 的规则一次只升一级,多父要另一套形状
+ pub sub_property_of: Option<String>,
pub domains: Vec<String>,
pub ranges: Vec<String>,
/// **多条 range 是并集还是交集**。`rdfs:range` 写多条是交集
@@ -219,6 +226,9 @@ pub fn project(bytes: &[u8], format: RdfFormat) -> anyhow::Result<OwlProjection>
let mut inverse_functional: BTreeSet<String> = BTreeSet::new();
let mut transitive: BTreeSet<String> = BTreeSet::new();
let mut symmetric: BTreeSet<String> = BTreeSet::new();
+ // 属性之间的两条关系(不是类型声明,所以单独收)
+ let mut inverse_of: BTreeMap<String, String> = BTreeMap::new();
+ let mut sub_property_of: BTreeMap<String, String> = BTreeMap::new();
let mut asymmetric: BTreeSet<String> = BTreeSet::new();
let mut irreflexive: BTreeSet<String> = BTreeSet::new();
let mut plain_props: BTreeSet<String> = BTreeSet::new();
@@ -304,6 +314,7 @@ pub fn project(bytes: &[u8], format: RdfFormat) -> anyhow::Result<OwlProjection>
|| is_schema(p, "domainIncludes")
|| is_schema(p, "rangeIncludes")
|| p == format!("{OWL}disjointWith")
+ || p == format!("{OWL}inverseOf")
};
for t in &triples {
let p = t.predicate.as_str();
@@ -332,6 +343,23 @@ pub fn project(bytes: &[u8], format: RdfFormat) -> anyhow::Result<OwlProjection>
.or_default()
.push(t.subject.clone());
}
+ } else if p == format!("{OWL}inverseOf") {
+ // **只按写的方向收。** OWL 里 `p owl:inverseOf q` 蕴含反向,
+ // 而词表通常只写一遍。补反向是在读取公理时做的
+ //(`reasoning::axioms`,那一处绕不过去)——在这里补会让
+ // 「本体自己写了什么」和「我们推出来的」分不开,而 R0 有一条
+ // `inverse_not_mutual` 检查恰恰要区分这两者
+ if let Some(o) = &t.object_iri {
+ inverse_of.entry(t.subject.clone()).or_insert(o.clone());
+ }
+ } else if p == format!("{RDFS}subPropertyOf") {
+ // 从前这条只出现在 `known()` 白名单里——认得出、不报警、**然后扔掉**。
+ // 导一份带 subPropertyOf 的本体进来,那部分信息当场消失且没有提示
+ if let Some(o) = &t.object_iri {
+ sub_property_of
+ .entry(t.subject.clone())
+ .or_insert(o.clone());
+ }
} else if p == format!("{RDFS}subClassOf") {
if let Some(o) = &t.object_iri {
parents
@@ -450,6 +478,8 @@ pub fn project(bytes: &[u8], format: RdfFormat) -> anyhow::Result<OwlProjection>
transitive: transitive.contains(iri),
symmetric: symmetric.contains(iri),
asymmetric: asymmetric.contains(iri),
+ inverse_of: inverse_of.get(iri).cloned(),
+ sub_property_of: sub_property_of.get(iri).cloned(),
irreflexive: irreflexive.contains(iri),
domains: domains.get(iri).cloned().unwrap_or_default(),
ranges: rs,
@@ -1249,3 +1279,44 @@ mod against_real_packs {
);
}
}
+
+#[cfg(test)]
+mod property_axiom_tests {
+ use super::*;
+
+ /// `owl:inverseOf` 与 `rdfs:subPropertyOf` 要被读出来。
+ ///
+ /// 从前 `subPropertyOf` 只出现在 `known()` 白名单里——认得出、不报警、
+ /// **然后扔掉**;`inverseOf` 连白名单都没进,被算进「暂未投影」。
+ /// 两种都是导一份本体进来,那部分信息当场消失。
+ #[test]
+ fn the_two_property_relations_survive_projection() {
+ let ttl = include_str!("../tests/inverse_and_sub.ttl");
+ let p = project(ttl.as_bytes(), RdfFormat::Turtle).expect("解析");
+ let by = |k: &str| {
+ p.properties
+ .iter()
+ .find(|x| x.key == k)
+ .unwrap_or_else(|| panic!("没有 {k}"))
+ };
+ assert_eq!(
+ by("employs").inverse_of.as_deref(),
+ Some("http://example.org/worksAt"),
+ "**逆要按写的方向收**——补反向是读取公理时的事"
+ );
+ assert_eq!(
+ by("ceo_of").sub_property_of.as_deref(),
+ Some("http://example.org/worksAt")
+ );
+ // 反方向没写,就该是空的:本体写了什么与我们推了什么要分得开,
+ // R0 的 inverse_not_mutual 检查靠这个区分
+ assert!(
+ by("works_at").inverse_of.is_none(),
+ "没写的方向不该在导入时被补上"
+ );
+ assert!(
+ !p.unprojected.keys().any(|k| k.contains("inverseOf")),
+ "**认了就不该再算进「暂未投影」**"
+ );
+ }
+}
diff --git a/crates/utopia-ingest/tests/inverse_and_sub.ttl b/crates/utopia-ingest/tests/inverse_and_sub.ttl
new file mode 100644
index 00000000..d7f70f7a
--- /dev/null
+++ b/crates/utopia-ingest/tests/inverse_and_sub.ttl
@@ -0,0 +1,20 @@
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+@prefix ex: <http://example.org/> .
+
+ex:Person a owl:Class ; rdfs:label "Person" ; rdfs:comment "A human being." .
+ex:Org a owl:Class ; rdfs:label "Organization" ; rdfs:comment "A company." .
+
+ex:worksAt a owl:ObjectProperty ;
+ rdfs:label "works at" ; rdfs:comment "Employment." ;
+ rdfs:domain ex:Person ; rdfs:range ex:Org .
+
+ex:employs a owl:ObjectProperty ;
+ rdfs:label "employs" ; rdfs:comment "The other direction." ;
+ rdfs:domain ex:Org ; rdfs:range ex:Person ;
+ owl:inverseOf ex:worksAt .
+
+ex:ceoOf a owl:ObjectProperty ;
+ rdfs:label "CEO of" ; rdfs:comment "Chief executive." ;
+ rdfs:domain ex:Person ; rdfs:range ex:Org ;
+ rdfs:subPropertyOf ex:worksAt .
diff --git a/crates/utopia-reason/src/derive.rs b/crates/utopia-reason/src/derive.rs
index 00c70374..73c8ab2e 100644
--- a/crates/utopia-reason/src/derive.rs
+++ b/crates/utopia-reason/src/derive.rs
@@ -37,6 +37,11 @@ pub enum Rule {
Transitive,
/// `A p B` ⟹ `B p A`
Symmetric,
+ /// `A p B` ∧ `p⁻¹ = q` ⟹ `B q A`。**主宾对调且换谓词**——
+ /// 两件事一起发生,只做一件是这条规则最容易写错的地方
+ Inverse,
+ /// `A p B` ∧ `p ⊑ q` ⟹ `A q B`。主宾不动,只升谓词
+ SubProperty,
}
impl Rule {
@@ -44,6 +49,8 @@ impl Rule {
match self {
Rule::Transitive => "transitive",
Rule::Symmetric => "symmetric",
+ Rule::Inverse => "inverse",
+ Rule::SubProperty => "sub_property",
}
}
}
@@ -52,6 +59,16 @@ impl Rule {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Derived {
pub predicate: Uuid,
+ /// **哪个谓词的声明触发了它。**
+ ///
+ /// 传递与对称不换谓词,`via == predicate`;而 `inverseOf` 与
+ /// `subPropertyOf` 换——`ceo_of ⊑ works_at` 推出的事实谓词是 `works_at`,
+ /// 而声明写在 `ceo_of` 上。
+ ///
+ /// 落库时按 `via` 找规则行。**这里踩过一次**:原先按 `predicate` 找,
+ /// 前两条规则一直对(两者相同),加了跨谓词的两条之后查不到规则,
+ /// 于是 `continue` 静默丢弃——推出来了却不落库,最难查的那一种。
+ pub via: Uuid,
pub subject: Uuid,
pub object: Uuid,
pub rule: Rule,
@@ -117,171 +134,232 @@ struct Reached {
premises: Vec<Uuid>,
}
+/// 一条三元组的身份:(谓词, 主语, 宾语)。
+///
+/// **谓词进了 key,这是这一版最要紧的改动。** 从前推导按谓词分组、组内自成一体,
+/// 因为传递与对称都不换谓词;而 `inverseOf` 与 `subPropertyOf` 天生跨谓词——
+/// `A works_at B` 推出的是 `B employs A`,落在另一个谓词上。分组一做,这两条
+/// 规则就无处安放。
+type Triple = (Uuid, Uuid, Uuid);
+
/// 拿公理推一遍这批边。
+///
+/// **全局不动点,不再按谓词分组。** 三条规则会串起来:
+///
+/// ```text
+/// A ceo_of B --(subPropertyOf)--> A works_at B --(inverseOf)--> B employs A
+/// ```
+///
+/// 各谓词各算各的话,这条链在第一步就断了。所以改成半朴素求值扫全集:每一轮拿上
+/// 一轮的新边(frontier)再推一遍,没有新增就停。
+///
+/// 三条一跳规则(对称/逆/子属性)与传递放在同一轮里,因为它们互为输入——
+/// 逆推出来的边可能让某条传递链接得上,反之亦然。
pub fn derive(edges: &[TimedEdge], axioms: &HashMap<Uuid, Axioms>) -> Derivation {
let mut out = Derivation::default();
- let mut by_pred: HashMap<Uuid, Vec<TimedEdge>> = HashMap::new();
- for e in edges {
- let Some(ax) = axioms.get(&e.edge.predicate) else {
- continue;
- };
- if !ax.transitive && !ax.symmetric {
- continue;
- }
- by_pred.entry(e.edge.predicate).or_default().push(*e);
- }
- // 谓词按 id 排序:同一个库两次推导该给出同一份结果
- let mut preds: Vec<Uuid> = by_pred.keys().copied().collect();
- preds.sort();
- for pred in preds {
- let group = &by_pred[&pred];
- let ax = axioms[&pred];
- one_predicate(pred, group, ax, &mut out);
- }
- out
-}
-fn one_predicate(pred: Uuid, group: &[TimedEdge], ax: Axioms, out: &mut Derivation) {
// 断言过的三元组。**派生撞上它就让路**——asserted > derived 是硬性的
- let asserted: HashSet<(Uuid, Uuid)> = group
+ let asserted: HashSet<Triple> = edges
.iter()
- .map(|e| (e.edge.subject, e.edge.object))
+ .map(|e| (e.edge.predicate, e.edge.subject, e.edge.object))
.collect();
- // 已经推出来的 (主, 宾) → 怎么来的。同一对只留第一条证明:
- // 多条路径都能推出同一件事时,展示哪一条对用户没有区别,而全存下来
- // 会让证明树的规模跟着路径数走
- let mut reached: HashMap<(Uuid, Uuid), Reached> = HashMap::new();
- let mut emitted: Vec<Derived> = Vec::new();
- let mut capped = false;
-
- // ---- 对称:一跳就够,不进迭代
- if ax.symmetric {
- for e in group {
- let pair = (e.edge.object, e.edge.subject);
- if pair.0 == pair.1 || asserted.contains(&pair) || reached.contains_key(&pair) {
- continue;
- }
- reached.insert(
- pair,
+ // 已经推出来的 → 怎么来的。同一条只留第一条证明:多条路径都能推出同一件事
+ // 时,展示哪一条对用户没有区别,而全存下来会让证明树的规模跟着路径数走
+ let mut reached: HashMap<Triple, Reached> = HashMap::new();
+ // **封顶仍按谓词计**:那个常量的含义没变(一个谓词最多推两万条),
+ // 而 `Derivation::capped` 回的也是谓词列表。跨谓词之后若改成全局一个数,
+ // 界面上「哪个谓词太密」就答不出来了
+ let mut per_pred: HashMap<Uuid, usize> = HashMap::new();
+ let mut capped: HashSet<Uuid> = HashSet::new();
+
+ // 从 (谓词, 主语) 出发能走的边,传递用。派生出来的也进来——它们已经是
+ // 我们的断言了,链上不该因为「来路不同」断掉
+ let mut adj: HashMap<(Uuid, Uuid), Vec<Hop>> = HashMap::new();
+ for e in edges {
+ adj.entry((e.edge.predicate, e.edge.subject))
+ .or_default()
+ .push((e.edge.object, e.from, e.to, e.edge.fact));
+ }
+
+ let mut frontier: Vec<(Triple, Reached)> = edges
+ .iter()
+ .map(|e| {
+ (
+ (e.edge.predicate, e.edge.subject, e.edge.object),
Reached {
from: e.from,
to: e.to,
premises: vec![e.edge.fact],
},
- );
- emitted.push(Derived {
- predicate: pred,
- subject: pair.0,
- object: pair.1,
- rule: Rule::Symmetric,
- premises: vec![e.edge.fact],
- });
+ )
+ })
+ .collect();
+ // 起始 frontier 的顺序跟着入参走,而入参顺序不保证——排一次,
+ // 同一个库两次推导才给得出同一份结果
+ frontier.sort_by_key(|(t, _)| *t);
+
+ // 轮数上限是**兜底**,真正的界在下面那条 `premises.len() >= MAX_DEPTH`:
+ // 常量的含义是「路径最长 12」,按前提条数算才对得上。轮数只防病态输入
+ for _ in 0..MAX_DEPTH {
+ if frontier.is_empty() {
+ break;
}
- }
+ let mut next: Vec<(Triple, Reached)> = Vec::new();
- // ---- 传递:半朴素求值。frontier 是上一轮新产生的,只有它需要再往下接
- if ax.transitive {
- // 从主语出发能走的边。对称推出来的那些也算基础事实——它们已经是我们
- // 的断言了,链上不该因为「来路不同」断掉
- let mut base: HashMap<Uuid, Vec<Hop>> = HashMap::new();
- for e in group {
- base.entry(e.edge.subject).or_default().push((
- e.edge.object,
- e.from,
- e.to,
- e.edge.fact,
- ));
- }
- for ((s, o), r) in reached.iter() {
- if let Some(&p) = r.premises.first() {
- base.entry(*s).or_default().push((*o, r.from, r.to, p));
+ for (triple, acc) in frontier.drain(..) {
+ let (pred, subj, obj) = triple;
+ let Some(ax) = axioms.get(&pred) else {
+ continue;
+ };
+ // 再接一条就超了:这一条不再往下延,但它自己已经产出过
+ if acc.premises.len() >= MAX_DEPTH {
+ continue;
}
- }
-
- let mut frontier: Vec<((Uuid, Uuid), Reached)> = group
- .iter()
- .map(|e| {
- (
- (e.edge.subject, e.edge.object),
- Reached {
- from: e.from,
- to: e.to,
- premises: vec![e.edge.fact],
- },
- )
- })
- .collect();
- // **`MAX_DEPTH - 1` 轮,不是 MAX_DEPTH 轮。** 起始 frontier 里每条已经
- // 带着一条前提,此后每轮加一条——跑满 MAX_DEPTH 轮会得到 13 条前提的
- // 证明,而那个常量在 R0 那边的含义是「路径最长 12」。两处得是同一个意思
- for _ in 0..MAX_DEPTH.saturating_sub(1) {
- if frontier.is_empty() {
- break;
+ // ---- 一跳的三条:换主宾(对称)、换谓词(逆 / 子属性)
+ let mut hops: Vec<(Triple, Rule)> = Vec::new();
+ if ax.symmetric {
+ hops.push(((pred, obj, subj), Rule::Symmetric));
+ }
+ if let Some(inv) = ax.inverse_of {
+ // `A p B ⟹ B p⁻¹ A`。主宾对调**且**谓词换掉——两件事一起发生,
+ // 只做一件是这条规则最容易写错的地方
+ hops.push(((inv, obj, subj), Rule::Inverse));
}
- let mut next: Vec<((Uuid, Uuid), Reached)> = Vec::new();
- for ((a, b), acc) in frontier.drain(..) {
- let Some(outs) = base.get(&b) else {
+ if let Some(sup) = ax.sub_property_of {
+ // `A p B ∧ p ⊑ q ⟹ A q B`。主宾不动,只升谓词
+ hops.push(((sup, subj, obj), Rule::SubProperty));
+ }
+ for (t, rule) in hops {
+ if emit(
+ t,
+ pred,
+ rule,
+ &acc,
+ acc.from,
+ acc.to,
+ None,
+ &asserted,
+ &mut reached,
+ &mut per_pred,
+ &mut capped,
+ &mut out,
+ &mut next,
+ &mut adj,
+ ) {
continue;
- };
- for &(c, from, to, fact) in outs {
+ }
+ }
+
+ // ---- 传递:需要接一条同谓词的出边
+ if ax.transitive {
+ let outs = adj.get(&(pred, obj)).cloned().unwrap_or_default();
+ for (c, from, to, fact) in outs {
// **不推自环。** `A p A` 在一个传递+反对称的谓词上是矛盾
// 而不是知识,R0 那边会把这个环连路径一起报出来
- if a == c {
- continue;
- }
- if asserted.contains(&(a, c)) || reached.contains_key(&(a, c)) {
+ if subj == c {
continue;
}
let Some((nf, nt)) = overlap((acc.from, acc.to), (from, to)) else {
continue;
};
- if emitted.len() >= MAX_DERIVED_PER_PREDICATE {
- capped = true;
- break;
- }
- let mut premises = acc.premises.clone();
- premises.push(fact);
- reached.insert(
- (a, c),
- Reached {
- from: nf,
- to: nt,
- premises: premises.clone(),
- },
+ emit(
+ (pred, subj, c),
+ pred,
+ Rule::Transitive,
+ &acc,
+ nf,
+ nt,
+ Some(fact),
+ &asserted,
+ &mut reached,
+ &mut per_pred,
+ &mut capped,
+ &mut out,
+ &mut next,
+ &mut adj,
);
- emitted.push(Derived {
- predicate: pred,
- subject: a,
- object: c,
- rule: Rule::Transitive,
- premises: premises.clone(),
- });
- next.push((
- (a, c),
- Reached {
- from: nf,
- to: nt,
- premises,
- },
- ));
- }
- if capped {
- break;
}
}
- if capped {
- break;
- }
- frontier = next;
}
+ next.sort_by_key(|(t, _)| *t);
+ frontier = next;
}
- out.facts.extend(emitted);
- if capped {
- out.capped.push(pred);
+ let mut capped: Vec<Uuid> = capped.into_iter().collect();
+ capped.sort();
+ out.capped = capped;
+ out
+}
+
+/// 落一条派生,并把它接进邻接表供后续传递使用。返回 true = 这个谓词封顶了。
+///
+/// 参数多得难看,但把它抽出来是必要的:四条规则各自的落地动作一模一样
+/// (查断言、查已推、算区间、记证明、进 frontier、进邻接表),而上一版
+/// 正是因为对称与传递各写一遍,两处的「跳过条件」慢慢长得不一样了。
+#[allow(clippy::too_many_arguments)]
+fn emit(
+ t: Triple,
+ // 触发它的那个谓词的声明。四条规则都是「当前展开的这条边的谓词」
+ via: Uuid,
+ rule: Rule,
+ acc: &Reached,
+ from: Option<i64>,
+ to: Option<i64>,
+ // 传递多用掉的那一条前提;一跳规则没有
+ extra_premise: Option<Uuid>,
+ asserted: &HashSet<Triple>,
+ reached: &mut HashMap<Triple, Reached>,
+ per_pred: &mut HashMap<Uuid, usize>,
+ capped: &mut HashSet<Uuid>,
+ out: &mut Derivation,
+ next: &mut Vec<(Triple, Reached)>,
+ adj: &mut HashMap<(Uuid, Uuid), Vec<Hop>>,
+) -> bool {
+ let (pred, subj, obj) = t;
+ // 自环不推,任何规则都一样:`A p A` 是矛盾不是知识
+ if subj == obj {
+ return false;
+ }
+ // 断言优先;已经推过的不重复推——**逆的互指靠这一条收敛**:
+ // `p⁻¹ = q` 且 `q⁻¹ = p` 时,第二轮推回来的那条已经在 reached 里
+ if asserted.contains(&t) || reached.contains_key(&t) {
+ return false;
}
+ let n = per_pred.entry(pred).or_insert(0);
+ if *n >= MAX_DERIVED_PER_PREDICATE {
+ capped.insert(pred);
+ return true;
+ }
+ *n += 1;
+
+ let mut premises = acc.premises.clone();
+ if let Some(p) = extra_premise {
+ premises.push(p);
+ }
+ let r = Reached {
+ from,
+ to,
+ premises: premises.clone(),
+ };
+ reached.insert(t, r.clone());
+ // 派生出来的边也能被后续传递接上
+ if let Some(&first) = premises.first() {
+ adj.entry((pred, subj))
+ .or_default()
+ .push((obj, from, to, first));
+ }
+ out.facts.push(Derived {
+ predicate: pred,
+ via,
+ subject: subj,
+ object: obj,
+ rule,
+ premises,
+ });
+ next.push((t, r));
+ false
}
/// 派生事实的有效期,给落库那一侧用。
@@ -501,4 +579,221 @@ mod tests {
let d = derive(&edges, &transitive());
assert!(d.facts.is_empty(), "1 →(99) 2 →(98) 3 推不出任何东西");
}
+
+ // ---- 跨谓词的两条规则(inverseOf / subPropertyOf)----
+ //
+ // 上面那些用的都是单谓词 `n(99)`;这两条规则天生要三个谓词才说得清,
+ // 所以另起一组常量与构造器
+
+ const P: Uuid = Uuid::from_bytes([1; 16]);
+ const Q: Uuid = Uuid::from_bytes([2; 16]);
+ const R: Uuid = Uuid::from_bytes([3; 16]);
+
+ /// 指定谓词的一条无时间边
+ fn ep(pred: Uuid, fact: u8, s: u8, o: u8) -> TimedEdge {
+ TimedEdge {
+ edge: Edge {
+ fact: f(fact),
+ predicate: pred,
+ subject: n(s),
+ object: n(o),
+ },
+ from: None,
+ to: None,
+ }
+ }
+ /// 指定谓词、带区间
+ fn tep(pred: Uuid, fact: u8, s: u8, o: u8, from: Option<i64>, to: Option<i64>) -> TimedEdge {
+ TimedEdge {
+ from,
+ to,
+ ..ep(pred, fact, s, o)
+ }
+ }
+ /// `p⁻¹ = q` 且 `q⁻¹ = p`——互指,收敛性靠它测
+ fn inverse_pair() -> HashMap<Uuid, Axioms> {
+ HashMap::from([
+ (
+ P,
+ Axioms {
+ inverse_of: Some(Q),
+ ..Default::default()
+ },
+ ),
+ (
+ Q,
+ Axioms {
+ inverse_of: Some(P),
+ ..Default::default()
+ },
+ ),
+ ])
+ }
+ /// `p ⊑ q`
+ fn sub_property() -> HashMap<Uuid, Axioms> {
+ HashMap::from([(
+ P,
+ Axioms {
+ sub_property_of: Some(Q),
+ ..Default::default()
+ },
+ )])
+ }
+
+ /// `A works_at B` ⟹ `B employs A`:主宾对调**且**换谓词。
+ /// 只做一件就是这条规则最常见的写错方式,所以两件都断言。
+ #[test]
+ fn the_inverse_swaps_the_ends_and_the_predicate() {
+ let d = derive(&[ep(P, 1, 1, 2)], &inverse_pair());
+ assert_eq!(d.facts.len(), 1, "一条边只推出一条逆");
+ let got = &d.facts[0];
+ assert_eq!(got.predicate, Q, "**谓词换了**");
+ assert_eq!((got.subject, got.object), (n(2), n(1)), "**主宾也对调了**");
+ assert_eq!(got.rule, Rule::Inverse);
+ assert_eq!(got.via, P, "声明写在 P 上,产出落在 Q 上");
+ assert_eq!(got.premises, vec![f(1)], "证明就是那一条原边");
+ }
+
+ /// `p⁻¹ = q` 且 `q⁻¹ = p` —— 互指。推回来的那条已经断言过,
+ /// 必须收敛而不是来回震荡。
+ #[test]
+ fn a_mutual_inverse_settles_instead_of_bouncing() {
+ let d = derive(&[ep(P, 1, 1, 2), ep(Q, 2, 2, 1)], &inverse_pair());
+ assert!(
+ d.facts.is_empty(),
+ "两个方向都已经断言过,一条都不该推——**断言优先**"
+ );
+ }
+
+ /// `p ⊑ q`:断言具体的,通用的也成立。主宾不动。
+ #[test]
+ fn a_sub_property_lifts_the_predicate_and_keeps_the_ends() {
+ let d = derive(&[ep(P, 1, 1, 2)], &sub_property());
+ assert_eq!(d.facts.len(), 1);
+ let got = &d.facts[0];
+ assert_eq!(got.predicate, Q, "升到父属性");
+ assert_eq!((got.subject, got.object), (n(1), n(2)), "主宾不动");
+ assert_eq!(got.rule, Rule::SubProperty);
+ assert_eq!(
+ got.via, P,
+ "**via 是声明公理的那个谓词**,不是推出来的那个——落库按它找规则行"
+ );
+ }
+
+ /// **不换谓词的两条规则,`via` 必须等于 `predicate`。**
+ ///
+ /// 这条看着是废话,而它正是那个 bug 藏得住的原因:落库从前按 `predicate`
+ /// 找规则行,对传递与对称一直是对的,所以没人发现键选错了。跨谓词的两条
+ /// 一加,`ceo_of ⊑ works_at` 推出的事实就查不到规则、被静默丢弃。
+ #[test]
+ fn for_the_same_predicate_rules_via_is_the_predicate() {
+ let d = derive(&[e(1, 1, 2), e(2, 2, 3)], &transitive());
+ assert!(!d.facts.is_empty());
+ for f in &d.facts {
+ assert_eq!(f.via, f.predicate, "传递不换谓词");
+ }
+ }
+
+ /// **这一条是整次改造的理由**:三条规则串起来。
+ ///
+ /// `A ceo_of B` ∧ `ceo_of ⊑ works_at` ∧ `works_at⁻¹ = employs`
+ /// ⟹ `A works_at B` ⟹ `B employs A`
+ ///
+ /// 按谓词分组的旧结构在第一步就断了。
+ #[test]
+ fn a_sub_property_feeds_the_inverse() {
+ let mut ax = HashMap::new();
+ // ceo_of ⊑ works_at
+ ax.insert(
+ P,
+ Axioms {
+ sub_property_of: Some(Q),
+ ..Default::default()
+ },
+ );
+ // works_at⁻¹ = employs
+ ax.insert(
+ Q,
+ Axioms {
+ inverse_of: Some(R),
+ ..Default::default()
+ },
+ );
+ let d = derive(&[ep(P, 1, 1, 2)], &ax);
+ let mut got: Vec<(Uuid, u8, u8)> = d
+ .facts
+ .iter()
+ .map(|x| (x.predicate, x.subject.as_bytes()[0], x.object.as_bytes()[0]))
+ .collect();
+ got.sort();
+ assert!(got.contains(&(Q, 1, 2)), "先升成 works_at");
+ assert!(
+ got.contains(&(R, 2, 1)),
+ "**再转成 employs 的反方向**——跨了两个谓词,旧结构做不到"
+ );
+ assert_eq!(got.len(), 2);
+ // 证明要跟着长:第二跳用掉两条前提里的第一条
+ let employs = d.facts.iter().find(|x| x.predicate == R).unwrap();
+ assert_eq!(employs.premises, vec![f(1)], "根还是那条原始断言");
+ }
+
+ /// 逆推出来的边要能被传递接上:`p` 传递、`q` 是它的逆,
+ /// `B q A` ∧ `C q B` 应当推出 `C q A`(若 q 也传递)。
+ #[test]
+ fn what_the_inverse_produces_can_still_be_chained() {
+ let mut ax = HashMap::new();
+ ax.insert(
+ P,
+ Axioms {
+ inverse_of: Some(Q),
+ ..Default::default()
+ },
+ );
+ ax.insert(
+ Q,
+ Axioms {
+ transitive: true,
+ ..Default::default()
+ },
+ );
+ // A p B、B p C ⟹ B q A、C q B ⟹(q 传递)⟹ C q A
+ let d = derive(&[ep(P, 1, 1, 2), ep(P, 2, 2, 3)], &ax);
+ let got: Vec<(Uuid, u8, u8)> = d
+ .facts
+ .iter()
+ .map(|x| (x.predicate, x.subject.as_bytes()[0], x.object.as_bytes()[0]))
+ .collect();
+ assert!(got.contains(&(Q, 2, 1)));
+ assert!(got.contains(&(Q, 3, 2)));
+ assert!(
+ got.contains(&(Q, 3, 1)),
+ "**逆产出的边要进邻接表**,否则传递接不上它"
+ );
+ }
+
+ /// 区间照旧取交集,跨谓词也一样。
+ #[test]
+ fn the_inverse_carries_the_same_span() {
+ let d = derive(&[tep(P, 1, 1, 2, Some(10), Some(20))], &inverse_pair());
+ assert_eq!(d.facts.len(), 1);
+ let v = validity(
+ &d.facts[0].premises,
+ &HashMap::from([(f(1), (Some(10), Some(20)))]),
+ );
+ assert_eq!(v, Some((Some(10), Some(20))), "逆不改变有效期");
+ }
+
+ /// 自己是自己的逆 = 对称,但不该推出自环。
+ #[test]
+ fn a_predicate_that_is_its_own_inverse_still_refuses_self_loops() {
+ let ax = HashMap::from([(
+ P,
+ Axioms {
+ inverse_of: Some(P),
+ ..Default::default()
+ },
+ )]);
+ let d = derive(&[ep(P, 1, 1, 1)], &ax);
+ assert!(d.facts.is_empty(), "`A p A` 的逆还是 `A p A`——自环不推");
+ }
}
diff --git a/crates/utopia-reason/src/lib.rs b/crates/utopia-reason/src/lib.rs
index e360b031..f4939003 100644
--- a/crates/utopia-reason/src/lib.rs
+++ b/crates/utopia-reason/src/lib.rs
@@ -36,6 +36,11 @@ pub struct Axioms {
pub irreflexive: bool,
pub functional: bool,
pub inverse_functional: bool,
+ /// `p⁻¹ = q`:这个谓词的逆是哪一个。**跨谓词的规则从这里来**——
+ /// `A p B` 推出 `B q A`,而 R0 的检查也要看它(自己是自己的逆等于对称)
+ pub inverse_of: Option<Uuid>,
+ /// `p ⊑ q`:断言了具体的,通用的也成立。链要防成环,R0 那边查
+ pub sub_property_of: Option<Uuid>,
}
impl Axioms {
diff --git a/crates/utopia-reason/src/ontology.rs b/crates/utopia-reason/src/ontology.rs
index c3c52a4d..dc6e6853 100644
--- a/crates/utopia-reason/src/ontology.rs
+++ b/crates/utopia-reason/src/ontology.rs
@@ -44,6 +44,17 @@ pub enum Defect {
/// 一个类的两个祖先互相互斥 → 同上,不可满足。
/// 多父继承下这个形状不罕见:两支各自合理,合起来就矛盾了。
InheritsDisjoint,
+ /// 一个谓词声明自己是自己的逆。**等价于 symmetric**——推理照跑,
+ /// 只是读的人要多想一步。提示改写成 `symmetric` 更直白
+ InverseOfItself,
+ /// `p⁻¹ = q` 而 `q⁻¹ = r`,两边指得不一样。
+ ///
+ /// 载入公理时只补空缺、不覆盖人写的(**人写的优先于推出来的**),
+ /// 所以这个矛盾不会被悄悄抹平,留到这里报。
+ InverseNotMutual,
+ /// subPropertyOf 绕成了环。与 [`Defect::SubclassCycle`] 同形:
+ /// 环上所有谓词互为子属性 = 它们其实是同一个谓词,而各自有标签、有事实。
+ SubPropertyCycle,
}
impl Defect {
@@ -54,6 +65,9 @@ impl Defect {
Defect::SubclassCycle => "subclass_cycle",
Defect::DisjointWithAncestor => "disjoint_with_ancestor",
Defect::InheritsDisjoint => "inherits_disjoint",
+ Defect::InverseOfItself => "inverse_of_itself",
+ Defect::InverseNotMutual => "inverse_not_mutual",
+ Defect::SubPropertyCycle => "sub_property_cycle",
}
}
}
@@ -102,6 +116,79 @@ pub fn check_ontology(
path: Vec::new(),
});
}
+ // 自己是自己的逆 = 对称。**不是错,是绕远路**——推理照跑,
+ // 但读本体的人得自己想一步才明白。提示改用 `symmetric` 更直白
+ if ax.inverse_of == Some(pred) {
+ out.push(OntologyDefect {
+ kind: Defect::InverseOfItself,
+ subject: pred,
+ other: None,
+ path: Vec::new(),
+ });
+ }
+ // 逆 + 反对称:`A p B` 推出 `B p A`(自己的逆),而反对称说这不成立。
+ // 与 symmetric+asymmetric 同一个矛盾,换了个写法进来
+ if ax.inverse_of == Some(pred) && ax.asymmetric {
+ out.push(OntologyDefect {
+ kind: Defect::SymmetricAndAsymmetric,
+ subject: pred,
+ other: None,
+ path: Vec::new(),
+ });
+ }
+ // 两边各自声明了逆,却指向不同的谓词。**不在载入时悄悄改一致**
+ // (`reasoning::axioms` 那边只补空缺,不覆盖人写的),所以在这里报
+ if let Some(inv) = ax.inverse_of {
+ if let Some(back) = axioms.get(&inv).and_then(|a| a.inverse_of) {
+ if back != pred {
+ out.push(OntologyDefect {
+ kind: Defect::InverseNotMutual,
+ subject: pred,
+ other: Some(inv),
+ path: vec![pred, inv, back],
+ });
+ }
+ }
+ }
+ }
+
+ // ---- subPropertyOf 成环。与 subClassOf 的环是同一个形状:
+ // 环上所有谓词互为子属性 = 它们其实是同一个谓词,而各自有标签、有事实
+ {
+ let parent_of: HashMap<Uuid, Uuid> = axioms
+ .iter()
+ .filter_map(|(id, ax)| ax.sub_property_of.map(|p| (*id, p)))
+ .collect();
+ let mut starts: Vec<Uuid> = parent_of.keys().copied().collect();
+ starts.sort();
+ let mut reported: HashSet<Uuid> = HashSet::new();
+ for start in starts {
+ if reported.contains(&start) {
+ continue;
+ }
+ let mut seen: Vec<Uuid> = Vec::new();
+ let mut cur = start;
+ for _ in 0..MAX_ANCESTRY {
+ if seen.contains(&cur) {
+ // 环上每个成员都标记过,整条环只报一次
+ for m in &seen {
+ reported.insert(*m);
+ }
+ out.push(OntologyDefect {
+ kind: Defect::SubPropertyCycle,
+ subject: start,
+ other: None,
+ path: seen.clone(),
+ });
+ break;
+ }
+ seen.push(cur);
+ match parent_of.get(&cur) {
+ Some(&p) => cur = p,
+ None => break,
+ }
+ }
+ }
}
let up = adjacency(parents);
@@ -390,3 +477,139 @@ mod tests {
assert!(check_ontology(&HashMap::new(), &parents, &[]).is_empty());
}
}
+
+#[cfg(test)]
+mod inverse_and_sub_property_tests {
+ use super::*;
+
+ fn c(i: u8) -> Uuid {
+ Uuid::from_bytes([i; 16])
+ }
+ fn kinds(v: &[OntologyDefect]) -> Vec<Defect> {
+ let mut k: Vec<Defect> = v.iter().map(|d| d.kind).collect();
+ k.sort();
+ k
+ }
+ fn only(id: Uuid, a: Axioms) -> HashMap<Uuid, Axioms> {
+ HashMap::from([(id, a)])
+ }
+
+ /// 自己是自己的逆 —— 合法但绕远路,提示改用 symmetric。
+ #[test]
+ fn a_predicate_that_is_its_own_inverse_should_just_say_symmetric() {
+ let a = Axioms {
+ inverse_of: Some(c(1)),
+ ..Default::default()
+ };
+ let d = check_ontology(&only(c(1), a), &[], &[]);
+ assert_eq!(kinds(&d), vec![Defect::InverseOfItself]);
+ }
+
+ /// 自己的逆 + 反对称 = 与 symmetric+asymmetric 同一个矛盾,换了个写法。
+ #[test]
+ fn its_own_inverse_and_asymmetric_is_the_same_contradiction_in_disguise() {
+ let a = Axioms {
+ inverse_of: Some(c(1)),
+ asymmetric: true,
+ ..Default::default()
+ };
+ let d = check_ontology(&only(c(1), a), &[], &[]);
+ assert!(
+ kinds(&d).contains(&Defect::SymmetricAndAsymmetric),
+ "**要报成同一类**:读的人不该因为写法不同就以为是两回事"
+ );
+ }
+
+ /// 互指一致 —— 干净,什么都不该报。
+ #[test]
+ fn a_mutual_pair_is_clean() {
+ let ax = HashMap::from([
+ (
+ c(1),
+ Axioms {
+ inverse_of: Some(c(2)),
+ ..Default::default()
+ },
+ ),
+ (
+ c(2),
+ Axioms {
+ inverse_of: Some(c(1)),
+ ..Default::default()
+ },
+ ),
+ ]);
+ assert!(check_ontology(&ax, &[], &[]).is_empty());
+ }
+
+ /// `p⁻¹ = q` 而 `q⁻¹ = r` —— 两边指得不一样。
+ ///
+ /// **载入公理时只补空缺不覆盖**,所以这个矛盾不会被悄悄抹平;
+ /// 它必须在这里被报出来,否则没有任何地方会提。
+ #[test]
+ fn an_inverse_that_does_not_point_back_is_reported() {
+ let ax = HashMap::from([
+ (
+ c(1),
+ Axioms {
+ inverse_of: Some(c(2)),
+ ..Default::default()
+ },
+ ),
+ (
+ c(2),
+ Axioms {
+ inverse_of: Some(c(3)),
+ ..Default::default()
+ },
+ ),
+ ]);
+ let d = check_ontology(&ax, &[], &[]);
+ let one = d
+ .iter()
+ .find(|x| x.kind == Defect::InverseNotMutual)
+ .expect("该报 InverseNotMutual");
+ assert_eq!(one.subject, c(1));
+ assert_eq!(one.other, Some(c(2)));
+ assert_eq!(one.path, vec![c(1), c(2), c(3)], "路径要说清指到哪去了");
+ }
+
+ /// subPropertyOf 成环。
+ #[test]
+ fn a_sub_property_ring_is_a_single_predicate_wearing_three_hats() {
+ let mk = |parent: u8| Axioms {
+ sub_property_of: Some(c(parent)),
+ ..Default::default()
+ };
+ let ax = HashMap::from([(c(1), mk(2)), (c(2), mk(3)), (c(3), mk(1))]);
+ let d = check_ontology(&ax, &[], &[]);
+ let ring: Vec<&OntologyDefect> = d
+ .iter()
+ .filter(|x| x.kind == Defect::SubPropertyCycle)
+ .collect();
+ assert_eq!(ring.len(), 1, "**整条环只报一次**,不是每个成员报一遍");
+ assert_eq!(ring[0].path.len(), 3);
+ }
+
+ /// 一条不成环的链不该被误报。
+ #[test]
+ fn a_chain_that_ends_is_not_a_ring() {
+ let ax = HashMap::from([
+ (
+ c(1),
+ Axioms {
+ sub_property_of: Some(c(2)),
+ ..Default::default()
+ },
+ ),
+ (
+ c(2),
+ Axioms {
+ sub_property_of: Some(c(3)),
+ ..Default::default()
+ },
+ ),
+ ]);
+ assert!(check_ontology(&ax, &[], &[]).is_empty());
+ }
+}
diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rs
index 403d4af6..c96473ee 100644
--- a/crates/utopia-server/src/api/ontology_routes.rs
+++ b/crates/utopia-server/src/api/ontology_routes.rs
@@ -223,6 +223,16 @@ pub struct RelationTypeReq {
pub is_asymmetric: bool,
#[serde(default)]
pub is_irreflexive: bool,
+ /// 指向另一个关系的两条(`inverseOf` / `subPropertyOf`)。
+ ///
+ /// **缺省 = 清空,与上面六位同一条规矩。** 它们是同一个表单一次提交的
+ /// 一组声明;一半覆盖一半保留,会让「我把逆去掉了」和「我没碰逆」
+ /// 长得一模一样。属性表单不填这两个,而属性本来就不许有——
+ /// store 层会拦,落库也照样是 NULL
+ #[serde(default)]
+ pub inverse_of: Option<Uuid>,
+ #[serde(default)]
+ pub sub_property_of: Option<Uuid>,
#[serde(default)]
pub description: Option<String>,
/// relation | attribute(创建时定死,更新时忽略)
@@ -244,7 +254,8 @@ pub struct RelationTypeReq {
}
impl RelationTypeReq {
- /// 六位公理打包。**散着传迟早传错顺序**——它们都是 bool,编译器帮不上忙。
+ /// 公理打包。**散着传迟早传错顺序**——六位都是 bool,编译器帮不上忙;
+ /// 后两位都是 `Option<Uuid>`,一样。
fn axioms(&self) -> utopia_core::models::RelationAxioms {
utopia_core::models::RelationAxioms {
functional: self.functional,
@@ -253,6 +264,8 @@ impl RelationTypeReq {
symmetric: self.is_symmetric,
asymmetric: self.is_asymmetric,
irreflexive: self.is_irreflexive,
+ inverse_of: self.inverse_of,
+ sub_property_of: self.sub_property_of,
}
}
}
diff --git a/crates/utopia-server/src/owl_import.rs b/crates/utopia-server/src/owl_import.rs
index 070792d0..40624bb7 100644
--- a/crates/utopia-server/src/owl_import.rs
+++ b/crates/utopia-server/src/owl_import.rs
@@ -543,6 +543,31 @@ pub async fn apply(
let rel_ids =
utopia_store::ontology::create_relation_types_bulk(&state.pool, kb_id, &new_rels).await?;
created_rels += rel_ids.len();
+
+ // 逆与父属性指的是**另一个关系类型**,id 要等全部插完才有——所以是第二遍。
+ // 一遍过只能处理「父属性恰好排在前面」的文件,而 RDF 三元组没有顺序。
+ //
+ // 新建的与已存在的都收:一份本体重导时,这两条声明可能是这次才加上的
+ let mut inv_pairs: Vec<(String, String)> = Vec::new();
+ let mut sub_pairs: Vec<(String, String)> = Vec::new();
+ for item in &plan.relations {
+ let Some(p) = by_prop_iri.get(item.iri.as_str()) else {
+ continue;
+ };
+ if let Some(o) = &p.inverse_of {
+ inv_pairs.push((p.iri.clone(), o.clone()));
+ }
+ if let Some(o) = &p.sub_property_of {
+ sub_pairs.push((p.iri.clone(), o.clone()));
+ }
+ }
+ let (linked_inv, linked_sub) = utopia_store::ontology::link_property_axioms_bulk(
+ &state.pool,
+ kb_id,
+ &inv_pairs,
+ &sub_pairs,
+ )
+ .await?;
// 关联行也摊平:单条版对每条关系跑 4 句(两张表各一次 DELETE 一次 INSERT),
// 一千五百条关系就是六千次提交
let mut link_d: Vec<(Uuid, Uuid)> = Vec::new();
@@ -617,6 +642,10 @@ pub async fn apply(
"classes_updated": updated_classes,
"classes_key_taken": plan.classes.iter().filter(|c| c.disposition == Disposition::KeyTaken).count(),
"relations_seen": plan.relations.len(),
+ // 连上了几条逆 / 父属性。**报出来**——目标 IRI 不在这个库里时会静默跳过
+ // (引用外部词汇表是常态),不给数就没人知道少连了多少
+ "inverse_linked": linked_inv,
+ "sub_property_linked": linked_sub,
"relations_created": created_rels,
"relations_updated": updated_rels,
"attributes_seen": plan.attributes.len(),
diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rs
index c60110fc..1e0748eb 100644
--- a/crates/utopia-store/src/ontology.rs
+++ b/crates/utopia-store/src/ontology.rs
@@ -75,6 +75,7 @@ pub async fn relation_type_views(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<Re
Ok(sqlx::query_as(
"SELECT r.id, r.key, r.label, r.temporal, r.functional, r.inverse_functional,
r.is_transitive, r.is_symmetric, r.is_asymmetric, r.is_irreflexive,
+ r.inverse_of, r.sub_property_of,
r.builtin, r.description,
r.kind, r.datatype, r.unit,
ARRAY(SELECT d.entity_type_id FROM relation_type_domains d
@@ -302,6 +303,68 @@ fn validate_attribute_fields(
}
}
+/// 两条指向别的关系的公理,落库前必须过这里。
+///
+/// **最要紧的一条是同库。** 列上的外键是 `REFERENCES relation_types(id)`,
+/// 它不认知识库——数据库层面,A 库的关系可以指向 B 库的关系。RDF 导入那条路
+/// 天然过不去(按 IRI 在本库里查),而接口收的是裸 UUID:不在这里挡,
+/// 拿到任意一个 UUID 就能让推理机跨库读公理。**不能靠前端只列本库选项**,
+/// 那是界面礼貌,不是边界。
+///
+/// 另外两条:属性没有逆(它的宾语是字面值,反过来无从谈起),
+/// 子属性不能是自己(DB 有 CHECK,但撞上去是 500,得在这里给出人话)。
+/// 而**逆是自己允许**——那等于对称,R0 会提示改用 `symmetric` 更直白,不算错。
+async fn validate_property_links(
+ pool: &PgPool,
+ kb_id: Uuid,
+ self_id: Option<Uuid>,
+ kind: &str,
+ ax: RelationAxioms,
+) -> AppResult<()> {
+ let links = [ax.inverse_of, ax.sub_property_of];
+ if links.iter().all(|l| l.is_none()) {
+ return Ok(());
+ }
+ if kind == "attribute" {
+ return Err(AppError::invalid(
+ "attr_has_no_link",
+ "An attribute cannot have an inverse or a super-property",
+ ));
+ }
+ if self_id.is_some() && ax.sub_property_of == self_id {
+ return Err(AppError::invalid(
+ "sub_property_self",
+ "A relation cannot be its own super-property",
+ ));
+ }
+ for target in links.into_iter().flatten() {
+ let ok: Option<(String,)> =
+ sqlx::query_as("SELECT kind FROM relation_types WHERE id = $1 AND kb_id = $2")
+ .bind(target)
+ .bind(kb_id)
+ .fetch_optional(pool)
+ .await?;
+ match ok {
+ // 不区分「不存在」与「在别的库」:能问出哪个 UUID 存在于别处,
+ // 本身就是一点不该给的信息
+ None => {
+ return Err(AppError::invalid(
+ "unknown_relation",
+ "That relation is not in this knowledge base",
+ ));
+ }
+ Some((k,)) if k != "relation" => {
+ return Err(AppError::invalid(
+ "link_target_is_attr",
+ "An attribute cannot be an inverse or a super-property",
+ ));
+ }
+ Some(_) => {}
+ }
+ }
+ Ok(())
+}
+
#[allow(clippy::too_many_arguments)]
pub async fn create_relation_type(
pool: &PgPool,
@@ -324,6 +387,8 @@ pub async fn create_relation_type(
));
}
validate_attribute_fields(kind, domains, datatype)?;
+ // 新建的行 id 还不存在,指向自己无从谈起——所以 self_id 传 None
+ validate_property_links(pool, kb_id, None, kind, ax).await?;
let is_attr = kind == "attribute";
let id = Uuid::now_v7();
sqlx::query(
@@ -331,8 +396,10 @@ pub async fn create_relation_type(
functional, inverse_functional, description,
kind, datatype, unit,
is_transitive, is_symmetric,
- is_asymmetric, is_irreflexive)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)",
+ is_asymmetric, is_irreflexive,
+ inverse_of, sub_property_of)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
+ $16, $17)",
)
.bind(id)
.bind(kb_id)
@@ -349,6 +416,9 @@ pub async fn create_relation_type(
.bind(ax.symmetric)
.bind(ax.asymmetric)
.bind(ax.irreflexive)
+ // 属性不带这两条(上面已经拦了非空的情况,这里是兜底)
+ .bind(if is_attr { None } else { ax.inverse_of })
+ .bind(if is_attr { None } else { ax.sub_property_of })
.execute(pool)
.await
.map_err(|e| match &e {
@@ -421,9 +491,25 @@ pub async fn update_relation_type(
"datatype must be text / number / date / bool".into(),
));
}
+ // 指向别的关系的两条要先问过库:目标在不在本库、是不是关系。
+ // 只在真的填了的时候查——清空(两个都 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?;
+ }
// kind 不可变(改它会让存量事实语义错乱)。domain/range 可改——
// 它们是签名不是身份,"这个属性也适用于承包商" 是个正当的编辑。
// datatype/unit 只对 attribute 行生效,datatype 缺省保持原值
+ //
+ // 两条链**跟着六位公理一起覆盖式写**:缺省 = 清空,不是「不动」。
+ // 与 `is_transitive` 那几位同一条规矩——它们是同一个表单里同时提交的
+ // 一组声明,一半覆盖一半保留才是真正会出事的语义
let res = sqlx::query(
"UPDATE relation_types
SET label = $3, temporal = $4,
@@ -431,7 +517,8 @@ pub async fn update_relation_type(
datatype = CASE WHEN kind = 'attribute' AND $8 IS NOT NULL THEN $8 ELSE datatype END,
unit = CASE WHEN kind = 'attribute' THEN $9 ELSE unit END,
is_transitive = $10, is_symmetric = $11,
- is_asymmetric = $12, is_irreflexive = $13
+ is_asymmetric = $12, is_irreflexive = $13,
+ inverse_of = $14, sub_property_of = $15
WHERE id = $2 AND kb_id = $1",
)
.bind(kb_id)
@@ -447,6 +534,8 @@ pub async fn update_relation_type(
.bind(ax.symmetric)
.bind(ax.asymmetric)
.bind(ax.irreflexive)
+ .bind(ax.inverse_of)
+ .bind(ax.sub_property_of)
.execute(pool)
.await?;
if res.rows_affected() == 0 {
@@ -1678,3 +1767,46 @@ pub async fn entity_fits_domain(
.await?;
Ok((declared > 0).then_some(ok > 0))
}
+
+/// 把 `owl:inverseOf` / `rdfs:subPropertyOf` 从 IRI 解析成 id。
+///
+/// **必须是第二遍。** 这两条指的是另一个关系类型,而 id 要等全部插完才有——
+/// 一遍过的写法只能处理「父属性恰好排在前面」的文件,而 RDF 三元组没有顺序。
+///
+/// 按 IRI 配对而不是按 key:key 会因为撞名加后缀(`part_of_2`),
+/// 而 IRI 是这份本体里的身份。
+pub async fn link_property_axioms_bulk(
+ pool: &PgPool,
+ kb_id: Uuid,
+ inverse: &[(String, String)],
+ sub_property: &[(String, String)],
+) -> AppResult<(u64, u64)> {
+ let run = |column: &'static str, pairs: &[(String, String)]| {
+ let src: Vec<String> = pairs.iter().map(|(s, _)| s.clone()).collect();
+ let dst: Vec<String> = pairs.iter().map(|(_, d)| d.clone()).collect();
+ async move {
+ if src.is_empty() {
+ return AppResult::Ok(0);
+ }
+ // 目标 IRI 在这个库里找不到就跳过这一条——**部分导入是常态**
+ // (引用了外部词汇表里的属性),一条连不上不该让整次导入失败
+ let sql = format!(
+ "UPDATE relation_types r SET {column} = t.id
+ FROM UNNEST($2::text[], $3::text[]) AS p(src, dst)
+ JOIN relation_types t ON t.kb_id = $1 AND t.iri = p.dst
+ WHERE r.kb_id = $1 AND r.iri = p.src AND r.id <> t.id"
+ );
+ let n = sqlx::query(&sql)
+ .bind(kb_id)
+ .bind(&src)
+ .bind(&dst)
+ .execute(pool)
+ .await?
+ .rows_affected();
+ AppResult::Ok(n)
+ }
+ };
+ let inv = run("inverse_of", inverse).await?;
+ let sub = run("sub_property_of", sub_property).await?;
+ Ok((inv, sub))
+}
diff --git a/crates/utopia-store/src/reasoning.rs b/crates/utopia-store/src/reasoning.rs
index 4ed59933..15b39ff8 100644
--- a/crates/utopia-store/src/reasoning.rs
+++ b/crates/utopia-store/src/reasoning.rs
@@ -72,19 +72,31 @@ async fn edges(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<Edge>> {
/// **只取声明了至少一位的**:一位都没声明的谓词进了表也不会被检查(`says_nothing`
/// 会跳过),白白占内存。而且这个条数本身有意义——它是「有没有判据」的度量,
/// 报告里要用。
+#[allow(clippy::type_complexity)]
async fn axioms(pool: &PgPool, kb_id: Uuid) -> AppResult<HashMap<Uuid, Axioms>> {
- let rows: Vec<(Uuid, bool, bool, bool, bool, bool, bool)> = sqlx::query_as(
+ let rows: Vec<(
+ Uuid,
+ bool,
+ bool,
+ bool,
+ bool,
+ bool,
+ bool,
+ Option<Uuid>,
+ Option<Uuid>,
+ )> = sqlx::query_as(
"SELECT id, is_transitive, is_symmetric, is_asymmetric, is_irreflexive,
- functional, inverse_functional
- FROM relation_types
- WHERE kb_id = $1
- AND (is_transitive OR is_symmetric OR is_asymmetric OR is_irreflexive
- OR functional OR inverse_functional)",
+ functional, inverse_functional, inverse_of, sub_property_of
+ FROM relation_types
+ WHERE kb_id = $1
+ AND (is_transitive OR is_symmetric OR is_asymmetric OR is_irreflexive
+ OR functional OR inverse_functional
+ OR inverse_of IS NOT NULL OR sub_property_of IS NOT NULL)",
)
.bind(kb_id)
.fetch_all(pool)
.await?;
- Ok(rows
+ let mut map: HashMap<Uuid, Axioms> = rows
.into_iter()
.map(
|(
@@ -95,6 +107,8 @@ async fn axioms(pool: &PgPool, kb_id: Uuid) -> AppResult<HashMap<Uuid, Axioms>>
irreflexive,
functional,
inverse_functional,
+ inverse_of,
+ sub_property_of,
)| {
(
id,
@@ -105,11 +119,33 @@ async fn axioms(pool: &PgPool, kb_id: Uuid) -> AppResult<HashMap<Uuid, Axioms>>
irreflexive,
functional,
inverse_functional,
+ inverse_of,
+ sub_property_of,
},
)
},
)
- .collect())
+ .collect();
+
+ // **逆是相互的,而库里只存单向。** 声明了 `p⁻¹ = q` 却没回填
+ // `q⁻¹ = p` 的话,`A p B` 推得出 `B q A`,`B q A` 却推不回 `A p B`
+ // ——「问工作和问雇佣答案不同」正是 R1 要消灭的东西,只修一半等于没修。
+ //
+ // 归一化放在这里而不是数据库触发器:绕过触发器的路不止一条(RDF 导入、
+ // 直接改表),而载入公理只有这一处,谁也绕不过去。
+ let pairs: Vec<(Uuid, Uuid)> = map
+ .iter()
+ .filter_map(|(id, ax)| ax.inverse_of.map(|inv| (inv, *id)))
+ .collect();
+ for (target, source) in pairs {
+ // 已经声明了自己的逆就不动它——**人写的优先于推出来的**,
+ // 两边指得不一样是本体自己的矛盾,交给 R0 报,不在这里悄悄改
+ map.entry(target)
+ .or_default()
+ .inverse_of
+ .get_or_insert(source);
+ }
+ Ok(map)
}
/// 跑一遍检查,把结果落库。
@@ -365,6 +401,13 @@ pub struct DeriveReport {
pub invalidated: usize,
/// 撞上单谓词上限、没推完的谓词个数
pub capped: usize,
+ /// **推出来了却找不到对应规则行的条数。正常应当恒为零。**
+ ///
+ /// 不为零意味着规则编译与推导对不上了。之前这里是一句 `continue`,
+ /// 于是 `ceo_of ⊑ works_at` 推出的那条 `works_at` 事实**推出来了却不落库**,
+ /// 而下游靠它推出的 `employs` 反倒进了库——一条派生的前提凭空消失。
+ /// 数出来,别再让它静默一次
+ pub unruled: usize,
}
/// 派生事实的身份:三元组 + 区间。
@@ -413,6 +456,15 @@ async fn compile_rules(
if a.symmetric {
want.push((pred, "symmetric"));
}
+ // 后两种是 0017 补上的规则源。**规则挂在「有声明的那一侧」**——
+ // 归一化过的逆两边都有声明,所以两个方向各得一条规则,与它们各自
+ // 推出的派生对得上
+ if a.inverse_of.is_some() {
+ want.push((pred, "inverse"));
+ }
+ if a.sub_property_of.is_some() {
+ want.push((pred, "sub_property"));
+ }
}
want.sort();
let mut out = HashMap::new();
@@ -557,7 +609,14 @@ pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport>
}
for ((subject, predicate, object, from, to), d) in wanted {
- let Some(&rule_id) = rules.get(&(predicate, d.rule.as_str())) else {
+ // **按 `via` 查,不是 `predicate`。** 规则行是给「声明了公理的那个
+ // 谓词」编的;跨谓词的两条规则里,派生出来的谓词是另一个。
+ // 原先按 predicate 查,前两条规则一直对(两者相同),加了 inverse /
+ // sub_property 之后查不到规则就 `continue`——推出来了却不落库
+ let Some(&rule_id) = rules.get(&(d.via, d.rule.as_str())) else {
+ // 查不到规则是**编译与推导不一致**,不是正常情况。数出来,
+ // 别再让它静默消失一次
+ report.unruled += 1;
continue;
};
// 精度与置信度都取前提里最保守的那一个
diff --git a/crates/utopia-store/tests/a_relation_points_only_inside_its_own_kb.rs b/crates/utopia-store/tests/a_relation_points_only_inside_its_own_kb.rs
new file mode 100644
index 00000000..152cd670
--- /dev/null
+++ b/crates/utopia-store/tests/a_relation_points_only_inside_its_own_kb.rs
@@ -0,0 +1,340 @@
+//! `inverseOf` / `subPropertyOf` 的落库与边界——打在真库上。
+//!
+//! **这里守的第一条是知识库隔离。** 列上的外键写的是
+//! `REFERENCES relation_types(id)`,它不认 `kb_id`:数据库层面,A 库的关系
+//! 完全可以指向 B 库的关系。RDF 导入那条路天然过不去(按 IRI 在本库里查),
+//! 而 HTTP 接口收的是裸 UUID——挡不住的话,拿到任意一个 id 就能让推理机
+//! 跨库读公理,推出来的边会带着另一个库的语义落进这个库。
+//!
+//! 前端只列本库的关系。**那是界面礼貌,不是边界**:接口自己收 UUID,
+//! curl 一下就绕过去了。所以校验必须在 store 层,测试也必须在这里。
+//!
+//! 其余三条是同一族的形状约束:属性没有逆(宾语是字面值,无从谈起)、
+//! 属性不能当别人的逆、子属性不能是自己(库里有 CHECK,但撞上去是 500,
+//! 得在到达 CHECK 之前给出人话)。
+
+use sqlx::PgPool;
+use utopia_core::models::RelationAxioms;
+use uuid::Uuid;
+
+/// 一个 org 底下两个库。**两个是必需的**——这组测试的主角就是跨库那条线。
+async fn two_kbs(pool: &PgPool) -> anyhow::Result<(Uuid, Uuid, Uuid)> {
+ let (org, ws, a, b) = (
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ );
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'link-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'link-test')")
+ .bind(ws)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ for (id, name) in [(a, "link-a"), (b, "link-b")] {
+ sqlx::query("INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, $3)")
+ .bind(id)
+ .bind(ws)
+ .bind(name)
+ .execute(pool)
+ .await?;
+ }
+ Ok((org, a, b))
+}
+
+/// 建一条最普通的关系,不带任何链。
+async fn plain(pool: &PgPool, kb: Uuid, key: &str) -> anyhow::Result<Uuid> {
+ Ok(utopia_store::ontology::create_relation_type(
+ pool,
+ kb,
+ key,
+ key,
+ "state",
+ RelationAxioms::default(),
+ "",
+ "relation",
+ &[],
+ &[],
+ None,
+ None,
+ )
+ .await?)
+}
+
+#[tokio::test]
+async fn a_relation_points_only_inside_its_own_kb() -> anyhow::Result<()> {
+ let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {
+ eprintln!("跳过:未设 UTOPIA_DATABASE_URL");
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let (org, kb_a, kb_b) = two_kbs(&pool).await?;
+
+ let run = async {
+ let works_at = plain(&pool, kb_a, "works_at").await?;
+ let employs = plain(&pool, kb_a, "employs").await?;
+ let ceo_of = plain(&pool, kb_a, "ceo_of").await?;
+ // 另一个库里的关系。名字取一样的——**同名不同库,正是最容易被当成
+ // 自己人的那种**
+ let foreign = plain(&pool, kb_b, "employs").await?;
+
+ // ---- 一、跨库指向:建的时候就该被拒
+ let err = utopia_store::ontology::create_relation_type(
+ &pool,
+ kb_a,
+ "leaks",
+ "leaks",
+ "state",
+ RelationAxioms {
+ inverse_of: Some(foreign),
+ ..Default::default()
+ },
+ "",
+ "relation",
+ &[],
+ &[],
+ None,
+ None,
+ )
+ .await
+ .expect_err("指向别的知识库的关系必须被拒");
+ assert!(
+ format!("{err:?}").contains("unknown_relation"),
+ "**拒绝的理由不能透露那个 id 存在于别处**——不区分「不存在」\
+ 与「在别的库」,实得 {err:?}"
+ );
+ let leaked: i64 =
+ sqlx::query_scalar("SELECT count(*) FROM relation_types WHERE kb_id = $1 AND key = $2")
+ .bind(kb_a)
+ .bind("leaks")
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(leaked, 0, "被拒的那次不该留下半行");
+
+ // ---- 二、跨库指向:改的时候同样该被拒
+ let err = utopia_store::ontology::update_relation_type(
+ &pool,
+ kb_a,
+ works_at,
+ "works at",
+ "state",
+ RelationAxioms {
+ sub_property_of: Some(foreign),
+ ..Default::default()
+ },
+ "",
+ None,
+ None,
+ None,
+ None,
+ )
+ .await
+ .expect_err("改成指向别的知识库同样必须被拒");
+ assert!(
+ format!("{err:?}").contains("unknown_relation"),
+ "实得 {err:?}"
+ );
+
+ // ---- 三、本库之内:写得进,也读得回
+ utopia_store::ontology::update_relation_type(
+ &pool,
+ kb_a,
+ works_at,
+ "works at",
+ "state",
+ RelationAxioms {
+ inverse_of: Some(employs),
+ ..Default::default()
+ },
+ "",
+ None,
+ None,
+ None,
+ None,
+ )
+ .await?;
+ utopia_store::ontology::update_relation_type(
+ &pool,
+ kb_a,
+ ceo_of,
+ "ceo of",
+ "state",
+ RelationAxioms {
+ sub_property_of: Some(works_at),
+ ..Default::default()
+ },
+ "",
+ None,
+ None,
+ None,
+ None,
+ )
+ .await?;
+ let views = utopia_store::ontology::relation_type_views(&pool, kb_a).await?;
+ let find = |id: Uuid| views.iter().find(|v| v.id == id).expect("落库");
+ assert_eq!(
+ find(works_at).inverse_of,
+ Some(employs),
+ "**视图必须回这两个值**——下拉框要显示当前选的是谁,\
+ 读不回来的话打开表单是空的,保存一次就把声明抹了"
+ );
+ assert_eq!(find(ceo_of).sub_property_of, Some(works_at));
+
+ // ---- 四、缺省 = 清空,与上面六位公理同一条规矩
+ utopia_store::ontology::update_relation_type(
+ &pool,
+ kb_a,
+ works_at,
+ "works at",
+ "state",
+ RelationAxioms::default(),
+ "",
+ None,
+ None,
+ None,
+ None,
+ )
+ .await?;
+ let views = utopia_store::ontology::relation_type_views(&pool, kb_a).await?;
+ assert_eq!(
+ views.iter().find(|v| v.id == works_at).unwrap().inverse_of,
+ None,
+ "不传 = 清空。一半覆盖一半保留,会让「我把逆去掉了」\
+ 和「我没碰逆」长得一模一样"
+ );
+
+ // ---- 五、属性:不能有链,也不能当链的目标
+ let salary = utopia_store::ontology::create_relation_type(
+ &pool,
+ kb_a,
+ "salary",
+ "salary",
+ "state",
+ RelationAxioms::default(),
+ "",
+ "attribute",
+ // 属性至少要挂一个类,这里借用一个现成的类
+ &[class(&pool, kb_a).await?],
+ &[],
+ Some("number"),
+ None,
+ )
+ .await?;
+ let err = utopia_store::ontology::update_relation_type(
+ &pool,
+ kb_a,
+ ceo_of,
+ "ceo of",
+ "state",
+ RelationAxioms {
+ inverse_of: Some(salary),
+ ..Default::default()
+ },
+ "",
+ None,
+ None,
+ None,
+ None,
+ )
+ .await
+ .expect_err("属性不能当逆——它的宾语是字面值,反过来指回来无从谈起");
+ assert!(
+ format!("{err:?}").contains("link_target_is_attr"),
+ "实得 {err:?}"
+ );
+ let err = utopia_store::ontology::update_relation_type(
+ &pool,
+ kb_a,
+ salary,
+ "salary",
+ "state",
+ RelationAxioms {
+ sub_property_of: Some(ceo_of),
+ ..Default::default()
+ },
+ "",
+ None,
+ None,
+ None,
+ None,
+ )
+ .await
+ .expect_err("属性自己也不能有父属性");
+ assert!(
+ format!("{err:?}").contains("attr_has_no_link"),
+ "实得 {err:?}"
+ );
+
+ // ---- 六、子属性不能是自己。**库里有 CHECK,但那是 500**
+ let err = utopia_store::ontology::update_relation_type(
+ &pool,
+ kb_a,
+ ceo_of,
+ "ceo of",
+ "state",
+ RelationAxioms {
+ sub_property_of: Some(ceo_of),
+ ..Default::default()
+ },
+ "",
+ None,
+ None,
+ None,
+ None,
+ )
+ .await
+ .expect_err("自己不能是自己的父属性");
+ assert!(
+ format!("{err:?}").contains("sub_property_self"),
+ "得在撞上 CHECK 之前给出人话,而不是让人看到一个 500,实得 {err:?}"
+ );
+
+ // 逆是自己**不拦**:那等于 symmetric,是合法声明。
+ // R0 会提示改用 `symmetric` 更直白,但那是提示不是错误
+ utopia_store::ontology::update_relation_type(
+ &pool,
+ kb_a,
+ employs,
+ "employs",
+ "state",
+ RelationAxioms {
+ inverse_of: Some(employs),
+ ..Default::default()
+ },
+ "",
+ None,
+ None,
+ None,
+ None,
+ )
+ .await?;
+
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(org)
+ .execute(&pool)
+ .await?;
+ let _ = kb_b;
+ run
+}
+
+/// 借一个类给属性当 domain——属性没有类就建不出来。
+async fn class(pool: &PgPool, kb: Uuid) -> anyhow::Result<Uuid> {
+ Ok(utopia_store::ontology::create_entity_type(
+ pool,
+ kb,
+ "person",
+ "Person",
+ "#888888",
+ "circle",
+ &[],
+ "",
+ )
+ .await?)
+}
diff --git a/migrations/0016_a_relation_can_name_its_inverse.sql b/migrations/0016_a_relation_can_name_its_inverse.sql
new file mode 100644
index 00000000..06e91d5b
--- /dev/null
+++ b/migrations/0016_a_relation_can_name_its_inverse.sql
@@ -0,0 +1,52 @@
+-- 关系的逆与父属性(R1 的后两种规则源,见 docs/decisions/0002)。
+--
+-- ADR 0002 给 R1 定的规则来源是四种:`TransitiveProperty` / `SymmetricProperty` /
+-- `inverseOf` / `subPropertyOf`。前两种一直在跑,后两种**连列都没有**——
+-- 0013 的 `rules.kind` 注释把这件事记下来了:
+--
+-- > `inverseOf` 与 `subPropertyOf` 投影侧还没落库,所以也就编不出来
+--
+-- 这条迁移补上投影侧。缺的后果不是「少推几条」,是**答案不对称**:本体声明了
+-- `works_at⁻¹ = employs`,而问「谁在 Acme 工作」和「Acme 雇了谁」会得到不同答案,
+-- 除非两个方向都被断言过——那正是 R1 该消灭的重复劳动。
+ALTER TABLE relation_types
+ -- `p⁻¹ = q`。**单向存,双向用。**
+ --
+ -- 不加触发器去自动回填 `q.inverse_of = p`:那会把一条语义规则藏进数据库,
+ -- 而绕过它的路不止一条(RDF 导入、直接 SQL)。改在读取公理时归一化——
+ -- 载入那一处认这件事,绕不过去,也测得动(`reasoning::axioms_of`)。
+ ADD COLUMN inverse_of UUID REFERENCES relation_types(id) ON DELETE SET NULL,
+ -- `p ⊑ q`:断言了具体的,通用的也成立(`ceo_of ⊑ works_at`)。
+ -- 链要防成环,R0 那边加检查——与 `entity_types` 的父类环是同一类问题
+ ADD COLUMN sub_property_of UUID REFERENCES relation_types(id) ON DELETE SET NULL;
+
+-- 自己不能是自己的父属性。**自己可以是自己的逆**——那等于对称,
+-- 是合法的声明(R0 会提示改用 `symmetric` 更直白,但不算错)
+ALTER TABLE relation_types
+ ADD CONSTRAINT relation_types_sub_property_not_self
+ CHECK (sub_property_of IS NULL OR sub_property_of <> id);
+
+-- 归一化要按「谁指着我」反查,编译规则时每个谓词问一次
+CREATE INDEX relation_types_inverse_idx ON relation_types (inverse_of)
+ WHERE inverse_of IS NOT NULL;
+CREATE INDEX relation_types_sub_property_idx ON relation_types (sub_property_of)
+ WHERE sub_property_of IS NOT NULL;
+
+-- 两处 CHECK 跟着放开:新规则与新缺陷都是 0013 那两张表没预见到的取值。
+--
+-- **不是补漏,是那时确实还没有。** 0013 的注释写着「`inverseOf` 与
+-- `subPropertyOf` 投影侧还没落库,所以也就编不出来」——这条迁移补上投影侧,
+-- 约束自然要跟着扩。
+ALTER TABLE rules DROP CONSTRAINT IF EXISTS rules_kind_check;
+ALTER TABLE rules ADD CONSTRAINT rules_kind_check
+ CHECK (kind IN ('transitive', 'symmetric', 'inverse', 'sub_property'));
+
+-- 三条新的本体自检:自己是自己的逆(等于 symmetric,提示改写)、
+-- 逆没指回来(载入时只补空缺不覆盖,所以矛盾留到这里报)、子属性成环
+ALTER TABLE ontology_defects DROP CONSTRAINT IF EXISTS ontology_defects_kind_check;
+ALTER TABLE ontology_defects ADD CONSTRAINT ontology_defects_kind_check
+ CHECK (kind IN (
+ 'symmetric_and_asymmetric', 'transitive_and_functional',
+ 'subclass_cycle', 'disjoint_with_ancestor', 'inherits_disjoint',
+ 'inverse_of_itself', 'inverse_not_mutual', 'sub_property_cycle'
+ ));