Changesets · Branches · Tags · Compare
| Changeset | 056185cb340ecdb078bcd3823a8ba3388cf2c1162576af5a112d6f5ad0ca5fc2 |
|---|---|
| Author | WaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-09-02 17:04 +08:00 |
| Committer | GitHub <noreply@github.com> · 2026-09-02 17:04 +08:00 |
| Parents | f54c9bcf46f3 |
12 files changed
modified crates/utopia-core/src/models.rs +35 −1
| @@ -328,6 +328,10 @@ | ||
| 328 | 328 | pub is_symmetric: bool, |
| 329 | 329 | pub is_asymmetric: bool, |
| 330 | 330 | pub is_irreflexive: bool, |
| 331 | + /// 指向另一个关系的两条。**必须回给界面**——下拉框要显示当前选的是谁, | |
| 332 | + /// 否则每次打开表单都是空的,编辑一次就把已声明的抹掉了 | |
| 333 | + pub inverse_of: Option<Uuid>, | |
| 334 | + pub sub_property_of: Option<Uuid>, | |
| 331 | 335 | pub builtin: bool, |
| 332 | 336 | pub description: String, |
| 333 | 337 | /// relation(宾语是实体)| attribute(宾语是字面值) |
| @@ -936,9 +940,13 @@ | ||
| 936 | 940 | |
| 937 | 941 | /// 一个关系声明了哪些 OWL 公理。 |
| 938 | 942 | /// |
| 939 | -/// **六位打包成一个东西传,不是六个参数。** 它们本来就是同一族——推理机 | |
| 943 | +/// **打包成一个东西传,不是一串参数。** 它们本来就是同一族——推理机 | |
| 940 | 944 | /// (0002)拿它们当判据,界面上也该并排出现;散成参数表里的六个 bool, |
| 941 | 945 | /// 调用点迟早传错顺序,而 `bool` 之间编译器帮不上忙。 |
| 946 | +/// | |
| 947 | +/// 后两位不是 bool:`inverseOf` 与 `subPropertyOf` 指向**另一个关系**, | |
| 948 | +/// 界面上是下拉框而不是复选框。形状不同不改变它们属于这一族——推理机 | |
| 949 | +/// 的四种规则源正是这六位里的两条加上这两条(0002)。 | |
| 942 | 950 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] |
| 943 | 951 | pub struct RelationAxioms { |
| 944 | 952 | /// 主语侧唯一(一个人一个出生地) |
| @@ -953,6 +961,11 @@ | ||
| 953 | 961 | pub asymmetric: bool, |
| 954 | 962 | /// 不存在 A→A |
| 955 | 963 | pub irreflexive: bool, |
| 964 | + /// `p⁻¹ = q`:`A p B ⟹ B q A`。**单向存,双向用**——载入公理时归一化 | |
| 965 | + /// (`reasoning::axioms`),所以只需在一侧声明,反向那条自动成立 | |
| 966 | + pub inverse_of: Option<Uuid>, | |
| 967 | + /// `p ⊑ q`:`A p B ⟹ A q B`。断言了具体的,通用的也成立 | |
| 968 | + pub sub_property_of: Option<Uuid>, | |
| 956 | 969 | } |
| 957 | 970 | |
| 958 | 971 | /// 文库的一页,连同这一页之外的统计。 |
| @@ -968,3 +981,24 @@ | ||
| 968 | 981 | pub extracting: i64, |
| 969 | 982 | pub failed: i64, |
| 970 | 983 | } |
| 984 | + | |
| 985 | +/// 一枚个人访问令牌的元信息(0014)。**永远不含明文**—— | |
| 986 | +/// 明文只在 `tokens::issue` 返回的那一次存在,库里只有哈希。 | |
| 987 | +#[derive(Debug, Clone, Serialize, sqlx::FromRow)] | |
| 988 | +pub struct TokenView { | |
| 989 | + pub id: Uuid, | |
| 990 | + pub name: String, | |
| 991 | + /// 给人认的那一小截(`utp_pat_ab12`)。够对上配置文件里那一串, | |
| 992 | + /// 又不足以复原 | |
| 993 | + pub token_prefix: String, | |
| 994 | + /// read | write。**上限不是授权**:有效权限 = 这个人的角色 ∩ 这个 scope | |
| 995 | + pub scope: String, | |
| 996 | + /// None = 这个人能进的全部库 | |
| 997 | + pub kb_ids: Option<Vec<Uuid>>, | |
| 998 | + pub expires_at: Option<DateTime<Utc>>, | |
| 999 | + /// 「这把还在用吗」。撤之前要答得出,否则没人敢撤 | |
| 1000 | + pub last_used_at: Option<DateTime<Utc>>, | |
| 1001 | + /// **撤销打戳不删行**:撤过这件事本身要留痕 | |
| 1002 | + pub revoked_at: Option<DateTime<Utc>>, | |
| 1003 | + pub created_at: DateTime<Utc>, | |
| 1004 | +} |
modified crates/utopia-ingest/src/ontology_rdf.rs +71 −0
| @@ -43,6 +43,13 @@ | ||
| 43 | 43 | pub symmetric: bool, |
| 44 | 44 | pub asymmetric: bool, |
| 45 | 45 | pub irreflexive: bool, |
| 46 | + /// `owl:inverseOf` 的对端 IRI。**只按写的方向收**——归一化(补上反向) | |
| 47 | + /// 在读取公理时做(`reasoning::axioms`),那里绕不过去; | |
| 48 | + /// 在这里补会让「本体自己写了什么」和「我们推出来的」分不开 | |
| 49 | + pub inverse_of: Option<String>, | |
| 50 | + /// `rdfs:subPropertyOf` 的父属性 IRI。多写几条只留第一条—— | |
| 51 | + /// OWL 允许多父,而 R1 的规则一次只升一级,多父要另一套形状 | |
| 52 | + pub sub_property_of: Option<String>, | |
| 46 | 53 | pub domains: Vec<String>, |
| 47 | 54 | pub ranges: Vec<String>, |
| 48 | 55 | /// **多条 range 是并集还是交集**。`rdfs:range` 写多条是交集 |
| @@ -219,6 +226,9 @@ | ||
| 219 | 226 | let mut inverse_functional: BTreeSet<String> = BTreeSet::new(); |
| 220 | 227 | let mut transitive: BTreeSet<String> = BTreeSet::new(); |
| 221 | 228 | let mut symmetric: BTreeSet<String> = BTreeSet::new(); |
| 229 | + // 属性之间的两条关系(不是类型声明,所以单独收) | |
| 230 | + let mut inverse_of: BTreeMap<String, String> = BTreeMap::new(); | |
| 231 | + let mut sub_property_of: BTreeMap<String, String> = BTreeMap::new(); | |
| 222 | 232 | let mut asymmetric: BTreeSet<String> = BTreeSet::new(); |
| 223 | 233 | let mut irreflexive: BTreeSet<String> = BTreeSet::new(); |
| 224 | 234 | let mut plain_props: BTreeSet<String> = BTreeSet::new(); |
| @@ -304,6 +314,7 @@ | ||
| 304 | 314 | || is_schema(p, "domainIncludes") |
| 305 | 315 | || is_schema(p, "rangeIncludes") |
| 306 | 316 | || p == format!("{OWL}disjointWith") |
| 317 | + || p == format!("{OWL}inverseOf") | |
| 307 | 318 | }; |
| 308 | 319 | for t in &triples { |
| 309 | 320 | let p = t.predicate.as_str(); |
| @@ -332,6 +343,23 @@ | ||
| 332 | 343 | .or_default() |
| 333 | 344 | .push(t.subject.clone()); |
| 334 | 345 | } |
| 346 | + } else if p == format!("{OWL}inverseOf") { | |
| 347 | + // **只按写的方向收。** OWL 里 `p owl:inverseOf q` 蕴含反向, | |
| 348 | + // 而词表通常只写一遍。补反向是在读取公理时做的 | |
| 349 | + //(`reasoning::axioms`,那一处绕不过去)——在这里补会让 | |
| 350 | + // 「本体自己写了什么」和「我们推出来的」分不开,而 R0 有一条 | |
| 351 | + // `inverse_not_mutual` 检查恰恰要区分这两者 | |
| 352 | + if let Some(o) = &t.object_iri { | |
| 353 | + inverse_of.entry(t.subject.clone()).or_insert(o.clone()); | |
| 354 | + } | |
| 355 | + } else if p == format!("{RDFS}subPropertyOf") { | |
| 356 | + // 从前这条只出现在 `known()` 白名单里——认得出、不报警、**然后扔掉**。 | |
| 357 | + // 导一份带 subPropertyOf 的本体进来,那部分信息当场消失且没有提示 | |
| 358 | + if let Some(o) = &t.object_iri { | |
| 359 | + sub_property_of | |
| 360 | + .entry(t.subject.clone()) | |
| 361 | + .or_insert(o.clone()); | |
| 362 | + } | |
| 335 | 363 | } else if p == format!("{RDFS}subClassOf") { |
| 336 | 364 | if let Some(o) = &t.object_iri { |
| 337 | 365 | parents |
| @@ -450,6 +478,8 @@ | ||
| 450 | 478 | transitive: transitive.contains(iri), |
| 451 | 479 | symmetric: symmetric.contains(iri), |
| 452 | 480 | asymmetric: asymmetric.contains(iri), |
| 481 | + inverse_of: inverse_of.get(iri).cloned(), | |
| 482 | + sub_property_of: sub_property_of.get(iri).cloned(), | |
| 453 | 483 | irreflexive: irreflexive.contains(iri), |
| 454 | 484 | domains: domains.get(iri).cloned().unwrap_or_default(), |
| 455 | 485 | ranges: rs, |
| @@ -1249,3 +1279,44 @@ | ||
| 1249 | 1279 | ); |
| 1250 | 1280 | } |
| 1251 | 1281 | } |
| 1282 | + | |
| 1283 | +#[cfg(test)] | |
| 1284 | +mod property_axiom_tests { | |
| 1285 | + use super::*; | |
| 1286 | + | |
| 1287 | + /// `owl:inverseOf` 与 `rdfs:subPropertyOf` 要被读出来。 | |
| 1288 | + /// | |
| 1289 | + /// 从前 `subPropertyOf` 只出现在 `known()` 白名单里——认得出、不报警、 | |
| 1290 | + /// **然后扔掉**;`inverseOf` 连白名单都没进,被算进「暂未投影」。 | |
| 1291 | + /// 两种都是导一份本体进来,那部分信息当场消失。 | |
| 1292 | + #[test] | |
| 1293 | + fn the_two_property_relations_survive_projection() { | |
| 1294 | + let ttl = include_str!("../tests/inverse_and_sub.ttl"); | |
| 1295 | + let p = project(ttl.as_bytes(), RdfFormat::Turtle).expect("解析"); | |
| 1296 | + let by = |k: &str| { | |
| 1297 | + p.properties | |
| 1298 | + .iter() | |
| 1299 | + .find(|x| x.key == k) | |
| 1300 | + .unwrap_or_else(|| panic!("没有 {k}")) | |
| 1301 | + }; | |
| 1302 | + assert_eq!( | |
| 1303 | + by("employs").inverse_of.as_deref(), | |
| 1304 | + Some("http://example.org/worksAt"), | |
| 1305 | + "**逆要按写的方向收**——补反向是读取公理时的事" | |
| 1306 | + ); | |
| 1307 | + assert_eq!( | |
| 1308 | + by("ceo_of").sub_property_of.as_deref(), | |
| 1309 | + Some("http://example.org/worksAt") | |
| 1310 | + ); | |
| 1311 | + // 反方向没写,就该是空的:本体写了什么与我们推了什么要分得开, | |
| 1312 | + // R0 的 inverse_not_mutual 检查靠这个区分 | |
| 1313 | + assert!( | |
| 1314 | + by("works_at").inverse_of.is_none(), | |
| 1315 | + "没写的方向不该在导入时被补上" | |
| 1316 | + ); | |
| 1317 | + assert!( | |
| 1318 | + !p.unprojected.keys().any(|k| k.contains("inverseOf")), | |
| 1319 | + "**认了就不该再算进「暂未投影」**" | |
| 1320 | + ); | |
| 1321 | + } | |
| 1322 | +} |
added crates/utopia-ingest/tests/inverse_and_sub.ttl +20 −0
| @@ -0,0 +1,20 @@ | ||
| 1 | +@prefix owl: <http://www.w3.org/2002/07/owl#> . | |
| 2 | +@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . | |
| 3 | +@prefix ex: <http://example.org/> . | |
| 4 | + | |
| 5 | +ex:Person a owl:Class ; rdfs:label "Person" ; rdfs:comment "A human being." . | |
| 6 | +ex:Org a owl:Class ; rdfs:label "Organization" ; rdfs:comment "A company." . | |
| 7 | + | |
| 8 | +ex:worksAt a owl:ObjectProperty ; | |
| 9 | + rdfs:label "works at" ; rdfs:comment "Employment." ; | |
| 10 | + rdfs:domain ex:Person ; rdfs:range ex:Org . | |
| 11 | + | |
| 12 | +ex:employs a owl:ObjectProperty ; | |
| 13 | + rdfs:label "employs" ; rdfs:comment "The other direction." ; | |
| 14 | + rdfs:domain ex:Org ; rdfs:range ex:Person ; | |
| 15 | + owl:inverseOf ex:worksAt . | |
| 16 | + | |
| 17 | +ex:ceoOf a owl:ObjectProperty ; | |
| 18 | + rdfs:label "CEO of" ; rdfs:comment "Chief executive." ; | |
| 19 | + rdfs:domain ex:Person ; rdfs:range ex:Org ; | |
| 20 | + rdfs:subPropertyOf ex:worksAt . |
modified crates/utopia-reason/src/derive.rs +427 −132
| @@ -37,6 +37,11 @@ | ||
| 37 | 37 | Transitive, |
| 38 | 38 | /// `A p B` ⟹ `B p A` |
| 39 | 39 | Symmetric, |
| 40 | + /// `A p B` ∧ `p⁻¹ = q` ⟹ `B q A`。**主宾对调且换谓词**—— | |
| 41 | + /// 两件事一起发生,只做一件是这条规则最容易写错的地方 | |
| 42 | + Inverse, | |
| 43 | + /// `A p B` ∧ `p ⊑ q` ⟹ `A q B`。主宾不动,只升谓词 | |
| 44 | + SubProperty, | |
| 40 | 45 | } |
| 41 | 46 | |
| 42 | 47 | impl Rule { |
| @@ -44,6 +49,8 @@ | ||
| 44 | 49 | match self { |
| 45 | 50 | Rule::Transitive => "transitive", |
| 46 | 51 | Rule::Symmetric => "symmetric", |
| 52 | + Rule::Inverse => "inverse", | |
| 53 | + Rule::SubProperty => "sub_property", | |
| 47 | 54 | } |
| 48 | 55 | } |
| 49 | 56 | } |
| @@ -52,6 +59,16 @@ | ||
| 52 | 59 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 53 | 60 | pub struct Derived { |
| 54 | 61 | pub predicate: Uuid, |
| 62 | + /// **哪个谓词的声明触发了它。** | |
| 63 | + /// | |
| 64 | + /// 传递与对称不换谓词,`via == predicate`;而 `inverseOf` 与 | |
| 65 | + /// `subPropertyOf` 换——`ceo_of ⊑ works_at` 推出的事实谓词是 `works_at`, | |
| 66 | + /// 而声明写在 `ceo_of` 上。 | |
| 67 | + /// | |
| 68 | + /// 落库时按 `via` 找规则行。**这里踩过一次**:原先按 `predicate` 找, | |
| 69 | + /// 前两条规则一直对(两者相同),加了跨谓词的两条之后查不到规则, | |
| 70 | + /// 于是 `continue` 静默丢弃——推出来了却不落库,最难查的那一种。 | |
| 71 | + pub via: Uuid, | |
| 55 | 72 | pub subject: Uuid, |
| 56 | 73 | pub object: Uuid, |
| 57 | 74 | pub rule: Rule, |
| @@ -117,171 +134,232 @@ | ||
| 117 | 134 | premises: Vec<Uuid>, |
| 118 | 135 | } |
| 119 | 136 | |
| 137 | +/// 一条三元组的身份:(谓词, 主语, 宾语)。 | |
| 138 | +/// | |
| 139 | +/// **谓词进了 key,这是这一版最要紧的改动。** 从前推导按谓词分组、组内自成一体, | |
| 140 | +/// 因为传递与对称都不换谓词;而 `inverseOf` 与 `subPropertyOf` 天生跨谓词—— | |
| 141 | +/// `A works_at B` 推出的是 `B employs A`,落在另一个谓词上。分组一做,这两条 | |
| 142 | +/// 规则就无处安放。 | |
| 143 | +type Triple = (Uuid, Uuid, Uuid); | |
| 144 | + | |
| 120 | 145 | /// 拿公理推一遍这批边。 |
| 146 | +/// | |
| 147 | +/// **全局不动点,不再按谓词分组。** 三条规则会串起来: | |
| 148 | +/// | |
| 149 | +/// ```text | |
| 150 | +/// A ceo_of B --(subPropertyOf)--> A works_at B --(inverseOf)--> B employs A | |
| 151 | +/// ``` | |
| 152 | +/// | |
| 153 | +/// 各谓词各算各的话,这条链在第一步就断了。所以改成半朴素求值扫全集:每一轮拿上 | |
| 154 | +/// 一轮的新边(frontier)再推一遍,没有新增就停。 | |
| 155 | +/// | |
| 156 | +/// 三条一跳规则(对称/逆/子属性)与传递放在同一轮里,因为它们互为输入—— | |
| 157 | +/// 逆推出来的边可能让某条传递链接得上,反之亦然。 | |
| 121 | 158 | pub fn derive(edges: &[TimedEdge], axioms: &HashMap<Uuid, Axioms>) -> Derivation { |
| 122 | 159 | let mut out = Derivation::default(); |
| 123 | - let mut by_pred: HashMap<Uuid, Vec<TimedEdge>> = HashMap::new(); | |
| 124 | - for e in edges { | |
| 125 | - let Some(ax) = axioms.get(&e.edge.predicate) else { | |
| 126 | - continue; | |
| 127 | - }; | |
| 128 | - if !ax.transitive && !ax.symmetric { | |
| 129 | - continue; | |
| 130 | - } | |
| 131 | - by_pred.entry(e.edge.predicate).or_default().push(*e); | |
| 132 | - } | |
| 133 | - // 谓词按 id 排序:同一个库两次推导该给出同一份结果 | |
| 134 | - let mut preds: Vec<Uuid> = by_pred.keys().copied().collect(); | |
| 135 | - preds.sort(); | |
| 136 | - for pred in preds { | |
| 137 | - let group = &by_pred[&pred]; | |
| 138 | - let ax = axioms[&pred]; | |
| 139 | - one_predicate(pred, group, ax, &mut out); | |
| 140 | - } | |
| 141 | - out | |
| 142 | -} | |
| 143 | 160 | |
| 144 | -fn one_predicate(pred: Uuid, group: &[TimedEdge], ax: Axioms, out: &mut Derivation) { | |
| 145 | 161 | // 断言过的三元组。**派生撞上它就让路**——asserted > derived 是硬性的 |
| 146 | - let asserted: HashSet<(Uuid, Uuid)> = group | |
| 162 | + let asserted: HashSet<Triple> = edges | |
| 147 | 163 | .iter() |
| 148 | - .map(|e| (e.edge.subject, e.edge.object)) | |
| 164 | + .map(|e| (e.edge.predicate, e.edge.subject, e.edge.object)) | |
| 149 | 165 | .collect(); |
| 150 | 166 | |
| 151 | - // 已经推出来的 (主, 宾) → 怎么来的。同一对只留第一条证明: | |
| 152 | - // 多条路径都能推出同一件事时,展示哪一条对用户没有区别,而全存下来 | |
| 153 | - // 会让证明树的规模跟着路径数走 | |
| 154 | - let mut reached: HashMap<(Uuid, Uuid), Reached> = HashMap::new(); | |
| 155 | - let mut emitted: Vec<Derived> = Vec::new(); | |
| 156 | - let mut capped = false; | |
| 157 | - | |
| 158 | - // ---- 对称:一跳就够,不进迭代 | |
| 159 | - if ax.symmetric { | |
| 160 | - for e in group { | |
| 161 | - let pair = (e.edge.object, e.edge.subject); | |
| 162 | - if pair.0 == pair.1 || asserted.contains(&pair) || reached.contains_key(&pair) { | |
| 163 | - continue; | |
| 164 | - } | |
| 165 | - reached.insert( | |
| 166 | - pair, | |
| 167 | + // 已经推出来的 → 怎么来的。同一条只留第一条证明:多条路径都能推出同一件事 | |
| 168 | + // 时,展示哪一条对用户没有区别,而全存下来会让证明树的规模跟着路径数走 | |
| 169 | + let mut reached: HashMap<Triple, Reached> = HashMap::new(); | |
| 170 | + // **封顶仍按谓词计**:那个常量的含义没变(一个谓词最多推两万条), | |
| 171 | + // 而 `Derivation::capped` 回的也是谓词列表。跨谓词之后若改成全局一个数, | |
| 172 | + // 界面上「哪个谓词太密」就答不出来了 | |
| 173 | + let mut per_pred: HashMap<Uuid, usize> = HashMap::new(); | |
| 174 | + let mut capped: HashSet<Uuid> = HashSet::new(); | |
| 175 | + | |
| 176 | + // 从 (谓词, 主语) 出发能走的边,传递用。派生出来的也进来——它们已经是 | |
| 177 | + // 我们的断言了,链上不该因为「来路不同」断掉 | |
| 178 | + let mut adj: HashMap<(Uuid, Uuid), Vec<Hop>> = HashMap::new(); | |
| 179 | + for e in edges { | |
| 180 | + adj.entry((e.edge.predicate, e.edge.subject)) | |
| 181 | + .or_default() | |
| 182 | + .push((e.edge.object, e.from, e.to, e.edge.fact)); | |
| 183 | + } | |
| 184 | + | |
| 185 | + let mut frontier: Vec<(Triple, Reached)> = edges | |
| 186 | + .iter() | |
| 187 | + .map(|e| { | |
| 188 | + ( | |
| 189 | + (e.edge.predicate, e.edge.subject, e.edge.object), | |
| 167 | 190 | Reached { |
| 168 | 191 | from: e.from, |
| 169 | 192 | to: e.to, |
| 170 | 193 | premises: vec![e.edge.fact], |
| 171 | 194 | }, |
| 172 | - ); | |
| 173 | - emitted.push(Derived { | |
| 174 | - predicate: pred, | |
| 175 | - subject: pair.0, | |
| 176 | - object: pair.1, | |
| 177 | - rule: Rule::Symmetric, | |
| 178 | - premises: vec![e.edge.fact], | |
| 179 | - }); | |
| 180 | - } | |
| 181 | - } | |
| 195 | + ) | |
| 196 | + }) | |
| 197 | + .collect(); | |
| 198 | + // 起始 frontier 的顺序跟着入参走,而入参顺序不保证——排一次, | |
| 199 | + // 同一个库两次推导才给得出同一份结果 | |
| 200 | + frontier.sort_by_key(|(t, _)| *t); | |
| 182 | 201 | |
| 183 | - // ---- 传递:半朴素求值。frontier 是上一轮新产生的,只有它需要再往下接 | |
| 184 | - if ax.transitive { | |
| 185 | - // 从主语出发能走的边。对称推出来的那些也算基础事实——它们已经是我们 | |
| 186 | - // 的断言了,链上不该因为「来路不同」断掉 | |
| 187 | - let mut base: HashMap<Uuid, Vec<Hop>> = HashMap::new(); | |
| 188 | - for e in group { | |
| 189 | - base.entry(e.edge.subject).or_default().push(( | |
| 190 | - e.edge.object, | |
| 191 | - e.from, | |
| 192 | - e.to, | |
| 193 | - e.edge.fact, | |
| 194 | - )); | |
| 195 | - } | |
| 196 | - for ((s, o), r) in reached.iter() { | |
| 197 | - if let Some(&p) = r.premises.first() { | |
| 198 | - base.entry(*s).or_default().push((*o, r.from, r.to, p)); | |
| 199 | - } | |
| 202 | + // 轮数上限是**兜底**,真正的界在下面那条 `premises.len() >= MAX_DEPTH`: | |
| 203 | + // 常量的含义是「路径最长 12」,按前提条数算才对得上。轮数只防病态输入 | |
| 204 | + for _ in 0..MAX_DEPTH { | |
| 205 | + if frontier.is_empty() { | |
| 206 | + break; | |
| 200 | 207 | } |
| 208 | + let mut next: Vec<(Triple, Reached)> = Vec::new(); | |
| 201 | 209 | |
| 202 | - let mut frontier: Vec<((Uuid, Uuid), Reached)> = group | |
| 203 | - .iter() | |
| 204 | - .map(|e| { | |
| 205 | - ( | |
| 206 | - (e.edge.subject, e.edge.object), | |
| 207 | - Reached { | |
| 208 | - from: e.from, | |
| 209 | - to: e.to, | |
| 210 | - premises: vec![e.edge.fact], | |
| 211 | - }, | |
| 212 | - ) | |
| 213 | - }) | |
| 214 | - .collect(); | |
| 210 | + for (triple, acc) in frontier.drain(..) { | |
| 211 | + let (pred, subj, obj) = triple; | |
| 212 | + let Some(ax) = axioms.get(&pred) else { | |
| 213 | + continue; | |
| 214 | + }; | |
| 215 | + // 再接一条就超了:这一条不再往下延,但它自己已经产出过 | |
| 216 | + if acc.premises.len() >= MAX_DEPTH { | |
| 217 | + continue; | |
| 218 | + } | |
| 215 | 219 | |
| 216 | - // **`MAX_DEPTH - 1` 轮,不是 MAX_DEPTH 轮。** 起始 frontier 里每条已经 | |
| 217 | - // 带着一条前提,此后每轮加一条——跑满 MAX_DEPTH 轮会得到 13 条前提的 | |
| 218 | - // 证明,而那个常量在 R0 那边的含义是「路径最长 12」。两处得是同一个意思 | |
| 219 | - for _ in 0..MAX_DEPTH.saturating_sub(1) { | |
| 220 | - if frontier.is_empty() { | |
| 221 | - break; | |
| 220 | + // ---- 一跳的三条:换主宾(对称)、换谓词(逆 / 子属性) | |
| 221 | + let mut hops: Vec<(Triple, Rule)> = Vec::new(); | |
| 222 | + if ax.symmetric { | |
| 223 | + hops.push(((pred, obj, subj), Rule::Symmetric)); | |
| 224 | + } | |
| 225 | + if let Some(inv) = ax.inverse_of { | |
| 226 | + // `A p B ⟹ B p⁻¹ A`。主宾对调**且**谓词换掉——两件事一起发生, | |
| 227 | + // 只做一件是这条规则最容易写错的地方 | |
| 228 | + hops.push(((inv, obj, subj), Rule::Inverse)); | |
| 222 | 229 | } |
| 223 | - let mut next: Vec<((Uuid, Uuid), Reached)> = Vec::new(); | |
| 224 | - for ((a, b), acc) in frontier.drain(..) { | |
| 225 | - let Some(outs) = base.get(&b) else { | |
| 230 | + if let Some(sup) = ax.sub_property_of { | |
| 231 | + // `A p B ∧ p ⊑ q ⟹ A q B`。主宾不动,只升谓词 | |
| 232 | + hops.push(((sup, subj, obj), Rule::SubProperty)); | |
| 233 | + } | |
| 234 | + for (t, rule) in hops { | |
| 235 | + if emit( | |
| 236 | + t, | |
| 237 | + pred, | |
| 238 | + rule, | |
| 239 | + &acc, | |
| 240 | + acc.from, | |
| 241 | + acc.to, | |
| 242 | + None, | |
| 243 | + &asserted, | |
| 244 | + &mut reached, | |
| 245 | + &mut per_pred, | |
| 246 | + &mut capped, | |
| 247 | + &mut out, | |
| 248 | + &mut next, | |
| 249 | + &mut adj, | |
| 250 | + ) { | |
| 226 | 251 | continue; |
| 227 | - }; | |
| 228 | - for &(c, from, to, fact) in outs { | |
| 252 | + } | |
| 253 | + } | |
| 254 | + | |
| 255 | + // ---- 传递:需要接一条同谓词的出边 | |
| 256 | + if ax.transitive { | |
| 257 | + let outs = adj.get(&(pred, obj)).cloned().unwrap_or_default(); | |
| 258 | + for (c, from, to, fact) in outs { | |
| 229 | 259 | // **不推自环。** `A p A` 在一个传递+反对称的谓词上是矛盾 |
| 230 | 260 | // 而不是知识,R0 那边会把这个环连路径一起报出来 |
| 231 | - if a == c { | |
| 232 | - continue; | |
| 233 | - } | |
| 234 | - if asserted.contains(&(a, c)) || reached.contains_key(&(a, c)) { | |
| 261 | + if subj == c { | |
| 235 | 262 | continue; |
| 236 | 263 | } |
| 237 | 264 | let Some((nf, nt)) = overlap((acc.from, acc.to), (from, to)) else { |
| 238 | 265 | continue; |
| 239 | 266 | }; |
| 240 | - if emitted.len() >= MAX_DERIVED_PER_PREDICATE { | |
| 241 | - capped = true; | |
| 242 | - break; | |
| 243 | - } | |
| 244 | - let mut premises = acc.premises.clone(); | |
| 245 | - premises.push(fact); | |
| 246 | - reached.insert( | |
| 247 | - (a, c), | |
| 248 | - Reached { | |
| 249 | - from: nf, | |
| 250 | - to: nt, | |
| 251 | - premises: premises.clone(), | |
| 252 | - }, | |
| 267 | + emit( | |
| 268 | + (pred, subj, c), | |
| 269 | + pred, | |
| 270 | + Rule::Transitive, | |
| 271 | + &acc, | |
| 272 | + nf, | |
| 273 | + nt, | |
| 274 | + Some(fact), | |
| 275 | + &asserted, | |
| 276 | + &mut reached, | |
| 277 | + &mut per_pred, | |
| 278 | + &mut capped, | |
| 279 | + &mut out, | |
| 280 | + &mut next, | |
| 281 | + &mut adj, | |
| 253 | 282 | ); |
| 254 | - emitted.push(Derived { | |
| 255 | - predicate: pred, | |
| 256 | - subject: a, | |
| 257 | - object: c, | |
| 258 | - rule: Rule::Transitive, | |
| 259 | - premises: premises.clone(), | |
| 260 | - }); | |
| 261 | - next.push(( | |
| 262 | - (a, c), | |
| 263 | - Reached { | |
| 264 | - from: nf, | |
| 265 | - to: nt, | |
| 266 | - premises, | |
| 267 | - }, | |
| 268 | - )); | |
| 269 | - } | |
| 270 | - if capped { | |
| 271 | - break; | |
| 272 | 283 | } |
| 273 | 284 | } |
| 274 | - if capped { | |
| 275 | - break; | |
| 276 | - } | |
| 277 | - frontier = next; | |
| 278 | 285 | } |
| 286 | + next.sort_by_key(|(t, _)| *t); | |
| 287 | + frontier = next; | |
| 288 | + } | |
| 289 | + | |
| 290 | + let mut capped: Vec<Uuid> = capped.into_iter().collect(); | |
| 291 | + capped.sort(); | |
| 292 | + out.capped = capped; | |
| 293 | + out | |
| 294 | +} | |
| 295 | + | |
| 296 | +/// 落一条派生,并把它接进邻接表供后续传递使用。返回 true = 这个谓词封顶了。 | |
| 297 | +/// | |
| 298 | +/// 参数多得难看,但把它抽出来是必要的:四条规则各自的落地动作一模一样 | |
| 299 | +/// (查断言、查已推、算区间、记证明、进 frontier、进邻接表),而上一版 | |
| 300 | +/// 正是因为对称与传递各写一遍,两处的「跳过条件」慢慢长得不一样了。 | |
| 301 | +#[allow(clippy::too_many_arguments)] | |
| 302 | +fn emit( | |
| 303 | + t: Triple, | |
| 304 | + // 触发它的那个谓词的声明。四条规则都是「当前展开的这条边的谓词」 | |
| 305 | + via: Uuid, | |
| 306 | + rule: Rule, | |
| 307 | + acc: &Reached, | |
| 308 | + from: Option<i64>, | |
| 309 | + to: Option<i64>, | |
| 310 | + // 传递多用掉的那一条前提;一跳规则没有 | |
| 311 | + extra_premise: Option<Uuid>, | |
| 312 | + asserted: &HashSet<Triple>, | |
| 313 | + reached: &mut HashMap<Triple, Reached>, | |
| 314 | + per_pred: &mut HashMap<Uuid, usize>, | |
| 315 | + capped: &mut HashSet<Uuid>, | |
| 316 | + out: &mut Derivation, | |
| 317 | + next: &mut Vec<(Triple, Reached)>, | |
| 318 | + adj: &mut HashMap<(Uuid, Uuid), Vec<Hop>>, | |
| 319 | +) -> bool { | |
| 320 | + let (pred, subj, obj) = t; | |
| 321 | + // 自环不推,任何规则都一样:`A p A` 是矛盾不是知识 | |
| 322 | + if subj == obj { | |
| 323 | + return false; | |
| 324 | + } | |
| 325 | + // 断言优先;已经推过的不重复推——**逆的互指靠这一条收敛**: | |
| 326 | + // `p⁻¹ = q` 且 `q⁻¹ = p` 时,第二轮推回来的那条已经在 reached 里 | |
| 327 | + if asserted.contains(&t) || reached.contains_key(&t) { | |
| 328 | + return false; | |
| 279 | 329 | } |
| 330 | + let n = per_pred.entry(pred).or_insert(0); | |
| 331 | + if *n >= MAX_DERIVED_PER_PREDICATE { | |
| 332 | + capped.insert(pred); | |
| 333 | + return true; | |
| 334 | + } | |
| 335 | + *n += 1; | |
| 280 | 336 | |
| 281 | - out.facts.extend(emitted); | |
| 282 | - if capped { | |
| 283 | - out.capped.push(pred); | |
| 337 | + let mut premises = acc.premises.clone(); | |
| 338 | + if let Some(p) = extra_premise { | |
| 339 | + premises.push(p); | |
| 340 | + } | |
| 341 | + let r = Reached { | |
| 342 | + from, | |
| 343 | + to, | |
| 344 | + premises: premises.clone(), | |
| 345 | + }; | |
| 346 | + reached.insert(t, r.clone()); | |
| 347 | + // 派生出来的边也能被后续传递接上 | |
| 348 | + if let Some(&first) = premises.first() { | |
| 349 | + adj.entry((pred, subj)) | |
| 350 | + .or_default() | |
| 351 | + .push((obj, from, to, first)); | |
| 284 | 352 | } |
| 353 | + out.facts.push(Derived { | |
| 354 | + predicate: pred, | |
| 355 | + via, | |
| 356 | + subject: subj, | |
| 357 | + object: obj, | |
| 358 | + rule, | |
| 359 | + premises, | |
| 360 | + }); | |
| 361 | + next.push((t, r)); | |
| 362 | + false | |
| 285 | 363 | } |
| 286 | 364 | |
| 287 | 365 | /// 派生事实的有效期,给落库那一侧用。 |
| @@ -501,4 +579,221 @@ | ||
| 501 | 579 | let d = derive(&edges, &transitive()); |
| 502 | 580 | assert!(d.facts.is_empty(), "1 →(99) 2 →(98) 3 推不出任何东西"); |
| 503 | 581 | } |
| 582 | + | |
| 583 | + // ---- 跨谓词的两条规则(inverseOf / subPropertyOf)---- | |
| 584 | + // | |
| 585 | + // 上面那些用的都是单谓词 `n(99)`;这两条规则天生要三个谓词才说得清, | |
| 586 | + // 所以另起一组常量与构造器 | |
| 587 | + | |
| 588 | + const P: Uuid = Uuid::from_bytes([1; 16]); | |
| 589 | + const Q: Uuid = Uuid::from_bytes([2; 16]); | |
| 590 | + const R: Uuid = Uuid::from_bytes([3; 16]); | |
| 591 | + | |
| 592 | + /// 指定谓词的一条无时间边 | |
| 593 | + fn ep(pred: Uuid, fact: u8, s: u8, o: u8) -> TimedEdge { | |
| 594 | + TimedEdge { | |
| 595 | + edge: Edge { | |
| 596 | + fact: f(fact), | |
| 597 | + predicate: pred, | |
| 598 | + subject: n(s), | |
| 599 | + object: n(o), | |
| 600 | + }, | |
| 601 | + from: None, | |
| 602 | + to: None, | |
| 603 | + } | |
| 604 | + } | |
| 605 | + /// 指定谓词、带区间 | |
| 606 | + fn tep(pred: Uuid, fact: u8, s: u8, o: u8, from: Option<i64>, to: Option<i64>) -> TimedEdge { | |
| 607 | + TimedEdge { | |
| 608 | + from, | |
| 609 | + to, | |
| 610 | + ..ep(pred, fact, s, o) | |
| 611 | + } | |
| 612 | + } | |
| 613 | + /// `p⁻¹ = q` 且 `q⁻¹ = p`——互指,收敛性靠它测 | |
| 614 | + fn inverse_pair() -> HashMap<Uuid, Axioms> { | |
| 615 | + HashMap::from([ | |
| 616 | + ( | |
| 617 | + P, | |
| 618 | + Axioms { | |
| 619 | + inverse_of: Some(Q), | |
| 620 | + ..Default::default() | |
| 621 | + }, | |
| 622 | + ), | |
| 623 | + ( | |
| 624 | + Q, | |
| 625 | + Axioms { | |
| 626 | + inverse_of: Some(P), | |
| 627 | + ..Default::default() | |
| 628 | + }, | |
| 629 | + ), | |
| 630 | + ]) | |
| 631 | + } | |
| 632 | + /// `p ⊑ q` | |
| 633 | + fn sub_property() -> HashMap<Uuid, Axioms> { | |
| 634 | + HashMap::from([( | |
| 635 | + P, | |
| 636 | + Axioms { | |
| 637 | + sub_property_of: Some(Q), | |
| 638 | + ..Default::default() | |
| 639 | + }, | |
| 640 | + )]) | |
| 641 | + } | |
| 642 | + | |
| 643 | + /// `A works_at B` ⟹ `B employs A`:主宾对调**且**换谓词。 | |
| 644 | + /// 只做一件就是这条规则最常见的写错方式,所以两件都断言。 | |
| 645 | + #[test] | |
| 646 | + fn the_inverse_swaps_the_ends_and_the_predicate() { | |
| 647 | + let d = derive(&[ep(P, 1, 1, 2)], &inverse_pair()); | |
| 648 | + assert_eq!(d.facts.len(), 1, "一条边只推出一条逆"); | |
| 649 | + let got = &d.facts[0]; | |
| 650 | + assert_eq!(got.predicate, Q, "**谓词换了**"); | |
| 651 | + assert_eq!((got.subject, got.object), (n(2), n(1)), "**主宾也对调了**"); | |
| 652 | + assert_eq!(got.rule, Rule::Inverse); | |
| 653 | + assert_eq!(got.via, P, "声明写在 P 上,产出落在 Q 上"); | |
| 654 | + assert_eq!(got.premises, vec![f(1)], "证明就是那一条原边"); | |
| 655 | + } | |
| 656 | + | |
| 657 | + /// `p⁻¹ = q` 且 `q⁻¹ = p` —— 互指。推回来的那条已经断言过, | |
| 658 | + /// 必须收敛而不是来回震荡。 | |
| 659 | + #[test] | |
| 660 | + fn a_mutual_inverse_settles_instead_of_bouncing() { | |
| 661 | + let d = derive(&[ep(P, 1, 1, 2), ep(Q, 2, 2, 1)], &inverse_pair()); | |
| 662 | + assert!( | |
| 663 | + d.facts.is_empty(), | |
| 664 | + "两个方向都已经断言过,一条都不该推——**断言优先**" | |
| 665 | + ); | |
| 666 | + } | |
| 667 | + | |
| 668 | + /// `p ⊑ q`:断言具体的,通用的也成立。主宾不动。 | |
| 669 | + #[test] | |
| 670 | + fn a_sub_property_lifts_the_predicate_and_keeps_the_ends() { | |
| 671 | + let d = derive(&[ep(P, 1, 1, 2)], &sub_property()); | |
| 672 | + assert_eq!(d.facts.len(), 1); | |
| 673 | + let got = &d.facts[0]; | |
| 674 | + assert_eq!(got.predicate, Q, "升到父属性"); | |
| 675 | + assert_eq!((got.subject, got.object), (n(1), n(2)), "主宾不动"); | |
| 676 | + assert_eq!(got.rule, Rule::SubProperty); | |
| 677 | + assert_eq!( | |
| 678 | + got.via, P, | |
| 679 | + "**via 是声明公理的那个谓词**,不是推出来的那个——落库按它找规则行" | |
| 680 | + ); | |
| 681 | + } | |
| 682 | + | |
| 683 | + /// **不换谓词的两条规则,`via` 必须等于 `predicate`。** | |
| 684 | + /// | |
| 685 | + /// 这条看着是废话,而它正是那个 bug 藏得住的原因:落库从前按 `predicate` | |
| 686 | + /// 找规则行,对传递与对称一直是对的,所以没人发现键选错了。跨谓词的两条 | |
| 687 | + /// 一加,`ceo_of ⊑ works_at` 推出的事实就查不到规则、被静默丢弃。 | |
| 688 | + #[test] | |
| 689 | + fn for_the_same_predicate_rules_via_is_the_predicate() { | |
| 690 | + let d = derive(&[e(1, 1, 2), e(2, 2, 3)], &transitive()); | |
| 691 | + assert!(!d.facts.is_empty()); | |
| 692 | + for f in &d.facts { | |
| 693 | + assert_eq!(f.via, f.predicate, "传递不换谓词"); | |
| 694 | + } | |
| 695 | + } | |
| 696 | + | |
| 697 | + /// **这一条是整次改造的理由**:三条规则串起来。 | |
| 698 | + /// | |
| 699 | + /// `A ceo_of B` ∧ `ceo_of ⊑ works_at` ∧ `works_at⁻¹ = employs` | |
| 700 | + /// ⟹ `A works_at B` ⟹ `B employs A` | |
| 701 | + /// | |
| 702 | + /// 按谓词分组的旧结构在第一步就断了。 | |
| 703 | + #[test] | |
| 704 | + fn a_sub_property_feeds_the_inverse() { | |
| 705 | + let mut ax = HashMap::new(); | |
| 706 | + // ceo_of ⊑ works_at | |
| 707 | + ax.insert( | |
| 708 | + P, | |
| 709 | + Axioms { | |
| 710 | + sub_property_of: Some(Q), | |
| 711 | + ..Default::default() | |
| 712 | + }, | |
| 713 | + ); | |
| 714 | + // works_at⁻¹ = employs | |
| 715 | + ax.insert( | |
| 716 | + Q, | |
| 717 | + Axioms { | |
| 718 | + inverse_of: Some(R), | |
| 719 | + ..Default::default() | |
| 720 | + }, | |
| 721 | + ); | |
| 722 | + let d = derive(&[ep(P, 1, 1, 2)], &ax); | |
| 723 | + let mut got: Vec<(Uuid, u8, u8)> = d | |
| 724 | + .facts | |
| 725 | + .iter() | |
| 726 | + .map(|x| (x.predicate, x.subject.as_bytes()[0], x.object.as_bytes()[0])) | |
| 727 | + .collect(); | |
| 728 | + got.sort(); | |
| 729 | + assert!(got.contains(&(Q, 1, 2)), "先升成 works_at"); | |
| 730 | + assert!( | |
| 731 | + got.contains(&(R, 2, 1)), | |
| 732 | + "**再转成 employs 的反方向**——跨了两个谓词,旧结构做不到" | |
| 733 | + ); | |
| 734 | + assert_eq!(got.len(), 2); | |
| 735 | + // 证明要跟着长:第二跳用掉两条前提里的第一条 | |
| 736 | + let employs = d.facts.iter().find(|x| x.predicate == R).unwrap(); | |
| 737 | + assert_eq!(employs.premises, vec![f(1)], "根还是那条原始断言"); | |
| 738 | + } | |
| 739 | + | |
| 740 | + /// 逆推出来的边要能被传递接上:`p` 传递、`q` 是它的逆, | |
| 741 | + /// `B q A` ∧ `C q B` 应当推出 `C q A`(若 q 也传递)。 | |
| 742 | + #[test] | |
| 743 | + fn what_the_inverse_produces_can_still_be_chained() { | |
| 744 | + let mut ax = HashMap::new(); | |
| 745 | + ax.insert( | |
| 746 | + P, | |
| 747 | + Axioms { | |
| 748 | + inverse_of: Some(Q), | |
| 749 | + ..Default::default() | |
| 750 | + }, | |
| 751 | + ); | |
| 752 | + ax.insert( | |
| 753 | + Q, | |
| 754 | + Axioms { | |
| 755 | + transitive: true, | |
| 756 | + ..Default::default() | |
| 757 | + }, | |
| 758 | + ); | |
| 759 | + // A p B、B p C ⟹ B q A、C q B ⟹(q 传递)⟹ C q A | |
| 760 | + let d = derive(&[ep(P, 1, 1, 2), ep(P, 2, 2, 3)], &ax); | |
| 761 | + let got: Vec<(Uuid, u8, u8)> = d | |
| 762 | + .facts | |
| 763 | + .iter() | |
| 764 | + .map(|x| (x.predicate, x.subject.as_bytes()[0], x.object.as_bytes()[0])) | |
| 765 | + .collect(); | |
| 766 | + assert!(got.contains(&(Q, 2, 1))); | |
| 767 | + assert!(got.contains(&(Q, 3, 2))); | |
| 768 | + assert!( | |
| 769 | + got.contains(&(Q, 3, 1)), | |
| 770 | + "**逆产出的边要进邻接表**,否则传递接不上它" | |
| 771 | + ); | |
| 772 | + } | |
| 773 | + | |
| 774 | + /// 区间照旧取交集,跨谓词也一样。 | |
| 775 | + #[test] | |
| 776 | + fn the_inverse_carries_the_same_span() { | |
| 777 | + let d = derive(&[tep(P, 1, 1, 2, Some(10), Some(20))], &inverse_pair()); | |
| 778 | + assert_eq!(d.facts.len(), 1); | |
| 779 | + let v = validity( | |
| 780 | + &d.facts[0].premises, | |
| 781 | + &HashMap::from([(f(1), (Some(10), Some(20)))]), | |
| 782 | + ); | |
| 783 | + assert_eq!(v, Some((Some(10), Some(20))), "逆不改变有效期"); | |
| 784 | + } | |
| 785 | + | |
| 786 | + /// 自己是自己的逆 = 对称,但不该推出自环。 | |
| 787 | + #[test] | |
| 788 | + fn a_predicate_that_is_its_own_inverse_still_refuses_self_loops() { | |
| 789 | + let ax = HashMap::from([( | |
| 790 | + P, | |
| 791 | + Axioms { | |
| 792 | + inverse_of: Some(P), | |
| 793 | + ..Default::default() | |
| 794 | + }, | |
| 795 | + )]); | |
| 796 | + let d = derive(&[ep(P, 1, 1, 1)], &ax); | |
| 797 | + assert!(d.facts.is_empty(), "`A p A` 的逆还是 `A p A`——自环不推"); | |
| 798 | + } | |
| 504 | 799 | } |
modified crates/utopia-reason/src/lib.rs +5 −0
| @@ -36,6 +36,11 @@ | ||
| 36 | 36 | pub irreflexive: bool, |
| 37 | 37 | pub functional: bool, |
| 38 | 38 | pub inverse_functional: bool, |
| 39 | + /// `p⁻¹ = q`:这个谓词的逆是哪一个。**跨谓词的规则从这里来**—— | |
| 40 | + /// `A p B` 推出 `B q A`,而 R0 的检查也要看它(自己是自己的逆等于对称) | |
| 41 | + pub inverse_of: Option<Uuid>, | |
| 42 | + /// `p ⊑ q`:断言了具体的,通用的也成立。链要防成环,R0 那边查 | |
| 43 | + pub sub_property_of: Option<Uuid>, | |
| 39 | 44 | } |
| 40 | 45 | |
| 41 | 46 | impl Axioms { |
modified crates/utopia-reason/src/ontology.rs +223 −0
| @@ -44,6 +44,17 @@ | ||
| 44 | 44 | /// 一个类的两个祖先互相互斥 → 同上,不可满足。 |
| 45 | 45 | /// 多父继承下这个形状不罕见:两支各自合理,合起来就矛盾了。 |
| 46 | 46 | InheritsDisjoint, |
| 47 | + /// 一个谓词声明自己是自己的逆。**等价于 symmetric**——推理照跑, | |
| 48 | + /// 只是读的人要多想一步。提示改写成 `symmetric` 更直白 | |
| 49 | + InverseOfItself, | |
| 50 | + /// `p⁻¹ = q` 而 `q⁻¹ = r`,两边指得不一样。 | |
| 51 | + /// | |
| 52 | + /// 载入公理时只补空缺、不覆盖人写的(**人写的优先于推出来的**), | |
| 53 | + /// 所以这个矛盾不会被悄悄抹平,留到这里报。 | |
| 54 | + InverseNotMutual, | |
| 55 | + /// subPropertyOf 绕成了环。与 [`Defect::SubclassCycle`] 同形: | |
| 56 | + /// 环上所有谓词互为子属性 = 它们其实是同一个谓词,而各自有标签、有事实。 | |
| 57 | + SubPropertyCycle, | |
| 47 | 58 | } |
| 48 | 59 | |
| 49 | 60 | impl Defect { |
| @@ -54,6 +65,9 @@ | ||
| 54 | 65 | Defect::SubclassCycle => "subclass_cycle", |
| 55 | 66 | Defect::DisjointWithAncestor => "disjoint_with_ancestor", |
| 56 | 67 | Defect::InheritsDisjoint => "inherits_disjoint", |
| 68 | + Defect::InverseOfItself => "inverse_of_itself", | |
| 69 | + Defect::InverseNotMutual => "inverse_not_mutual", | |
| 70 | + Defect::SubPropertyCycle => "sub_property_cycle", | |
| 57 | 71 | } |
| 58 | 72 | } |
| 59 | 73 | } |
| @@ -102,6 +116,79 @@ | ||
| 102 | 116 | path: Vec::new(), |
| 103 | 117 | }); |
| 104 | 118 | } |
| 119 | + // 自己是自己的逆 = 对称。**不是错,是绕远路**——推理照跑, | |
| 120 | + // 但读本体的人得自己想一步才明白。提示改用 `symmetric` 更直白 | |
| 121 | + if ax.inverse_of == Some(pred) { | |
| 122 | + out.push(OntologyDefect { | |
| 123 | + kind: Defect::InverseOfItself, | |
| 124 | + subject: pred, | |
| 125 | + other: None, | |
| 126 | + path: Vec::new(), | |
| 127 | + }); | |
| 128 | + } | |
| 129 | + // 逆 + 反对称:`A p B` 推出 `B p A`(自己的逆),而反对称说这不成立。 | |
| 130 | + // 与 symmetric+asymmetric 同一个矛盾,换了个写法进来 | |
| 131 | + if ax.inverse_of == Some(pred) && ax.asymmetric { | |
| 132 | + out.push(OntologyDefect { | |
| 133 | + kind: Defect::SymmetricAndAsymmetric, | |
| 134 | + subject: pred, | |
| 135 | + other: None, | |
| 136 | + path: Vec::new(), | |
| 137 | + }); | |
| 138 | + } | |
| 139 | + // 两边各自声明了逆,却指向不同的谓词。**不在载入时悄悄改一致** | |
| 140 | + // (`reasoning::axioms` 那边只补空缺,不覆盖人写的),所以在这里报 | |
| 141 | + if let Some(inv) = ax.inverse_of { | |
| 142 | + if let Some(back) = axioms.get(&inv).and_then(|a| a.inverse_of) { | |
| 143 | + if back != pred { | |
| 144 | + out.push(OntologyDefect { | |
| 145 | + kind: Defect::InverseNotMutual, | |
| 146 | + subject: pred, | |
| 147 | + other: Some(inv), | |
| 148 | + path: vec![pred, inv, back], | |
| 149 | + }); | |
| 150 | + } | |
| 151 | + } | |
| 152 | + } | |
| 153 | + } | |
| 154 | + | |
| 155 | + // ---- subPropertyOf 成环。与 subClassOf 的环是同一个形状: | |
| 156 | + // 环上所有谓词互为子属性 = 它们其实是同一个谓词,而各自有标签、有事实 | |
| 157 | + { | |
| 158 | + let parent_of: HashMap<Uuid, Uuid> = axioms | |
| 159 | + .iter() | |
| 160 | + .filter_map(|(id, ax)| ax.sub_property_of.map(|p| (*id, p))) | |
| 161 | + .collect(); | |
| 162 | + let mut starts: Vec<Uuid> = parent_of.keys().copied().collect(); | |
| 163 | + starts.sort(); | |
| 164 | + let mut reported: HashSet<Uuid> = HashSet::new(); | |
| 165 | + for start in starts { | |
| 166 | + if reported.contains(&start) { | |
| 167 | + continue; | |
| 168 | + } | |
| 169 | + let mut seen: Vec<Uuid> = Vec::new(); | |
| 170 | + let mut cur = start; | |
| 171 | + for _ in 0..MAX_ANCESTRY { | |
| 172 | + if seen.contains(&cur) { | |
| 173 | + // 环上每个成员都标记过,整条环只报一次 | |
| 174 | + for m in &seen { | |
| 175 | + reported.insert(*m); | |
| 176 | + } | |
| 177 | + out.push(OntologyDefect { | |
| 178 | + kind: Defect::SubPropertyCycle, | |
| 179 | + subject: start, | |
| 180 | + other: None, | |
| 181 | + path: seen.clone(), | |
| 182 | + }); | |
| 183 | + break; | |
| 184 | + } | |
| 185 | + seen.push(cur); | |
| 186 | + match parent_of.get(&cur) { | |
| 187 | + Some(&p) => cur = p, | |
| 188 | + None => break, | |
| 189 | + } | |
| 190 | + } | |
| 191 | + } | |
| 105 | 192 | } |
| 106 | 193 | |
| 107 | 194 | let up = adjacency(parents); |
| @@ -390,3 +477,139 @@ | ||
| 390 | 477 | assert!(check_ontology(&HashMap::new(), &parents, &[]).is_empty()); |
| 391 | 478 | } |
| 392 | 479 | } |
| 480 | + | |
| 481 | +#[cfg(test)] | |
| 482 | +mod inverse_and_sub_property_tests { | |
| 483 | + use super::*; | |
| 484 | + | |
| 485 | + fn c(i: u8) -> Uuid { | |
| 486 | + Uuid::from_bytes([i; 16]) | |
| 487 | + } | |
| 488 | + fn kinds(v: &[OntologyDefect]) -> Vec<Defect> { | |
| 489 | + let mut k: Vec<Defect> = v.iter().map(|d| d.kind).collect(); | |
| 490 | + k.sort(); | |
| 491 | + k | |
| 492 | + } | |
| 493 | + fn only(id: Uuid, a: Axioms) -> HashMap<Uuid, Axioms> { | |
| 494 | + HashMap::from([(id, a)]) | |
| 495 | + } | |
| 496 | + | |
| 497 | + /// 自己是自己的逆 —— 合法但绕远路,提示改用 symmetric。 | |
| 498 | + #[test] | |
| 499 | + fn a_predicate_that_is_its_own_inverse_should_just_say_symmetric() { | |
| 500 | + let a = Axioms { | |
| 501 | + inverse_of: Some(c(1)), | |
| 502 | + ..Default::default() | |
| 503 | + }; | |
| 504 | + let d = check_ontology(&only(c(1), a), &[], &[]); | |
| 505 | + assert_eq!(kinds(&d), vec![Defect::InverseOfItself]); | |
| 506 | + } | |
| 507 | + | |
| 508 | + /// 自己的逆 + 反对称 = 与 symmetric+asymmetric 同一个矛盾,换了个写法。 | |
| 509 | + #[test] | |
| 510 | + fn its_own_inverse_and_asymmetric_is_the_same_contradiction_in_disguise() { | |
| 511 | + let a = Axioms { | |
| 512 | + inverse_of: Some(c(1)), | |
| 513 | + asymmetric: true, | |
| 514 | + ..Default::default() | |
| 515 | + }; | |
| 516 | + let d = check_ontology(&only(c(1), a), &[], &[]); | |
| 517 | + assert!( | |
| 518 | + kinds(&d).contains(&Defect::SymmetricAndAsymmetric), | |
| 519 | + "**要报成同一类**:读的人不该因为写法不同就以为是两回事" | |
| 520 | + ); | |
| 521 | + } | |
| 522 | + | |
| 523 | + /// 互指一致 —— 干净,什么都不该报。 | |
| 524 | + #[test] | |
| 525 | + fn a_mutual_pair_is_clean() { | |
| 526 | + let ax = HashMap::from([ | |
| 527 | + ( | |
| 528 | + c(1), | |
| 529 | + Axioms { | |
| 530 | + inverse_of: Some(c(2)), | |
| 531 | + ..Default::default() | |
| 532 | + }, | |
| 533 | + ), | |
| 534 | + ( | |
| 535 | + c(2), | |
| 536 | + Axioms { | |
| 537 | + inverse_of: Some(c(1)), | |
| 538 | + ..Default::default() | |
| 539 | + }, | |
| 540 | + ), | |
| 541 | + ]); | |
| 542 | + assert!(check_ontology(&ax, &[], &[]).is_empty()); | |
| 543 | + } | |
| 544 | + | |
| 545 | + /// `p⁻¹ = q` 而 `q⁻¹ = r` —— 两边指得不一样。 | |
| 546 | + /// | |
| 547 | + /// **载入公理时只补空缺不覆盖**,所以这个矛盾不会被悄悄抹平; | |
| 548 | + /// 它必须在这里被报出来,否则没有任何地方会提。 | |
| 549 | + #[test] | |
| 550 | + fn an_inverse_that_does_not_point_back_is_reported() { | |
| 551 | + let ax = HashMap::from([ | |
| 552 | + ( | |
| 553 | + c(1), | |
| 554 | + Axioms { | |
| 555 | + inverse_of: Some(c(2)), | |
| 556 | + ..Default::default() | |
| 557 | + }, | |
| 558 | + ), | |
| 559 | + ( | |
| 560 | + c(2), | |
| 561 | + Axioms { | |
| 562 | + inverse_of: Some(c(3)), | |
| 563 | + ..Default::default() | |
| 564 | + }, | |
| 565 | + ), | |
| 566 | + ]); | |
| 567 | + let d = check_ontology(&ax, &[], &[]); | |
| 568 | + let one = d | |
| 569 | + .iter() | |
| 570 | + .find(|x| x.kind == Defect::InverseNotMutual) | |
| 571 | + .expect("该报 InverseNotMutual"); | |
| 572 | + assert_eq!(one.subject, c(1)); | |
| 573 | + assert_eq!(one.other, Some(c(2))); | |
| 574 | + assert_eq!(one.path, vec![c(1), c(2), c(3)], "路径要说清指到哪去了"); | |
| 575 | + } | |
| 576 | + | |
| 577 | + /// subPropertyOf 成环。 | |
| 578 | + #[test] | |
| 579 | + fn a_sub_property_ring_is_a_single_predicate_wearing_three_hats() { | |
| 580 | + let mk = |parent: u8| Axioms { | |
| 581 | + sub_property_of: Some(c(parent)), | |
| 582 | + ..Default::default() | |
| 583 | + }; | |
| 584 | + let ax = HashMap::from([(c(1), mk(2)), (c(2), mk(3)), (c(3), mk(1))]); | |
| 585 | + let d = check_ontology(&ax, &[], &[]); | |
| 586 | + let ring: Vec<&OntologyDefect> = d | |
| 587 | + .iter() | |
| 588 | + .filter(|x| x.kind == Defect::SubPropertyCycle) | |
| 589 | + .collect(); | |
| 590 | + assert_eq!(ring.len(), 1, "**整条环只报一次**,不是每个成员报一遍"); | |
| 591 | + assert_eq!(ring[0].path.len(), 3); | |
| 592 | + } | |
| 593 | + | |
| 594 | + /// 一条不成环的链不该被误报。 | |
| 595 | + #[test] | |
| 596 | + fn a_chain_that_ends_is_not_a_ring() { | |
| 597 | + let ax = HashMap::from([ | |
| 598 | + ( | |
| 599 | + c(1), | |
| 600 | + Axioms { | |
| 601 | + sub_property_of: Some(c(2)), | |
| 602 | + ..Default::default() | |
| 603 | + }, | |
| 604 | + ), | |
| 605 | + ( | |
| 606 | + c(2), | |
| 607 | + Axioms { | |
| 608 | + sub_property_of: Some(c(3)), | |
| 609 | + ..Default::default() | |
| 610 | + }, | |
| 611 | + ), | |
| 612 | + ]); | |
| 613 | + assert!(check_ontology(&ax, &[], &[]).is_empty()); | |
| 614 | + } | |
| 615 | +} |
modified crates/utopia-server/src/api/ontology_routes.rs +14 −1
| @@ -223,6 +223,16 @@ | ||
| 223 | 223 | pub is_asymmetric: bool, |
| 224 | 224 | #[serde(default)] |
| 225 | 225 | pub is_irreflexive: bool, |
| 226 | + /// 指向另一个关系的两条(`inverseOf` / `subPropertyOf`)。 | |
| 227 | + /// | |
| 228 | + /// **缺省 = 清空,与上面六位同一条规矩。** 它们是同一个表单一次提交的 | |
| 229 | + /// 一组声明;一半覆盖一半保留,会让「我把逆去掉了」和「我没碰逆」 | |
| 230 | + /// 长得一模一样。属性表单不填这两个,而属性本来就不许有—— | |
| 231 | + /// store 层会拦,落库也照样是 NULL | |
| 232 | + #[serde(default)] | |
| 233 | + pub inverse_of: Option<Uuid>, | |
| 234 | + #[serde(default)] | |
| 235 | + pub sub_property_of: Option<Uuid>, | |
| 226 | 236 | #[serde(default)] |
| 227 | 237 | pub description: Option<String>, |
| 228 | 238 | /// relation | attribute(创建时定死,更新时忽略) |
| @@ -244,7 +254,8 @@ | ||
| 244 | 254 | } |
| 245 | 255 | |
| 246 | 256 | impl RelationTypeReq { |
| 247 | - /// 六位公理打包。**散着传迟早传错顺序**——它们都是 bool,编译器帮不上忙。 | |
| 257 | + /// 公理打包。**散着传迟早传错顺序**——六位都是 bool,编译器帮不上忙; | |
| 258 | + /// 后两位都是 `Option<Uuid>`,一样。 | |
| 248 | 259 | fn axioms(&self) -> utopia_core::models::RelationAxioms { |
| 249 | 260 | utopia_core::models::RelationAxioms { |
| 250 | 261 | functional: self.functional, |
| @@ -253,6 +264,8 @@ | ||
| 253 | 264 | symmetric: self.is_symmetric, |
| 254 | 265 | asymmetric: self.is_asymmetric, |
| 255 | 266 | irreflexive: self.is_irreflexive, |
| 267 | + inverse_of: self.inverse_of, | |
| 268 | + sub_property_of: self.sub_property_of, | |
| 256 | 269 | } |
| 257 | 270 | } |
| 258 | 271 | } |
modified crates/utopia-server/src/owl_import.rs +29 −0
| @@ -543,6 +543,31 @@ | ||
| 543 | 543 | let rel_ids = |
| 544 | 544 | utopia_store::ontology::create_relation_types_bulk(&state.pool, kb_id, &new_rels).await?; |
| 545 | 545 | created_rels += rel_ids.len(); |
| 546 | + | |
| 547 | + // 逆与父属性指的是**另一个关系类型**,id 要等全部插完才有——所以是第二遍。 | |
| 548 | + // 一遍过只能处理「父属性恰好排在前面」的文件,而 RDF 三元组没有顺序。 | |
| 549 | + // | |
| 550 | + // 新建的与已存在的都收:一份本体重导时,这两条声明可能是这次才加上的 | |
| 551 | + let mut inv_pairs: Vec<(String, String)> = Vec::new(); | |
| 552 | + let mut sub_pairs: Vec<(String, String)> = Vec::new(); | |
| 553 | + for item in &plan.relations { | |
| 554 | + let Some(p) = by_prop_iri.get(item.iri.as_str()) else { | |
| 555 | + continue; | |
| 556 | + }; | |
| 557 | + if let Some(o) = &p.inverse_of { | |
| 558 | + inv_pairs.push((p.iri.clone(), o.clone())); | |
| 559 | + } | |
| 560 | + if let Some(o) = &p.sub_property_of { | |
| 561 | + sub_pairs.push((p.iri.clone(), o.clone())); | |
| 562 | + } | |
| 563 | + } | |
| 564 | + let (linked_inv, linked_sub) = utopia_store::ontology::link_property_axioms_bulk( | |
| 565 | + &state.pool, | |
| 566 | + kb_id, | |
| 567 | + &inv_pairs, | |
| 568 | + &sub_pairs, | |
| 569 | + ) | |
| 570 | + .await?; | |
| 546 | 571 | // 关联行也摊平:单条版对每条关系跑 4 句(两张表各一次 DELETE 一次 INSERT), |
| 547 | 572 | // 一千五百条关系就是六千次提交 |
| 548 | 573 | let mut link_d: Vec<(Uuid, Uuid)> = Vec::new(); |
| @@ -617,6 +642,10 @@ | ||
| 617 | 642 | "classes_updated": updated_classes, |
| 618 | 643 | "classes_key_taken": plan.classes.iter().filter(|c| c.disposition == Disposition::KeyTaken).count(), |
| 619 | 644 | "relations_seen": plan.relations.len(), |
| 645 | + // 连上了几条逆 / 父属性。**报出来**——目标 IRI 不在这个库里时会静默跳过 | |
| 646 | + // (引用外部词汇表是常态),不给数就没人知道少连了多少 | |
| 647 | + "inverse_linked": linked_inv, | |
| 648 | + "sub_property_linked": linked_sub, | |
| 620 | 649 | "relations_created": created_rels, |
| 621 | 650 | "relations_updated": updated_rels, |
| 622 | 651 | "attributes_seen": plan.attributes.len(), |
modified crates/utopia-store/src/ontology.rs +135 −3
| @@ -75,6 +75,7 @@ | ||
| 75 | 75 | Ok(sqlx::query_as( |
| 76 | 76 | "SELECT r.id, r.key, r.label, r.temporal, r.functional, r.inverse_functional, |
| 77 | 77 | r.is_transitive, r.is_symmetric, r.is_asymmetric, r.is_irreflexive, |
| 78 | + r.inverse_of, r.sub_property_of, | |
| 78 | 79 | r.builtin, r.description, |
| 79 | 80 | r.kind, r.datatype, r.unit, |
| 80 | 81 | ARRAY(SELECT d.entity_type_id FROM relation_type_domains d |
| @@ -302,6 +303,68 @@ | ||
| 302 | 303 | } |
| 303 | 304 | } |
| 304 | 305 | |
| 306 | +/// 两条指向别的关系的公理,落库前必须过这里。 | |
| 307 | +/// | |
| 308 | +/// **最要紧的一条是同库。** 列上的外键是 `REFERENCES relation_types(id)`, | |
| 309 | +/// 它不认知识库——数据库层面,A 库的关系可以指向 B 库的关系。RDF 导入那条路 | |
| 310 | +/// 天然过不去(按 IRI 在本库里查),而接口收的是裸 UUID:不在这里挡, | |
| 311 | +/// 拿到任意一个 UUID 就能让推理机跨库读公理。**不能靠前端只列本库选项**, | |
| 312 | +/// 那是界面礼貌,不是边界。 | |
| 313 | +/// | |
| 314 | +/// 另外两条:属性没有逆(它的宾语是字面值,反过来无从谈起), | |
| 315 | +/// 子属性不能是自己(DB 有 CHECK,但撞上去是 500,得在这里给出人话)。 | |
| 316 | +/// 而**逆是自己允许**——那等于对称,R0 会提示改用 `symmetric` 更直白,不算错。 | |
| 317 | +async fn validate_property_links( | |
| 318 | + pool: &PgPool, | |
| 319 | + kb_id: Uuid, | |
| 320 | + self_id: Option<Uuid>, | |
| 321 | + kind: &str, | |
| 322 | + ax: RelationAxioms, | |
| 323 | +) -> AppResult<()> { | |
| 324 | + let links = [ax.inverse_of, ax.sub_property_of]; | |
| 325 | + if links.iter().all(|l| l.is_none()) { | |
| 326 | + return Ok(()); | |
| 327 | + } | |
| 328 | + if kind == "attribute" { | |
| 329 | + return Err(AppError::invalid( | |
| 330 | + "attr_has_no_link", | |
| 331 | + "An attribute cannot have an inverse or a super-property", | |
| 332 | + )); | |
| 333 | + } | |
| 334 | + if self_id.is_some() && ax.sub_property_of == self_id { | |
| 335 | + return Err(AppError::invalid( | |
| 336 | + "sub_property_self", | |
| 337 | + "A relation cannot be its own super-property", | |
| 338 | + )); | |
| 339 | + } | |
| 340 | + for target in links.into_iter().flatten() { | |
| 341 | + let ok: Option<(String,)> = | |
| 342 | + sqlx::query_as("SELECT kind FROM relation_types WHERE id = $1 AND kb_id = $2") | |
| 343 | + .bind(target) | |
| 344 | + .bind(kb_id) | |
| 345 | + .fetch_optional(pool) | |
| 346 | + .await?; | |
| 347 | + match ok { | |
| 348 | + // 不区分「不存在」与「在别的库」:能问出哪个 UUID 存在于别处, | |
| 349 | + // 本身就是一点不该给的信息 | |
| 350 | + None => { | |
| 351 | + return Err(AppError::invalid( | |
| 352 | + "unknown_relation", | |
| 353 | + "That relation is not in this knowledge base", | |
| 354 | + )); | |
| 355 | + } | |
| 356 | + Some((k,)) if k != "relation" => { | |
| 357 | + return Err(AppError::invalid( | |
| 358 | + "link_target_is_attr", | |
| 359 | + "An attribute cannot be an inverse or a super-property", | |
| 360 | + )); | |
| 361 | + } | |
| 362 | + Some(_) => {} | |
| 363 | + } | |
| 364 | + } | |
| 365 | + Ok(()) | |
| 366 | +} | |
| 367 | + | |
| 305 | 368 | #[allow(clippy::too_many_arguments)] |
| 306 | 369 | pub async fn create_relation_type( |
| 307 | 370 | pool: &PgPool, |
| @@ -324,6 +387,8 @@ | ||
| 324 | 387 | )); |
| 325 | 388 | } |
| 326 | 389 | validate_attribute_fields(kind, domains, datatype)?; |
| 390 | + // 新建的行 id 还不存在,指向自己无从谈起——所以 self_id 传 None | |
| 391 | + validate_property_links(pool, kb_id, None, kind, ax).await?; | |
| 327 | 392 | let is_attr = kind == "attribute"; |
| 328 | 393 | let id = Uuid::now_v7(); |
| 329 | 394 | sqlx::query( |
| @@ -331,8 +396,10 @@ | ||
| 331 | 396 | functional, inverse_functional, description, |
| 332 | 397 | kind, datatype, unit, |
| 333 | 398 | is_transitive, is_symmetric, |
| 334 | - is_asymmetric, is_irreflexive) | |
| 335 | - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)", | |
| 399 | + is_asymmetric, is_irreflexive, | |
| 400 | + inverse_of, sub_property_of) | |
| 401 | + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, | |
| 402 | + $16, $17)", | |
| 336 | 403 | ) |
| 337 | 404 | .bind(id) |
| 338 | 405 | .bind(kb_id) |
| @@ -349,6 +416,9 @@ | ||
| 349 | 416 | .bind(ax.symmetric) |
| 350 | 417 | .bind(ax.asymmetric) |
| 351 | 418 | .bind(ax.irreflexive) |
| 419 | + // 属性不带这两条(上面已经拦了非空的情况,这里是兜底) | |
| 420 | + .bind(if is_attr { None } else { ax.inverse_of }) | |
| 421 | + .bind(if is_attr { None } else { ax.sub_property_of }) | |
| 352 | 422 | .execute(pool) |
| 353 | 423 | .await |
| 354 | 424 | .map_err(|e| match &e { |
| @@ -421,9 +491,25 @@ | ||
| 421 | 491 | "datatype must be text / number / date / bool".into(), |
| 422 | 492 | )); |
| 423 | 493 | } |
| 494 | + // 指向别的关系的两条要先问过库:目标在不在本库、是不是关系。 | |
| 495 | + // 只在真的填了的时候查——清空(两个都 None)没有目标可验 | |
| 496 | + if ax.inverse_of.is_some() || ax.sub_property_of.is_some() { | |
| 497 | + let row: Option<(String,)> = | |
| 498 | + sqlx::query_as("SELECT kind FROM relation_types WHERE id = $1 AND kb_id = $2") | |
| 499 | + .bind(id) | |
| 500 | + .bind(kb_id) | |
| 501 | + .fetch_optional(pool) | |
| 502 | + .await?; | |
| 503 | + let (kind,) = row.ok_or(AppError::NotFound)?; | |
| 504 | + validate_property_links(pool, kb_id, Some(id), &kind, ax).await?; | |
| 505 | + } | |
| 424 | 506 | // kind 不可变(改它会让存量事实语义错乱)。domain/range 可改—— |
| 425 | 507 | // 它们是签名不是身份,"这个属性也适用于承包商" 是个正当的编辑。 |
| 426 | 508 | // datatype/unit 只对 attribute 行生效,datatype 缺省保持原值 |
| 509 | + // | |
| 510 | + // 两条链**跟着六位公理一起覆盖式写**:缺省 = 清空,不是「不动」。 | |
| 511 | + // 与 `is_transitive` 那几位同一条规矩——它们是同一个表单里同时提交的 | |
| 512 | + // 一组声明,一半覆盖一半保留才是真正会出事的语义 | |
| 427 | 513 | let res = sqlx::query( |
| 428 | 514 | "UPDATE relation_types |
| 429 | 515 | SET label = $3, temporal = $4, |
| @@ -431,7 +517,8 @@ | ||
| 431 | 517 | datatype = CASE WHEN kind = 'attribute' AND $8 IS NOT NULL THEN $8 ELSE datatype END, |
| 432 | 518 | unit = CASE WHEN kind = 'attribute' THEN $9 ELSE unit END, |
| 433 | 519 | is_transitive = $10, is_symmetric = $11, |
| 434 | - is_asymmetric = $12, is_irreflexive = $13 | |
| 520 | + is_asymmetric = $12, is_irreflexive = $13, | |
| 521 | + inverse_of = $14, sub_property_of = $15 | |
| 435 | 522 | WHERE id = $2 AND kb_id = $1", |
| 436 | 523 | ) |
| 437 | 524 | .bind(kb_id) |
| @@ -447,6 +534,8 @@ | ||
| 447 | 534 | .bind(ax.symmetric) |
| 448 | 535 | .bind(ax.asymmetric) |
| 449 | 536 | .bind(ax.irreflexive) |
| 537 | + .bind(ax.inverse_of) | |
| 538 | + .bind(ax.sub_property_of) | |
| 450 | 539 | .execute(pool) |
| 451 | 540 | .await?; |
| 452 | 541 | if res.rows_affected() == 0 { |
| @@ -1678,3 +1767,46 @@ | ||
| 1678 | 1767 | .await?; |
| 1679 | 1768 | Ok((declared > 0).then_some(ok > 0)) |
| 1680 | 1769 | } |
| 1770 | + | |
| 1771 | +/// 把 `owl:inverseOf` / `rdfs:subPropertyOf` 从 IRI 解析成 id。 | |
| 1772 | +/// | |
| 1773 | +/// **必须是第二遍。** 这两条指的是另一个关系类型,而 id 要等全部插完才有—— | |
| 1774 | +/// 一遍过的写法只能处理「父属性恰好排在前面」的文件,而 RDF 三元组没有顺序。 | |
| 1775 | +/// | |
| 1776 | +/// 按 IRI 配对而不是按 key:key 会因为撞名加后缀(`part_of_2`), | |
| 1777 | +/// 而 IRI 是这份本体里的身份。 | |
| 1778 | +pub async fn link_property_axioms_bulk( | |
| 1779 | + pool: &PgPool, | |
| 1780 | + kb_id: Uuid, | |
| 1781 | + inverse: &[(String, String)], | |
| 1782 | + sub_property: &[(String, String)], | |
| 1783 | +) -> AppResult<(u64, u64)> { | |
| 1784 | + let run = |column: &'static str, pairs: &[(String, String)]| { | |
| 1785 | + let src: Vec<String> = pairs.iter().map(|(s, _)| s.clone()).collect(); | |
| 1786 | + let dst: Vec<String> = pairs.iter().map(|(_, d)| d.clone()).collect(); | |
| 1787 | + async move { | |
| 1788 | + if src.is_empty() { | |
| 1789 | + return AppResult::Ok(0); | |
| 1790 | + } | |
| 1791 | + // 目标 IRI 在这个库里找不到就跳过这一条——**部分导入是常态** | |
| 1792 | + // (引用了外部词汇表里的属性),一条连不上不该让整次导入失败 | |
| 1793 | + let sql = format!( | |
| 1794 | + "UPDATE relation_types r SET {column} = t.id | |
| 1795 | + FROM UNNEST($2::text[], $3::text[]) AS p(src, dst) | |
| 1796 | + JOIN relation_types t ON t.kb_id = $1 AND t.iri = p.dst | |
| 1797 | + WHERE r.kb_id = $1 AND r.iri = p.src AND r.id <> t.id" | |
| 1798 | + ); | |
| 1799 | + let n = sqlx::query(&sql) | |
| 1800 | + .bind(kb_id) | |
| 1801 | + .bind(&src) | |
| 1802 | + .bind(&dst) | |
| 1803 | + .execute(pool) | |
| 1804 | + .await? | |
| 1805 | + .rows_affected(); | |
| 1806 | + AppResult::Ok(n) | |
| 1807 | + } | |
| 1808 | + }; | |
| 1809 | + let inv = run("inverse_of", inverse).await?; | |
| 1810 | + let sub = run("sub_property_of", sub_property).await?; | |
| 1811 | + Ok((inv, sub)) | |
| 1812 | +} |
modified crates/utopia-store/src/reasoning.rs +68 −9
| @@ -72,19 +72,31 @@ | ||
| 72 | 72 | /// **只取声明了至少一位的**:一位都没声明的谓词进了表也不会被检查(`says_nothing` |
| 73 | 73 | /// 会跳过),白白占内存。而且这个条数本身有意义——它是「有没有判据」的度量, |
| 74 | 74 | /// 报告里要用。 |
| 75 | +#[allow(clippy::type_complexity)] | |
| 75 | 76 | async fn axioms(pool: &PgPool, kb_id: Uuid) -> AppResult<HashMap<Uuid, Axioms>> { |
| 76 | - let rows: Vec<(Uuid, bool, bool, bool, bool, bool, bool)> = sqlx::query_as( | |
| 77 | + let rows: Vec<( | |
| 78 | + Uuid, | |
| 79 | + bool, | |
| 80 | + bool, | |
| 81 | + bool, | |
| 82 | + bool, | |
| 83 | + bool, | |
| 84 | + bool, | |
| 85 | + Option<Uuid>, | |
| 86 | + Option<Uuid>, | |
| 87 | + )> = sqlx::query_as( | |
| 77 | 88 | "SELECT id, is_transitive, is_symmetric, is_asymmetric, is_irreflexive, |
| 78 | - functional, inverse_functional | |
| 79 | - FROM relation_types | |
| 80 | - WHERE kb_id = $1 | |
| 81 | - AND (is_transitive OR is_symmetric OR is_asymmetric OR is_irreflexive | |
| 82 | - OR functional OR inverse_functional)", | |
| 89 | + functional, inverse_functional, inverse_of, sub_property_of | |
| 90 | + FROM relation_types | |
| 91 | + WHERE kb_id = $1 | |
| 92 | + AND (is_transitive OR is_symmetric OR is_asymmetric OR is_irreflexive | |
| 93 | + OR functional OR inverse_functional | |
| 94 | + OR inverse_of IS NOT NULL OR sub_property_of IS NOT NULL)", | |
| 83 | 95 | ) |
| 84 | 96 | .bind(kb_id) |
| 85 | 97 | .fetch_all(pool) |
| 86 | 98 | .await?; |
| 87 | - Ok(rows | |
| 99 | + let mut map: HashMap<Uuid, Axioms> = rows | |
| 88 | 100 | .into_iter() |
| 89 | 101 | .map( |
| 90 | 102 | |( |
| @@ -95,6 +107,8 @@ | ||
| 95 | 107 | irreflexive, |
| 96 | 108 | functional, |
| 97 | 109 | inverse_functional, |
| 110 | + inverse_of, | |
| 111 | + sub_property_of, | |
| 98 | 112 | )| { |
| 99 | 113 | ( |
| 100 | 114 | id, |
| @@ -105,11 +119,33 @@ | ||
| 105 | 119 | irreflexive, |
| 106 | 120 | functional, |
| 107 | 121 | inverse_functional, |
| 122 | + inverse_of, | |
| 123 | + sub_property_of, | |
| 108 | 124 | }, |
| 109 | 125 | ) |
| 110 | 126 | }, |
| 111 | 127 | ) |
| 112 | - .collect()) | |
| 128 | + .collect(); | |
| 129 | + | |
| 130 | + // **逆是相互的,而库里只存单向。** 声明了 `p⁻¹ = q` 却没回填 | |
| 131 | + // `q⁻¹ = p` 的话,`A p B` 推得出 `B q A`,`B q A` 却推不回 `A p B` | |
| 132 | + // ——「问工作和问雇佣答案不同」正是 R1 要消灭的东西,只修一半等于没修。 | |
| 133 | + // | |
| 134 | + // 归一化放在这里而不是数据库触发器:绕过触发器的路不止一条(RDF 导入、 | |
| 135 | + // 直接改表),而载入公理只有这一处,谁也绕不过去。 | |
| 136 | + let pairs: Vec<(Uuid, Uuid)> = map | |
| 137 | + .iter() | |
| 138 | + .filter_map(|(id, ax)| ax.inverse_of.map(|inv| (inv, *id))) | |
| 139 | + .collect(); | |
| 140 | + for (target, source) in pairs { | |
| 141 | + // 已经声明了自己的逆就不动它——**人写的优先于推出来的**, | |
| 142 | + // 两边指得不一样是本体自己的矛盾,交给 R0 报,不在这里悄悄改 | |
| 143 | + map.entry(target) | |
| 144 | + .or_default() | |
| 145 | + .inverse_of | |
| 146 | + .get_or_insert(source); | |
| 147 | + } | |
| 148 | + Ok(map) | |
| 113 | 149 | } |
| 114 | 150 | |
| 115 | 151 | /// 跑一遍检查,把结果落库。 |
| @@ -365,6 +401,13 @@ | ||
| 365 | 401 | pub invalidated: usize, |
| 366 | 402 | /// 撞上单谓词上限、没推完的谓词个数 |
| 367 | 403 | pub capped: usize, |
| 404 | + /// **推出来了却找不到对应规则行的条数。正常应当恒为零。** | |
| 405 | + /// | |
| 406 | + /// 不为零意味着规则编译与推导对不上了。之前这里是一句 `continue`, | |
| 407 | + /// 于是 `ceo_of ⊑ works_at` 推出的那条 `works_at` 事实**推出来了却不落库**, | |
| 408 | + /// 而下游靠它推出的 `employs` 反倒进了库——一条派生的前提凭空消失。 | |
| 409 | + /// 数出来,别再让它静默一次 | |
| 410 | + pub unruled: usize, | |
| 368 | 411 | } |
| 369 | 412 | |
| 370 | 413 | /// 派生事实的身份:三元组 + 区间。 |
| @@ -413,6 +456,15 @@ | ||
| 413 | 456 | if a.symmetric { |
| 414 | 457 | want.push((pred, "symmetric")); |
| 415 | 458 | } |
| 459 | + // 后两种是 0017 补上的规则源。**规则挂在「有声明的那一侧」**—— | |
| 460 | + // 归一化过的逆两边都有声明,所以两个方向各得一条规则,与它们各自 | |
| 461 | + // 推出的派生对得上 | |
| 462 | + if a.inverse_of.is_some() { | |
| 463 | + want.push((pred, "inverse")); | |
| 464 | + } | |
| 465 | + if a.sub_property_of.is_some() { | |
| 466 | + want.push((pred, "sub_property")); | |
| 467 | + } | |
| 416 | 468 | } |
| 417 | 469 | want.sort(); |
| 418 | 470 | let mut out = HashMap::new(); |
| @@ -557,7 +609,14 @@ | ||
| 557 | 609 | } |
| 558 | 610 | |
| 559 | 611 | for ((subject, predicate, object, from, to), d) in wanted { |
| 560 | - let Some(&rule_id) = rules.get(&(predicate, d.rule.as_str())) else { | |
| 612 | + // **按 `via` 查,不是 `predicate`。** 规则行是给「声明了公理的那个 | |
| 613 | + // 谓词」编的;跨谓词的两条规则里,派生出来的谓词是另一个。 | |
| 614 | + // 原先按 predicate 查,前两条规则一直对(两者相同),加了 inverse / | |
| 615 | + // sub_property 之后查不到规则就 `continue`——推出来了却不落库 | |
| 616 | + let Some(&rule_id) = rules.get(&(d.via, d.rule.as_str())) else { | |
| 617 | + // 查不到规则是**编译与推导不一致**,不是正常情况。数出来, | |
| 618 | + // 别再让它静默消失一次 | |
| 619 | + report.unruled += 1; | |
| 561 | 620 | continue; |
| 562 | 621 | }; |
| 563 | 622 | // 精度与置信度都取前提里最保守的那一个 |
added crates/utopia-store/tests/a_relation_points_only_inside_its_own_kb.rs +340 −0
| @@ -0,0 +1,340 @@ | ||
| 1 | +//! `inverseOf` / `subPropertyOf` 的落库与边界——打在真库上。 | |
| 2 | +//! | |
| 3 | +//! **这里守的第一条是知识库隔离。** 列上的外键写的是 | |
| 4 | +//! `REFERENCES relation_types(id)`,它不认 `kb_id`:数据库层面,A 库的关系 | |
| 5 | +//! 完全可以指向 B 库的关系。RDF 导入那条路天然过不去(按 IRI 在本库里查), | |
| 6 | +//! 而 HTTP 接口收的是裸 UUID——挡不住的话,拿到任意一个 id 就能让推理机 | |
| 7 | +//! 跨库读公理,推出来的边会带着另一个库的语义落进这个库。 | |
| 8 | +//! | |
| 9 | +//! 前端只列本库的关系。**那是界面礼貌,不是边界**:接口自己收 UUID, | |
| 10 | +//! curl 一下就绕过去了。所以校验必须在 store 层,测试也必须在这里。 | |
| 11 | +//! | |
| 12 | +//! 其余三条是同一族的形状约束:属性没有逆(宾语是字面值,无从谈起)、 | |
| 13 | +//! 属性不能当别人的逆、子属性不能是自己(库里有 CHECK,但撞上去是 500, | |
| 14 | +//! 得在到达 CHECK 之前给出人话)。 | |
| 15 | + | |
| 16 | +use sqlx::PgPool; | |
| 17 | +use utopia_core::models::RelationAxioms; | |
| 18 | +use uuid::Uuid; | |
| 19 | + | |
| 20 | +/// 一个 org 底下两个库。**两个是必需的**——这组测试的主角就是跨库那条线。 | |
| 21 | +async fn two_kbs(pool: &PgPool) -> anyhow::Result<(Uuid, Uuid, Uuid)> { | |
| 22 | + let (org, ws, a, b) = ( | |
| 23 | + Uuid::now_v7(), | |
| 24 | + Uuid::now_v7(), | |
| 25 | + Uuid::now_v7(), | |
| 26 | + Uuid::now_v7(), | |
| 27 | + ); | |
| 28 | + sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'link-test')") | |
| 29 | + .bind(org) | |
| 30 | + .execute(pool) | |
| 31 | + .await?; | |
| 32 | + sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'link-test')") | |
| 33 | + .bind(ws) | |
| 34 | + .bind(org) | |
| 35 | + .execute(pool) | |
| 36 | + .await?; | |
| 37 | + for (id, name) in [(a, "link-a"), (b, "link-b")] { | |
| 38 | + sqlx::query("INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, $3)") | |
| 39 | + .bind(id) | |
| 40 | + .bind(ws) | |
| 41 | + .bind(name) | |
| 42 | + .execute(pool) | |
| 43 | + .await?; | |
| 44 | + } | |
| 45 | + Ok((org, a, b)) | |
| 46 | +} | |
| 47 | + | |
| 48 | +/// 建一条最普通的关系,不带任何链。 | |
| 49 | +async fn plain(pool: &PgPool, kb: Uuid, key: &str) -> anyhow::Result<Uuid> { | |
| 50 | + Ok(utopia_store::ontology::create_relation_type( | |
| 51 | + pool, | |
| 52 | + kb, | |
| 53 | + key, | |
| 54 | + key, | |
| 55 | + "state", | |
| 56 | + RelationAxioms::default(), | |
| 57 | + "", | |
| 58 | + "relation", | |
| 59 | + &[], | |
| 60 | + &[], | |
| 61 | + None, | |
| 62 | + None, | |
| 63 | + ) | |
| 64 | + .await?) | |
| 65 | +} | |
| 66 | + | |
| 67 | +#[tokio::test] | |
| 68 | +async fn a_relation_points_only_inside_its_own_kb() -> anyhow::Result<()> { | |
| 69 | + let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else { | |
| 70 | + eprintln!("跳过:未设 UTOPIA_DATABASE_URL"); | |
| 71 | + return Ok(()); | |
| 72 | + }; | |
| 73 | + let pool = PgPool::connect(&url).await?; | |
| 74 | + let (org, kb_a, kb_b) = two_kbs(&pool).await?; | |
| 75 | + | |
| 76 | + let run = async { | |
| 77 | + let works_at = plain(&pool, kb_a, "works_at").await?; | |
| 78 | + let employs = plain(&pool, kb_a, "employs").await?; | |
| 79 | + let ceo_of = plain(&pool, kb_a, "ceo_of").await?; | |
| 80 | + // 另一个库里的关系。名字取一样的——**同名不同库,正是最容易被当成 | |
| 81 | + // 自己人的那种** | |
| 82 | + let foreign = plain(&pool, kb_b, "employs").await?; | |
| 83 | + | |
| 84 | + // ---- 一、跨库指向:建的时候就该被拒 | |
| 85 | + let err = utopia_store::ontology::create_relation_type( | |
| 86 | + &pool, | |
| 87 | + kb_a, | |
| 88 | + "leaks", | |
| 89 | + "leaks", | |
| 90 | + "state", | |
| 91 | + RelationAxioms { | |
| 92 | + inverse_of: Some(foreign), | |
| 93 | + ..Default::default() | |
| 94 | + }, | |
| 95 | + "", | |
| 96 | + "relation", | |
| 97 | + &[], | |
| 98 | + &[], | |
| 99 | + None, | |
| 100 | + None, | |
| 101 | + ) | |
| 102 | + .await | |
| 103 | + .expect_err("指向别的知识库的关系必须被拒"); | |
| 104 | + assert!( | |
| 105 | + format!("{err:?}").contains("unknown_relation"), | |
| 106 | + "**拒绝的理由不能透露那个 id 存在于别处**——不区分「不存在」\ | |
| 107 | + 与「在别的库」,实得 {err:?}" | |
| 108 | + ); | |
| 109 | + let leaked: i64 = | |
| 110 | + sqlx::query_scalar("SELECT count(*) FROM relation_types WHERE kb_id = $1 AND key = $2") | |
| 111 | + .bind(kb_a) | |
| 112 | + .bind("leaks") | |
| 113 | + .fetch_one(&pool) | |
| 114 | + .await?; | |
| 115 | + assert_eq!(leaked, 0, "被拒的那次不该留下半行"); | |
| 116 | + | |
| 117 | + // ---- 二、跨库指向:改的时候同样该被拒 | |
| 118 | + let err = utopia_store::ontology::update_relation_type( | |
| 119 | + &pool, | |
| 120 | + kb_a, | |
| 121 | + works_at, | |
| 122 | + "works at", | |
| 123 | + "state", | |
| 124 | + RelationAxioms { | |
| 125 | + sub_property_of: Some(foreign), | |
| 126 | + ..Default::default() | |
| 127 | + }, | |
| 128 | + "", | |
| 129 | + None, | |
| 130 | + None, | |
| 131 | + None, | |
| 132 | + None, | |
| 133 | + ) | |
| 134 | + .await | |
| 135 | + .expect_err("改成指向别的知识库同样必须被拒"); | |
| 136 | + assert!( | |
| 137 | + format!("{err:?}").contains("unknown_relation"), | |
| 138 | + "实得 {err:?}" | |
| 139 | + ); | |
| 140 | + | |
| 141 | + // ---- 三、本库之内:写得进,也读得回 | |
| 142 | + utopia_store::ontology::update_relation_type( | |
| 143 | + &pool, | |
| 144 | + kb_a, | |
| 145 | + works_at, | |
| 146 | + "works at", | |
| 147 | + "state", | |
| 148 | + RelationAxioms { | |
| 149 | + inverse_of: Some(employs), | |
| 150 | + ..Default::default() | |
| 151 | + }, | |
| 152 | + "", | |
| 153 | + None, | |
| 154 | + None, | |
| 155 | + None, | |
| 156 | + None, | |
| 157 | + ) | |
| 158 | + .await?; | |
| 159 | + utopia_store::ontology::update_relation_type( | |
| 160 | + &pool, | |
| 161 | + kb_a, | |
| 162 | + ceo_of, | |
| 163 | + "ceo of", | |
| 164 | + "state", | |
| 165 | + RelationAxioms { | |
| 166 | + sub_property_of: Some(works_at), | |
| 167 | + ..Default::default() | |
| 168 | + }, | |
| 169 | + "", | |
| 170 | + None, | |
| 171 | + None, | |
| 172 | + None, | |
| 173 | + None, | |
| 174 | + ) | |
| 175 | + .await?; | |
| 176 | + let views = utopia_store::ontology::relation_type_views(&pool, kb_a).await?; | |
| 177 | + let find = |id: Uuid| views.iter().find(|v| v.id == id).expect("落库"); | |
| 178 | + assert_eq!( | |
| 179 | + find(works_at).inverse_of, | |
| 180 | + Some(employs), | |
| 181 | + "**视图必须回这两个值**——下拉框要显示当前选的是谁,\ | |
| 182 | + 读不回来的话打开表单是空的,保存一次就把声明抹了" | |
| 183 | + ); | |
| 184 | + assert_eq!(find(ceo_of).sub_property_of, Some(works_at)); | |
| 185 | + | |
| 186 | + // ---- 四、缺省 = 清空,与上面六位公理同一条规矩 | |
| 187 | + utopia_store::ontology::update_relation_type( | |
| 188 | + &pool, | |
| 189 | + kb_a, | |
| 190 | + works_at, | |
| 191 | + "works at", | |
| 192 | + "state", | |
| 193 | + RelationAxioms::default(), | |
| 194 | + "", | |
| 195 | + None, | |
| 196 | + None, | |
| 197 | + None, | |
| 198 | + None, | |
| 199 | + ) | |
| 200 | + .await?; | |
| 201 | + let views = utopia_store::ontology::relation_type_views(&pool, kb_a).await?; | |
| 202 | + assert_eq!( | |
| 203 | + views.iter().find(|v| v.id == works_at).unwrap().inverse_of, | |
| 204 | + None, | |
| 205 | + "不传 = 清空。一半覆盖一半保留,会让「我把逆去掉了」\ | |
| 206 | + 和「我没碰逆」长得一模一样" | |
| 207 | + ); | |
| 208 | + | |
| 209 | + // ---- 五、属性:不能有链,也不能当链的目标 | |
| 210 | + let salary = utopia_store::ontology::create_relation_type( | |
| 211 | + &pool, | |
| 212 | + kb_a, | |
| 213 | + "salary", | |
| 214 | + "salary", | |
| 215 | + "state", | |
| 216 | + RelationAxioms::default(), | |
| 217 | + "", | |
| 218 | + "attribute", | |
| 219 | + // 属性至少要挂一个类,这里借用一个现成的类 | |
| 220 | + &[class(&pool, kb_a).await?], | |
| 221 | + &[], | |
| 222 | + Some("number"), | |
| 223 | + None, | |
| 224 | + ) | |
| 225 | + .await?; | |
| 226 | + let err = utopia_store::ontology::update_relation_type( | |
| 227 | + &pool, | |
| 228 | + kb_a, | |
| 229 | + ceo_of, | |
| 230 | + "ceo of", | |
| 231 | + "state", | |
| 232 | + RelationAxioms { | |
| 233 | + inverse_of: Some(salary), | |
| 234 | + ..Default::default() | |
| 235 | + }, | |
| 236 | + "", | |
| 237 | + None, | |
| 238 | + None, | |
| 239 | + None, | |
| 240 | + None, | |
| 241 | + ) | |
| 242 | + .await | |
| 243 | + .expect_err("属性不能当逆——它的宾语是字面值,反过来指回来无从谈起"); | |
| 244 | + assert!( | |
| 245 | + format!("{err:?}").contains("link_target_is_attr"), | |
| 246 | + "实得 {err:?}" | |
| 247 | + ); | |
| 248 | + let err = utopia_store::ontology::update_relation_type( | |
| 249 | + &pool, | |
| 250 | + kb_a, | |
| 251 | + salary, | |
| 252 | + "salary", | |
| 253 | + "state", | |
| 254 | + RelationAxioms { | |
| 255 | + sub_property_of: Some(ceo_of), | |
| 256 | + ..Default::default() | |
| 257 | + }, | |
| 258 | + "", | |
| 259 | + None, | |
| 260 | + None, | |
| 261 | + None, | |
| 262 | + None, | |
| 263 | + ) | |
| 264 | + .await | |
| 265 | + .expect_err("属性自己也不能有父属性"); | |
| 266 | + assert!( | |
| 267 | + format!("{err:?}").contains("attr_has_no_link"), | |
| 268 | + "实得 {err:?}" | |
| 269 | + ); | |
| 270 | + | |
| 271 | + // ---- 六、子属性不能是自己。**库里有 CHECK,但那是 500** | |
| 272 | + let err = utopia_store::ontology::update_relation_type( | |
| 273 | + &pool, | |
| 274 | + kb_a, | |
| 275 | + ceo_of, | |
| 276 | + "ceo of", | |
| 277 | + "state", | |
| 278 | + RelationAxioms { | |
| 279 | + sub_property_of: Some(ceo_of), | |
| 280 | + ..Default::default() | |
| 281 | + }, | |
| 282 | + "", | |
| 283 | + None, | |
| 284 | + None, | |
| 285 | + None, | |
| 286 | + None, | |
| 287 | + ) | |
| 288 | + .await | |
| 289 | + .expect_err("自己不能是自己的父属性"); | |
| 290 | + assert!( | |
| 291 | + format!("{err:?}").contains("sub_property_self"), | |
| 292 | + "得在撞上 CHECK 之前给出人话,而不是让人看到一个 500,实得 {err:?}" | |
| 293 | + ); | |
| 294 | + | |
| 295 | + // 逆是自己**不拦**:那等于 symmetric,是合法声明。 | |
| 296 | + // R0 会提示改用 `symmetric` 更直白,但那是提示不是错误 | |
| 297 | + utopia_store::ontology::update_relation_type( | |
| 298 | + &pool, | |
| 299 | + kb_a, | |
| 300 | + employs, | |
| 301 | + "employs", | |
| 302 | + "state", | |
| 303 | + RelationAxioms { | |
| 304 | + inverse_of: Some(employs), | |
| 305 | + ..Default::default() | |
| 306 | + }, | |
| 307 | + "", | |
| 308 | + None, | |
| 309 | + None, | |
| 310 | + None, | |
| 311 | + None, | |
| 312 | + ) | |
| 313 | + .await?; | |
| 314 | + | |
| 315 | + Ok::<_, anyhow::Error>(()) | |
| 316 | + } | |
| 317 | + .await; | |
| 318 | + | |
| 319 | + sqlx::query("DELETE FROM organizations WHERE id = $1") | |
| 320 | + .bind(org) | |
| 321 | + .execute(&pool) | |
| 322 | + .await?; | |
| 323 | + let _ = kb_b; | |
| 324 | + run | |
| 325 | +} | |
| 326 | + | |
| 327 | +/// 借一个类给属性当 domain——属性没有类就建不出来。 | |
| 328 | +async fn class(pool: &PgPool, kb: Uuid) -> anyhow::Result<Uuid> { | |
| 329 | + Ok(utopia_store::ontology::create_entity_type( | |
| 330 | + pool, | |
| 331 | + kb, | |
| 332 | + "person", | |
| 333 | + "Person", | |
| 334 | + "#888888", | |
| 335 | + "circle", | |
| 336 | + &[], | |
| 337 | + "", | |
| 338 | + ) | |
| 339 | + .await?) | |
| 340 | +} |
added migrations/0016_a_relation_can_name_its_inverse.sql +52 −0
| @@ -0,0 +1,52 @@ | ||
| 1 | +-- 关系的逆与父属性(R1 的后两种规则源,见 docs/decisions/0002)。 | |
| 2 | +-- | |
| 3 | +-- ADR 0002 给 R1 定的规则来源是四种:`TransitiveProperty` / `SymmetricProperty` / | |
| 4 | +-- `inverseOf` / `subPropertyOf`。前两种一直在跑,后两种**连列都没有**—— | |
| 5 | +-- 0013 的 `rules.kind` 注释把这件事记下来了: | |
| 6 | +-- | |
| 7 | +-- > `inverseOf` 与 `subPropertyOf` 投影侧还没落库,所以也就编不出来 | |
| 8 | +-- | |
| 9 | +-- 这条迁移补上投影侧。缺的后果不是「少推几条」,是**答案不对称**:本体声明了 | |
| 10 | +-- `works_at⁻¹ = employs`,而问「谁在 Acme 工作」和「Acme 雇了谁」会得到不同答案, | |
| 11 | +-- 除非两个方向都被断言过——那正是 R1 该消灭的重复劳动。 | |
| 12 | +ALTER TABLE relation_types | |
| 13 | + -- `p⁻¹ = q`。**单向存,双向用。** | |
| 14 | + -- | |
| 15 | + -- 不加触发器去自动回填 `q.inverse_of = p`:那会把一条语义规则藏进数据库, | |
| 16 | + -- 而绕过它的路不止一条(RDF 导入、直接 SQL)。改在读取公理时归一化—— | |
| 17 | + -- 载入那一处认这件事,绕不过去,也测得动(`reasoning::axioms_of`)。 | |
| 18 | + ADD COLUMN inverse_of UUID REFERENCES relation_types(id) ON DELETE SET NULL, | |
| 19 | + -- `p ⊑ q`:断言了具体的,通用的也成立(`ceo_of ⊑ works_at`)。 | |
| 20 | + -- 链要防成环,R0 那边加检查——与 `entity_types` 的父类环是同一类问题 | |
| 21 | + ADD COLUMN sub_property_of UUID REFERENCES relation_types(id) ON DELETE SET NULL; | |
| 22 | + | |
| 23 | +-- 自己不能是自己的父属性。**自己可以是自己的逆**——那等于对称, | |
| 24 | +-- 是合法的声明(R0 会提示改用 `symmetric` 更直白,但不算错) | |
| 25 | +ALTER TABLE relation_types | |
| 26 | + ADD CONSTRAINT relation_types_sub_property_not_self | |
| 27 | + CHECK (sub_property_of IS NULL OR sub_property_of <> id); | |
| 28 | + | |
| 29 | +-- 归一化要按「谁指着我」反查,编译规则时每个谓词问一次 | |
| 30 | +CREATE INDEX relation_types_inverse_idx ON relation_types (inverse_of) | |
| 31 | + WHERE inverse_of IS NOT NULL; | |
| 32 | +CREATE INDEX relation_types_sub_property_idx ON relation_types (sub_property_of) | |
| 33 | + WHERE sub_property_of IS NOT NULL; | |
| 34 | + | |
| 35 | +-- 两处 CHECK 跟着放开:新规则与新缺陷都是 0013 那两张表没预见到的取值。 | |
| 36 | +-- | |
| 37 | +-- **不是补漏,是那时确实还没有。** 0013 的注释写着「`inverseOf` 与 | |
| 38 | +-- `subPropertyOf` 投影侧还没落库,所以也就编不出来」——这条迁移补上投影侧, | |
| 39 | +-- 约束自然要跟着扩。 | |
| 40 | +ALTER TABLE rules DROP CONSTRAINT IF EXISTS rules_kind_check; | |
| 41 | +ALTER TABLE rules ADD CONSTRAINT rules_kind_check | |
| 42 | + CHECK (kind IN ('transitive', 'symmetric', 'inverse', 'sub_property')); | |
| 43 | + | |
| 44 | +-- 三条新的本体自检:自己是自己的逆(等于 symmetric,提示改写)、 | |
| 45 | +-- 逆没指回来(载入时只补空缺不覆盖,所以矛盾留到这里报)、子属性成环 | |
| 46 | +ALTER TABLE ontology_defects DROP CONSTRAINT IF EXISTS ontology_defects_kind_check; | |
| 47 | +ALTER TABLE ontology_defects ADD CONSTRAINT ontology_defects_kind_check | |
| 48 | + CHECK (kind IN ( | |
| 49 | + 'symmetric_and_asymmetric', 'transitive_and_functional', | |
| 50 | + 'subclass_cycle', 'disjoint_with_ancestor', 'inherits_disjoint', | |
| 51 | + 'inverse_of_itself', 'inverse_not_mutual', 'sub_property_cycle' | |
| 52 | + )); |