Skip to content

World's first open-source enterprise world model.

A rule reads what a rule concluded (#485)

WaylandYangcb2bab701cbf
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index be424d07..e7400ec4 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -1139,14 +1139,19 @@ pub struct BlockedDerivation {
pub premises: Vec<Uuid>,
}
-/// 证明的一步:一条断言前提,连同它的证据(0002 R2)。
+/// 证明的一步:一条前提,连同它的证据(0002 R2)。
///
-/// 前提一律是断言(`fact_derivations` 不记派生),所以证明是一条链而不是一棵树:
-/// 派生 → 按 `seq` 排好的断言 → 每条断言的原句。叶子就是 chunk。
+/// 前提要么是断言——叶子就是它的原句(chunk)——要么是**另一条派生**(0030),
+/// 那一步的证据是它自己的前提,在 `premises` 里再往下一层。所以证明是一棵树,
+/// 深度与推理同一条上限。
#[derive(Debug, Clone, Serialize)]
pub struct ProofStep {
pub seq: i32,
+ /// 断言时是 `facts.id`,派生时是 `derived_facts.id`——看 `derived`
pub fact_id: Uuid,
+ /// 这一步自己是推出来的(0030)。**界面要分得出**:一条推出来的前提与
+ /// 一条读来的前提在句子上长得一样,而它们能不能追到原文完全不同
+ pub derived: bool,
pub subject_id: Uuid,
pub subject: String,
pub predicate_id: Option<Uuid>,
@@ -1161,6 +1166,9 @@ pub struct ProofStep {
/// 这条前提后来被撤了。派生随之失效,但证明还要读得出「当时靠的是什么」
pub retracted: bool,
pub evidence: Vec<EvidenceView>,
+ /// 这一步自己的前提,按 `seq`(0030)。断言那一步是空的——它的叶子是
+ /// `evidence` 里的原句,不必再往下问
+ pub premises: Vec<ProofStep>,
}
/// 一条派生事实的完整证明:它本身,加上按顺序展开到原句的前提。
diff --git a/crates/utopia-server/src/api/rule_routes.rs b/crates/utopia-server/src/api/rule_routes.rs
index 0ebfbafa..afcbea5b 100644
--- a/crates/utopia-server/src/api/rule_routes.rs
+++ b/crates/utopia-server/src/api/rule_routes.rs
@@ -196,5 +196,9 @@ pub async fn run_now(
"capped": report.rule_capped,
"inserted": report.inserted,
"invalidated": report.invalidated,
+ // 链跑了几轮,以及有没有跑满上限就停(0030)。**跑满得说出来**——
+ // 没接上的那一环与「不满足」在结果里长得一模一样
+ "rounds": report.rule_rounds,
+ "rounds_capped": report.rule_rounds_capped,
})))
}
diff --git a/crates/utopia-server/src/rdf.rs b/crates/utopia-server/src/rdf.rs
index 3cbcc831..f48a3d80 100644
--- a/crates/utopia-server/src/rdf.rs
+++ b/crates/utopia-server/src/rdf.rs
@@ -960,6 +960,7 @@ mod tests {
rule: "business".into(),
rule_name: Some("Gas-bearing well".into()),
premises: vec![id(5)],
+ premises_derived: Vec::new(),
};
let quads = export(Format::Turtle, |sink, names, vocab| {
emit_derived(sink, names, vocab, &derived).unwrap();
@@ -1023,6 +1024,7 @@ mod tests {
rule: "transitive".into(),
rule_name: None,
premises: vec![id(5)],
+ premises_derived: Vec::new(),
};
let quads = export(Format::Turtle, |sink, names, vocab| {
emit_derived(sink, names, vocab, &derived).unwrap();
diff --git a/crates/utopia-store/src/business_rules.rs b/crates/utopia-store/src/business_rules.rs
index 295feb56..fcc5276c 100644
--- a/crates/utopia-store/src/business_rules.rs
+++ b/crates/utopia-store/src/business_rules.rs
@@ -396,11 +396,11 @@ pub async fn matches(
COALESCE(
(SELECT array_agg(
COALESCE(pr.label, '?') || ' = '
- || COALESCE(pf.object_value #>> '{value}', '?')
+ || COALESCE(fd.object_value #>> '{value}',
+ fd.object_value #>> '{class}', '?')
ORDER BY fd.seq)
- FROM fact_derivations fd
- JOIN facts pf ON pf.id = fd.premise_fact_id
- LEFT JOIN relation_types pr ON pr.id = pf.predicate_id
+ FROM derivation_premises fd
+ LEFT JOIN relation_types pr ON pr.id = fd.predicate_id
WHERE fd.derived_fact_id = d.id),
ARRAY[]::text[]
)
diff --git a/crates/utopia-store/src/export.rs b/crates/utopia-store/src/export.rs
index 762dbbad..06b688fd 100644
--- a/crates/utopia-store/src/export.rs
+++ b/crates/utopia-store/src/export.rs
@@ -106,6 +106,9 @@ pub struct ExportDerived {
pub rule_name: Option<String>,
/// 前提事实。审计要顺着它往下走到句子
pub premises: Vec<Uuid>,
+ /// 前提里是**另一条派生**的那些(0030)。与上面那列分开,是因为读回来的人
+ /// 要知道该去哪张表接着往下走;合成一列的话,一条链在导出里就断了
+ pub premises_derived: Vec<Uuid>,
}
#[derive(Debug, Clone, sqlx::FromRow)]
@@ -217,7 +220,13 @@ pub async fn derived_page(
d.derived_at, d.invalidated_at, d.confidence,
COALESCE(ru.kind, 'business') AS rule, ar.name AS rule_name,
COALESCE(ARRAY(SELECT fd.premise_fact_id FROM fact_derivations fd
- WHERE fd.derived_fact_id = d.id ORDER BY fd.seq), '{}') AS premises
+ WHERE fd.derived_fact_id = d.id
+ AND fd.premise_fact_id IS NOT NULL
+ ORDER BY fd.seq), '{}') AS premises,
+ COALESCE(ARRAY(SELECT fd.premise_derived_id FROM fact_derivations fd
+ WHERE fd.derived_fact_id = d.id
+ AND fd.premise_derived_id IS NOT NULL
+ ORDER BY fd.seq), '{}') AS premises_derived
FROM derived_facts d
LEFT JOIN rules ru ON ru.id = d.rule_id
LEFT JOIN attribute_rules ar ON ar.id = d.attribute_rule_id
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs
index 7b876971..e327e2cb 100644
--- a/crates/utopia-store/src/graph.rs
+++ b/crates/utopia-store/src/graph.rs
@@ -714,7 +714,9 @@ async fn edges_among(
r.key AS predicate, r.label AS label,
FALSE AS inferred, TRUE AS derived, ru.kind AS rule,
ARRAY(SELECT fd.premise_fact_id FROM fact_derivations fd
- WHERE fd.derived_fact_id = d.id ORDER BY fd.seq) AS premises,
+ WHERE fd.derived_fact_id = d.id
+ AND fd.premise_fact_id IS NOT NULL
+ ORDER BY fd.seq) AS premises,
d.valid_from, d.valid_to,
d.valid_from AS holds_from, d.valid_to AS holds_to, d.confidence,
FALSE AS contested, FALSE AS blocked
diff --git a/crates/utopia-store/src/reasoning.rs b/crates/utopia-store/src/reasoning.rs
index 2ba7d2ee..3514f240 100644
--- a/crates/utopia-store/src/reasoning.rs
+++ b/crates/utopia-store/src/reasoning.rs
@@ -832,6 +832,97 @@ pub struct DeriveReport {
pub rule_hits: usize,
/// 前提组合太多、没展开完的 (规则, 实体) 对数。**与「不满足」区分开报**
pub rule_capped: usize,
+ /// 业务规则跑了几轮(0030)。一轮的结论进下一轮的输入,直到某一轮不再
+ /// 产出新的结论。链上一环一轮,所以 1 就是「没有链」,2 就是 `A → B`
+ pub rule_rounds: usize,
+ /// 跑满 `MAX_DEPTH` 轮还在产出:链比上限长,后面的没接上。**与「不满足」
+ /// 区分开报**——没推到与不成立在结果里长得一模一样
+ pub rule_rounds_capped: bool,
+ /// 结论没变、证明变了、于是重写了前提链的行数(0030)。同一句话可以有
+ /// 第二条依据,而对账的键里没有前提——不重写的话那一行会一直挂着上一轮
+ /// 的理由,链上还可能挂着一条刚刚作废的前提
+ pub reproved: usize,
+}
+
+/// 一条派生从它的前提上得到的精度与置信度(0024)。
+///
+/// **抽出来是因为链**(0030):链中间那一层既要拿它算自己的两端,又要作为
+/// 下一层的前提被同一段代码读一遍。落库那一处与不动点那一处各写一份的话,
+/// 两处对「哪一端是锚点顶上来的」的判断迟早会长得不一样。
+///
+/// 精度跟着**赢下这一端的那条前提**走:派生的起点就是前提里最晚的那个起点,
+/// 它的精度就是那条前提的精度。几条前提并列时取其中最粗的;那一端若是某条
+/// 前提的**锚点**顶上来的(0022),没有精度可言。
+fn premise_meta(
+ premises: &[Uuid],
+ from: Option<i64>,
+ to: Option<i64>,
+ spans: &HashMap<Uuid, (Option<i64>, Option<i64>)>,
+ meta: &HashMap<Uuid, PremiseMeta>,
+) -> PremiseMeta {
+ let mut fp: Option<String> = None;
+ let mut tp: Option<String> = None;
+ let mut conf = 1.0f32;
+ let mut from_anchored = false;
+ let mut to_anchored = false;
+ for p in premises {
+ let Some((pf, pt, pc, fa, ta)) = meta.get(p) else {
+ continue;
+ };
+ // 置信度取前提里最低的:一条链只和它最弱的一环一样可信
+ conf = conf.min(*pc);
+ let Some((sf, st)) = spans.get(p) else {
+ continue;
+ };
+ if from.is_some() && *sf == from {
+ if *fa {
+ from_anchored = true;
+ } else {
+ fp = coarsest(fp.as_deref(), pf.as_deref());
+ }
+ }
+ if to.is_some() && *st == to {
+ if *ta {
+ to_anchored = true;
+ } else {
+ // 'unknown' 不是粒度,是「结束了不知哪天」的标记;它顶上来的
+ // 那一端是锚点,走上面那条路
+ tp = coarsest(
+ tp.as_deref(),
+ pt.as_deref().filter(|p| *p != crate::graph::ENDED_UNKNOWN),
+ );
+ }
+ }
+ }
+ (fp, tp, conf, from_anchored, to_anchored)
+}
+
+/// 主类靠**派生归类**才够得着的那一份规则:范围从筛子变成一条条件(0030)。
+///
+/// `范围 与 ((A 且 B) 或 C)` 展开就是 `(范围且A且B) 或 (范围且C)`——所以每组
+/// 各加一条,析取仍然只有一层(0029)。写成条件而不是筛子,是为了让归类那条
+/// 派生事实进前提:结论的区间跟着它收窄,它作废时结论也跟着退场。
+fn scoped_by_conclusion(
+ rule: &utopia_reason::rules::BusinessRule,
+ is_a: Uuid,
+ classes: &[String],
+) -> utopia_reason::rules::BusinessRule {
+ use utopia_reason::rules::{Condition, Op, Operand};
+ let groups: std::collections::BTreeSet<i32> = rule.conditions.iter().map(|c| c.group).collect();
+ let mut conditions = rule.conditions.clone();
+ for group in groups {
+ conditions.push(Condition {
+ group,
+ predicate: is_a,
+ op: Op::In,
+ operand: Operand::Set(classes.to_vec()),
+ });
+ }
+ utopia_reason::rules::BusinessRule {
+ id: rule.id,
+ conclusion: rule.conclusion.clone(),
+ conditions,
+ }
}
/// 一次取数,三样东西:带区间的边、每条事实的区间、精度与置信度。
@@ -994,6 +1085,10 @@ async fn accepted_clashes(
/// 宾语两格,与 `derived_facts` 拓宽后的两条通道一一对应(0021 决策 1):实体宾语
/// 走 `Option<Uuid>`,字面值结论走那串规范化过的 JSON。两格都参与比较——否则
/// 同一个类上的两条不同结论会被认成同一条。
+/// 一条前提在 `fact_derivations` 上的两格(0030):断言一格、派生一格,
+/// 恰好一个有值——数据库那条 CHECK 说的就是这句
+type PremiseCols = (Option<Uuid>, Option<Uuid>);
+
type DerivedKey = (
Uuid,
Uuid,
@@ -1136,10 +1231,23 @@ struct LoadedRule {
rule: utopia_reason::rules::BusinessRule,
/// 规则只看这个类**及其子类**的实体
subject_types: Vec<Uuid>,
+ /// 上面那几个类的名字(IRI,没有才 key)。派生归类记的是名字,主类范围记的
+ /// 是 id——链要接上就得两边都有一份(0030)
+ subject_classes: Vec<String>,
/// 结论落在哪个谓词上:归类落 `is_a`,属性落它自己那个
conclude_predicate: Uuid,
}
+/// 编译出来的一批规则,外加接链要用的两样东西(0030)。
+struct LoadedRules {
+ rules: Vec<LoadedRule>,
+ /// 内建 `is_a`。派生归类落在它上面,链上再读回来也从它上面读
+ is_a: Option<Uuid>,
+ /// 类名(IRI,没有才 key)→ 类 id。一条派生归类要变成「这个实体属于哪个类」,
+ /// 必须走这一步
+ class_ids: HashMap<String, Uuid>,
+}
+
/// 求值要用的一行规则:id、主类、结论种类、结论那三格,外加结论类的 IRI 与 key
/// (归类结论按 IRI 记,没有才退回 key)
type RuleDefRow = (
@@ -1155,22 +1263,45 @@ type RuleDefRow = (
/// 取业务规则。条件形状不合法的规则**整条跳过而不是报错退出**——一条写坏的
/// 规则不该让整轮物化停摆,而它不产出这件事在报告的条数里看得见。
-async fn attribute_rules(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<LoadedRule>> {
+async fn attribute_rules(pool: &PgPool, kb_id: Uuid) -> AppResult<LoadedRules> {
use utopia_reason::rules::{BusinessRule, Conclusion, Condition, Op};
+ // **按 id 排序**:规则之间撞上同一个结论时留下的是先到的那条证明,而
+ // 「先到」不该由 HashMap 的顺序决定——同一个库两次物化要给出同一份证明
+ // (0029 在组之间讲的是同一件事,0030 让链把它放大了)
let rows: Vec<RuleDefRow> = sqlx::query_as(
"SELECT r.id, r.subject_type_id, r.conclusion,
r.conclude_type_id, r.conclude_predicate_id, r.conclude_value,
ct.iri, ct.key
FROM attribute_rules r
LEFT JOIN entity_types ct ON ct.id = r.conclude_type_id
- WHERE r.kb_id = $1 AND r.enabled",
+ WHERE r.kb_id = $1 AND r.enabled
+ ORDER BY r.id",
)
.bind(kb_id)
.fetch_all(pool)
.await?;
if rows.is_empty() {
- return Ok(Vec::new());
+ return Ok(LoadedRules {
+ rules: Vec::new(),
+ is_a: None,
+ class_ids: HashMap::new(),
+ });
+ }
+
+ // 类名 ↔ 类 id,两个方向各一份:归类结论按名字记(改标签不该让已推出的结论
+ // 变成另一条,0021 决策 2),而主类范围与实体的类都是 id
+ let type_rows: Vec<(Uuid, Option<String>, Option<String>)> =
+ sqlx::query_as("SELECT id, iri, key FROM entity_types WHERE kb_id = $1")
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?;
+ let mut class_ids: HashMap<String, Uuid> = HashMap::new();
+ let mut class_name: HashMap<Uuid, String> = HashMap::new();
+ for (id, iri, key) in type_rows {
+ let Some(name) = iri.or(key) else { continue };
+ class_ids.insert(name.clone(), id);
+ class_name.insert(id, name);
}
// 归类结论要落在内建 `is_a` 上。规则存在就意味着它已经被建出来了
@@ -1247,6 +1378,10 @@ async fn attribute_rules(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<LoadedRule
_ => continue,
};
let subject_types = descendants_of(pool, kb_id, subject_type).await?;
+ let subject_classes = subject_types
+ .iter()
+ .filter_map(|t| class_name.get(t).cloned())
+ .collect();
out.push(LoadedRule {
rule: BusinessRule {
id,
@@ -1254,10 +1389,15 @@ async fn attribute_rules(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<LoadedRule
conditions,
},
subject_types,
+ subject_classes,
conclude_predicate: predicate,
});
}
- Ok(out)
+ Ok(LoadedRules {
+ rules: out,
+ is_a: is_a.map(|(id,)| id),
+ class_ids,
+ })
}
/// 操作数按 op 解析。形状不对返回 None,调用方整条规则跳过。
@@ -1473,46 +1613,93 @@ pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport>
// 下面的陈旧对账扫的是整张 `derived_facts`,两趟各做各的 diff 会把对方
// 落的行每一轮都判成陈旧
let loaded = attribute_rules(pool, kb_id).await?;
- report.attribute_rules = loaded.len();
- if !loaded.is_empty() {
- let (attr_facts, attr_spans, attr_meta, type_of) = attribute_facts(pool, kb_id).await?;
- for lr in &loaded {
- // 规则只看自己主类(含子类)的实体
- let scoped: Vec<utopia_reason::rules::AttrFact> = attr_facts
- .iter()
- .filter(|f| {
- type_of
+ report.attribute_rules = loaded.rules.len();
+ // 一条规则结论的临时 id → 它最后落在哪一行。链上的前提指的是前者,
+ // `fact_derivations` 要存的是后者(0030)。键是派生键,值是临时 id
+ let mut provisional: HashMap<DerivedKey, Uuid> = HashMap::new();
+ if !loaded.rules.is_empty() {
+ let (asserted, attr_spans, attr_meta, type_of) = attribute_facts(pool, kb_id).await?;
+ // 前提的精度与置信度:落地那一段与不动点这一段共用,所以两份 meta 先合起来;
+ // 区间也要——认出派生的哪一端是被前提的锚点顶上来的,靠的就是它
+ meta.extend(attr_meta);
+ spans.extend(attr_spans);
+
+ // ---- 不动点:这一轮的结论进下一轮的输入(0030)
+ //
+ // **全量重跑而不是半朴素**:链通常只有一两环,收敛靠「这一轮没产出新键」
+ // 那一下,真实代价是单趟的两三倍。半朴素要维护每条规则读哪些谓词,
+ // 为一个两三轮的循环换一份索引,不划算。
+ //
+ // 输入侧一行 `derived_facts` 都不读:反馈全在这个内存池子里,一次物化
+ // 仍然是 (facts, rules, axioms) 的纯函数——0013 那条反对意见守的是这个
+ let mut fact_pool = asserted;
+ // 每个实体被**推**出来的类。断言的类在 `type_of` 里,两者进规则的方式
+ // 不一样:断言的类没有区间,是个筛子;推出来的类有区间,得当条件
+ let mut derived_types: HashMap<Uuid, Vec<Uuid>> = HashMap::new();
+ let mut capped_by_rule: HashMap<Uuid, usize> = HashMap::new();
+ let mut rounds = 0usize;
+ for _ in 0..utopia_reason::MAX_DEPTH {
+ rounds += 1;
+ // 一轮之内先算完再入池:同一轮里规则读到的是上一轮结束时的池子,
+ // 谁先谁后就不影响结果
+ let mut fresh: Vec<(usize, utopia_reason::rules::RuleHit)> = Vec::new();
+ capped_by_rule.clear();
+ for (ri, lr) in loaded.rules.iter().enumerate() {
+ // 主类是断言的:范围是个筛子,不带区间、不进前提
+ let mut by_assertion: Vec<utopia_reason::rules::AttrFact> = Vec::new();
+ // 只靠派生归类够得着的:范围变成一个条件(下面那段)
+ let mut by_conclusion: Vec<utopia_reason::rules::AttrFact> = Vec::new();
+ for f in &fact_pool {
+ if type_of
.get(&f.subject)
.and_then(|t| *t)
.is_some_and(|t| lr.subject_types.contains(&t))
- })
- .cloned()
- .collect();
- let (hits, rr) = utopia_reason::rules::evaluate(
- std::slice::from_ref(&lr.rule),
- &scoped,
- &attr_spans,
- );
- report.rule_hits += rr.hits;
- // 展不完的组合数按规则写回:这个数字在卡片上常驻,而不只在
- // 「跑完那一刻」的提示里闪一下(少推几条与「不满足」长得一样)
- sqlx::query("UPDATE attribute_rules SET capped_at_last_run = $2 WHERE id = $1")
- .bind(lr.rule.id)
- .bind(rr.capped as i32)
- .execute(pool)
- .await?;
- // 是「这一轮算出来的派生总数」,公理与规则都算在内。
- // **别改写它的原义**:被拦下的那些也算「算出来了」,队列里那一行
- // 正是凭它对上的
- report.derived += rr.hits;
- report.rule_capped += rr.capped;
- for h in hits {
- let value = match &lr.rule.conclusion {
- utopia_reason::rules::Conclusion::Typing { class } => {
- serde_json::json!({ "class": class })
+ {
+ by_assertion.push(f.clone());
+ } else if derived_types
+ .get(&f.subject)
+ .is_some_and(|ts| ts.iter().any(|t| lr.subject_types.contains(t)))
+ {
+ by_conclusion.push(f.clone());
+ }
+ }
+ let (hits, rr) = utopia_reason::rules::evaluate(
+ std::slice::from_ref(&lr.rule),
+ &by_assertion,
+ &spans,
+ );
+ let mut capped = rr.capped;
+ fresh.extend(hits.into_iter().map(|h| (ri, h)));
+
+ // 主类是推出来的那一份:**范围写成一条条件**,而不是再当筛子。
+ // 归类那条派生事实因此进了前提,区间跟着它收窄(一个实体
+ // 2019–2022 是 B,就不该拿 2024 的读数满足一条 B 上的规则),
+ // 它作废时这条结论也就跟着退场——这一条不用另写代码
+ if !by_conclusion.is_empty() {
+ if let (Some(is_a), false) = (loaded.is_a, lr.subject_classes.is_empty()) {
+ let scoped = scoped_by_conclusion(&lr.rule, is_a, &lr.subject_classes);
+ let (h2, rr2) = utopia_reason::rules::evaluate(
+ std::slice::from_ref(&scoped),
+ &by_conclusion,
+ &spans,
+ );
+ capped += rr2.capped;
+ fresh.extend(h2.into_iter().map(|h| (ri, h)));
}
+ }
+ *capped_by_rule.entry(lr.rule.id).or_default() += capped;
+ }
+
+ let before = provisional.len();
+ for (ri, h) in fresh {
+ let lr = &loaded.rules[ri];
+ let (value, inner) = match &lr.rule.conclusion {
+ utopia_reason::rules::Conclusion::Typing { class } => (
+ serde_json::json!({ "class": class }),
+ serde_json::Value::String(class.clone()),
+ ),
utopia_reason::rules::Conclusion::Attribute { value, .. } => {
- serde_json::json!({ "value": value })
+ (serde_json::json!({ "value": value }), value.clone())
}
};
let key = (
@@ -1523,23 +1710,68 @@ pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport>
h.from,
h.to,
);
- wanted.entry(key).or_insert(Wanted {
+ // 上一轮已经推出过同一条:不再进池子,也就不会再进 frontier。
+ // 自反馈的环正是在这里停下的——它推出的是同一个键
+ if wanted.contains_key(&key) {
+ continue;
+ }
+ // 临时 id:这一条现在就要当事实用,可它落在哪一行要等对账之后
+ // 才知道(不变的结论保留原来那一行)。落库前统一换过来
+ let prov = Uuid::now_v7();
+ let pm = premise_meta(&h.premises, h.from, h.to, &spans, &meta);
+ spans.insert(prov, (h.from, h.to));
+ meta.insert(prov, pm);
+ fact_pool.push(utopia_reason::rules::AttrFact {
+ id: prov,
subject: h.subject,
predicate: lr.conclude_predicate,
- object_id: None,
- object_value: Some(value),
- from: h.from,
- to: h.to,
- premises: h.premises,
- rule_id: None,
- attribute_rule_id: Some(lr.rule.id),
+ value: inner,
});
+ if let utopia_reason::rules::Conclusion::Typing { class } = &lr.rule.conclusion {
+ if let Some(&t) = loaded.class_ids.get(class) {
+ derived_types.entry(h.subject).or_default().push(t);
+ }
+ }
+ provisional.insert(key.clone(), prov);
+ wanted.insert(
+ key,
+ Wanted {
+ subject: h.subject,
+ predicate: lr.conclude_predicate,
+ object_id: None,
+ object_value: Some(value),
+ from: h.from,
+ to: h.to,
+ premises: h.premises,
+ rule_id: None,
+ attribute_rule_id: Some(lr.rule.id),
+ },
+ );
+ }
+ // 这一轮什么新东西都没推出来:不动点到了
+ if provisional.len() == before {
+ break;
}
}
- // 前提的精度与置信度:两趟共用下面那段,所以两份 meta 也要合起来;
- // 区间也要——落地时要对着前提的区间认出派生的哪一端是锚点顶上的
- meta.extend(attr_meta);
- spans.extend(attr_spans);
+ report.rule_rounds = rounds;
+ // 跑满了轮数还在产出:链比 MAX_DEPTH 长,后面的没接上。**得报出来**——
+ // 「没推到」与「不满足」在结果里长得一模一样(组合封顶那条是同一个道理)
+ report.rule_rounds_capped = rounds == utopia_reason::MAX_DEPTH;
+ for lr in &loaded.rules {
+ // 展不完的组合数按规则写回:这个数字在表里常驻,而不只在「跑完那一刻」
+ // 的提示里闪一下。取最后一轮的数——那一轮扫的是最全的池子
+ let capped = capped_by_rule.get(&lr.rule.id).copied().unwrap_or(0);
+ sqlx::query("UPDATE attribute_rules SET capped_at_last_run = $2 WHERE id = $1")
+ .bind(lr.rule.id)
+ .bind(capped as i32)
+ .execute(pool)
+ .await?;
+ report.rule_capped += capped;
+ }
+ // 命中数按**不同的结论**数,不按算出来多少次:不动点里同一条结论每轮都
+ // 会被重新算出来,累加就成了轮数的函数
+ report.rule_hits = provisional.len();
+ report.derived += provisional.len();
}
let mut tx = pool.begin().await?;
@@ -1553,6 +1785,12 @@ pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport>
.await?;
let mut stale: Vec<Uuid> = Vec::new();
+ // 每个还成立的结论最后落在哪一行。**不变的结论保留原来那一行**,所以链上
+ // 指向它的前提要指向这个 id,而不是这一轮新造的(0030)
+ let mut settled: HashMap<DerivedKey, Uuid> = HashMap::new();
+ // 这一轮还成立、行也留着的那些,连同它们**这一轮的**前提。对账的键里没有
+ // 前提,所以「结论没变、理由变了」在这里是看不出来的——下面单独对一遍
+ let mut kept: Vec<(Uuid, Wanted)> = Vec::new();
for (id, s, p, o, ov, from, to) in &live {
let key = (
*s,
@@ -1562,7 +1800,10 @@ pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport>
from.map(|x| x.timestamp()),
to.map(|x| x.timestamp()),
);
- if wanted.remove(&key).is_none() {
+ if let Some(d) = wanted.remove(&key) {
+ settled.insert(key, *id);
+ kept.push((*id, d));
+ } else {
stale.push(*id);
}
}
@@ -1578,50 +1819,31 @@ pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport>
report.invalidated = stale.len();
}
- for (_, d) in wanted {
- // 置信度取前提里最低的;精度跟着**赢下这一端的那条前提**走(0024):派生的起点
- // 就是前提里最晚的那个起点,它的精度就是那条前提的精度——值与精度说同一句话,
- // 数据库的 CHECK 也这么要求。从前取所有前提里最粗的:year 标在一个 6 月 1 日的
- // 值上,值与标签互相矛盾。几条前提并列时取其中最粗的;那一端若是某条前提的
- // **锚点**顶上来的(0022),没有精度可言
- let mut fp: Option<String> = None;
- let mut tp: Option<String> = None;
- let mut conf = 1.0f32;
- let mut from_anchored = false;
- let mut to_anchored = false;
- for p in &d.premises {
- if let Some((pf, pt, pc, fa, ta)) = meta.get(p) {
- conf = conf.min(*pc);
- let Some((sf, st)) = spans.get(p) else {
- continue;
- };
- if d.from.is_some() && *sf == d.from {
- if *fa {
- from_anchored = true;
- } else {
- fp = coarsest(fp.as_deref(), pf.as_deref());
- }
- }
- if d.to.is_some() && *st == d.to {
- if *ta {
- to_anchored = true;
- } else {
- // 'unknown' 不是粒度,是「结束了不知哪天」的标记;它顶上来的
- // 那一端是锚点,走上面那条路
- tp = coarsest(
- tp.as_deref(),
- pt.as_deref().filter(|p| *p != crate::graph::ENDED_UNKNOWN),
- );
- }
- }
- }
- }
+ // 剩下的都是新行。**先把 id 全定下来再插**:链上的前提要指向的那一行,
+ // 可能是这一批里还没插的另一条(0030)
+ let fresh: Vec<(Uuid, Wanted)> = wanted
+ .into_iter()
+ .map(|(key, d)| {
+ let id = Uuid::now_v7();
+ settled.insert(key, id);
+ (id, d)
+ })
+ .collect();
+ // 临时 id → 真正的行 id。链上的前提在不动点里用的是临时 id,落库要换过来;
+ // 断言前提不在这张表里,原样通过
+ let resolve: HashMap<Uuid, Uuid> = provisional
+ .iter()
+ .filter_map(|(key, prov)| settled.get(key).map(|id| (*prov, *id)))
+ .collect();
+
+ for (id, d) in &fresh {
// 约束是「有精度必有日期」(0022 放宽了反向):交集把某一端算成无界时,那一端
// 的精度清掉;那一端若来自证据日期而不是原文的日期,也没有精度——在无知的地方
// 填一个确定的值,正是 `facts.valid_from_precision` 那条注释说的病
+ let (fp, tp, conf, from_anchored, to_anchored) =
+ premise_meta(&d.premises, d.from, d.to, &spans, &meta);
let fp = if from_anchored { None } else { d.from.and(fp) };
let tp = if to_anchored { None } else { d.to.and(tp) };
- let id = Uuid::now_v7();
sqlx::query(
"INSERT INTO derived_facts (id, kb_id, subject_id, predicate_id, object_id,
object_value, valid_from, valid_to,
@@ -1644,18 +1866,86 @@ pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport>
.bind(d.attribute_rule_id)
.execute(&mut *tx)
.await?;
+ report.inserted += 1;
+ }
+
+ // 结论没变、理由变了:**同一句话可以有第二条依据**(换了一条读数,或者换了
+ // 一组条件)。对账的键是主宾谓加区间,前提不在里面,所以那一行会带着上一轮
+ // 的证明留下来——链让这件事更容易撞上:站在它上面的那条前提可能刚刚作废。
+ // 一次查完再逐条比,只有真不一样的才重写
+ let kept_ids: Vec<Uuid> = kept.iter().map(|(id, _)| *id).collect();
+ let mut stored: HashMap<Uuid, Vec<PremiseCols>> = HashMap::new();
+ if !kept_ids.is_empty() {
+ let rows: Vec<(Uuid, Option<Uuid>, Option<Uuid>)> = sqlx::query_as(
+ "SELECT derived_fact_id, premise_fact_id, premise_derived_id
+ FROM fact_derivations WHERE derived_fact_id = ANY($1)
+ ORDER BY derived_fact_id, seq",
+ )
+ .bind(&kept_ids)
+ .fetch_all(&mut *tx)
+ .await?;
+ for (d, f, dv) in rows {
+ stored.entry(d).or_default().push((f, dv));
+ }
+ }
+ let premise_cols = |d: &Wanted| -> Vec<PremiseCols> {
+ d.premises
+ .iter()
+ .map(|p| match resolve.get(p) {
+ Some(x) => (None, Some(*x)),
+ None => (Some(*p), None),
+ })
+ .collect()
+ };
+ let mut reproved: Vec<(Uuid, Vec<PremiseCols>)> = Vec::new();
+ for (id, d) in &kept {
+ let want = premise_cols(d);
+ if stored.get(id).map(|s| s.as_slice()) == Some(want.as_slice()) {
+ continue;
+ }
+ reproved.push((*id, want));
+ }
+ for (id, want) in &reproved {
+ sqlx::query("DELETE FROM fact_derivations WHERE derived_fact_id = $1")
+ .bind(id)
+ .execute(&mut *tx)
+ .await?;
+ for (seq, (f, d)) in want.iter().enumerate() {
+ sqlx::query(
+ "INSERT INTO fact_derivations (derived_fact_id, premise_fact_id,
+ premise_derived_id, seq)
+ VALUES ($1, $2, $3, $4)",
+ )
+ .bind(id)
+ .bind(f)
+ .bind(d)
+ .bind(seq as i32)
+ .execute(&mut *tx)
+ .await?;
+ }
+ }
+ report.reproved = reproved.len();
+
+ // 证明**等派生全插完再写**:链上一条前提指的可能是这一批里的另一行,
+ // 而这一批没有顺序可言(`wanted` 是个 HashMap)。一趟写完的话,先轮到
+ // 的那一行会指着还不存在的行,外键当场拦下
+ for (id, d) in &fresh {
for (seq, premise) in d.premises.iter().enumerate() {
+ // 前提是断言还是另一条派生:两列二选一,`seq` 是跨两种的一个序,
+ // 证明读起来才是一条顺下来的路(0030)
+ let derived_premise = resolve.get(premise).copied();
sqlx::query(
- "INSERT INTO fact_derivations (derived_fact_id, premise_fact_id, seq)
- VALUES ($1, $2, $3)",
+ "INSERT INTO fact_derivations (derived_fact_id, premise_fact_id,
+ premise_derived_id, seq)
+ VALUES ($1, $2, $3, $4)",
)
.bind(id)
- .bind(premise)
+ .bind(derived_premise.is_none().then_some(*premise))
+ .bind(derived_premise)
.bind(seq as i32)
.execute(&mut *tx)
.await?;
}
- report.inserted += 1;
}
tx.commit().await?;
Ok(report)
@@ -1761,10 +2051,10 @@ pub async fn mark_inference_ran(pool: &PgPool, kb_id: Uuid) -> AppResult<()> {
/// 一条派生事实的证明,展开到原句(0002 R2)。
///
-/// `fact_derivations` 只记直接前提,而前提一律是断言,所以「递归展开」在这里
-/// 退化成一条链:派生 → 按 `seq` 的断言 → 每条断言的证据。叶子是 chunk,
-/// 界面上一路点到文档。**撤了的前提照样列出并打上标记**:派生随前提失效,
-/// 但「当时靠的是什么」要读得出来,那正是记录轴存在的理由。
+/// `fact_derivations` 只记直接前提,顺着它一层层问下去就是完整的证明。一条
+/// 前提要么是断言——那一步的叶子是它的原句——要么是**另一条派生**(0030),
+/// 那一步要再问一次它凭什么。**撤了的前提照样列出并打上标记**:派生随前提
+/// 失效,但「当时靠的是什么」要读得出来,那正是记录轴存在的理由。
///
/// 派生已失效或不存在时回 None——不是错误,界面据此收起。
pub async fn proof(
@@ -1775,14 +2065,135 @@ pub async fn proof(
let Some(derived) = derived_one(pool, kb_id, derived_id).await? else {
return Ok(None);
};
- let premises: Vec<Uuid> = sqlx::query_scalar(
- "SELECT premise_fact_id FROM fact_derivations WHERE derived_fact_id = $1 ORDER BY seq",
+ let steps = premise_steps(pool, derived_id, 0).await?;
+ Ok(Some(utopia_core::models::Proof { derived, steps }))
+}
+
+/// 一条派生的直接前提,派生的那几步再往下展开一层(0030)。
+///
+/// 深度上限与推理是同一条 `MAX_DEPTH`:链最长这么长,证明也就最深这么深。
+/// 到底了就停在那一步上——它自己的三元组还是列出来的,只是不再往下问。
+fn premise_steps<'a>(
+ pool: &'a PgPool,
+ derived_id: Uuid,
+ depth: usize,
+) -> std::pin::Pin<
+ Box<
+ dyn std::future::Future<Output = AppResult<Vec<utopia_core::models::ProofStep>>>
+ + Send
+ + 'a,
+ >,
+> {
+ Box::pin(async move {
+ let rows: Vec<(i32, Option<Uuid>, Option<Uuid>)> = sqlx::query_as(
+ "SELECT seq, premise_fact_id, premise_derived_id
+ FROM fact_derivations WHERE derived_fact_id = $1 ORDER BY seq",
+ )
+ .bind(derived_id)
+ .fetch_all(pool)
+ .await?;
+ // 断言那几步一次取完(每一步还要各取一次证据),派生那几步逐条问
+ let asserted: Vec<Uuid> = rows.iter().filter_map(|(_, f, _)| *f).collect();
+ let mut by_fact: HashMap<Uuid, utopia_core::models::ProofStep> = steps_for(pool, &asserted)
+ .await?
+ .into_iter()
+ .map(|s| (s.fact_id, s))
+ .collect();
+
+ let mut steps = Vec::with_capacity(rows.len());
+ for (seq, fact, derived) in rows {
+ if let Some(f) = fact {
+ let Some(mut step) = by_fact.remove(&f) else {
+ continue;
+ };
+ step.seq = seq;
+ steps.push(step);
+ } else if let Some(d) = derived {
+ let Some(mut step) = derived_step(pool, d).await? else {
+ continue;
+ };
+ step.seq = seq;
+ if depth + 1 < utopia_reason::MAX_DEPTH {
+ step.premises = premise_steps(pool, d, depth + 1).await?;
+ }
+ steps.push(step);
+ }
+ }
+ Ok(steps)
+ })
+}
+
+/// 一条派生前提读成证明的一步。三元组与区间跟断言那一步同一副样子——读的人
+/// 关心的是「这一句成不成立」,而不是它从哪张表来;`derived` 那一格答的是
+/// 后者,也是「还能不能再往下点一层」的依据。
+async fn derived_step(
+ pool: &PgPool,
+ id: Uuid,
+) -> AppResult<Option<utopia_core::models::ProofStep>> {
+ #[allow(clippy::type_complexity)]
+ let row: Option<(
+ Uuid,
+ Uuid,
+ String,
+ Option<Uuid>,
+ Option<String>,
+ Option<Uuid>,
+ Option<String>,
+ Option<chrono::DateTime<chrono::Utc>>,
+ Option<chrono::DateTime<chrono::Utc>>,
+ f32,
+ bool,
+ )> = sqlx::query_as(
+ "SELECT d.id, d.subject_id, s.canonical_name,
+ d.predicate_id, r.label, d.object_id,
+ COALESCE(o.canonical_name, ct.label,
+ d.object_value ->> 'class',
+ d.object_value #>> '{value}'),
+ d.valid_from, d.valid_to, d.confidence,
+ d.invalidated_at IS NOT NULL
+ FROM derived_facts d
+ JOIN entities s ON s.id = d.subject_id
+ LEFT JOIN relation_types r ON r.id = d.predicate_id
+ LEFT JOIN entities o ON o.id = d.object_id
+ LEFT JOIN attribute_rules ar ON ar.id = d.attribute_rule_id
+ LEFT JOIN entity_types ct ON ct.id = ar.conclude_type_id
+ WHERE d.id = $1",
)
- .bind(derived_id)
- .fetch_all(pool)
+ .bind(id)
+ .fetch_optional(pool)
.await?;
- let steps = steps_for(pool, &premises).await?;
- Ok(Some(utopia_core::models::Proof { derived, steps }))
+ Ok(row.map(
+ |(
+ fact_id,
+ subject_id,
+ subject,
+ predicate_id,
+ predicate,
+ object_id,
+ object,
+ valid_from,
+ valid_to,
+ confidence,
+ retracted,
+ )| utopia_core::models::ProofStep {
+ seq: 0,
+ fact_id,
+ derived: true,
+ subject_id,
+ subject,
+ predicate_id,
+ predicate,
+ object_id,
+ object,
+ valid_from,
+ valid_to,
+ confidence,
+ retracted,
+ // 派生没有原句:它的「证据」就是下面那一层前提
+ evidence: Vec::new(),
+ premises: Vec::new(),
+ },
+ ))
}
/// 一串前提展开成证明的步:三元组、区间、撤没撤、证据。
@@ -1843,6 +2254,8 @@ async fn steps_for(
steps.push(utopia_core::models::ProofStep {
seq: seq as i32,
fact_id,
+ derived: false,
+ premises: Vec::new(),
subject_id,
subject,
predicate_id,
@@ -1940,14 +2353,14 @@ async fn derived_one(
ps.canonical_name || ' · '
|| COALESCE(pr.label, '?') || ' · '
|| COALESCE(po.canonical_name,
- pf.object_value #>> '{value}',
+ fd.object_value #>> '{value}',
+ fd.object_value #>> '{class}',
'?')
ORDER BY fd.seq)
- FROM fact_derivations fd
- JOIN facts pf ON pf.id = fd.premise_fact_id
- JOIN entities ps ON ps.id = pf.subject_id
- LEFT JOIN relation_types pr ON pr.id = pf.predicate_id
- LEFT JOIN entities po ON po.id = pf.object_id
+ FROM derivation_premises fd
+ JOIN entities ps ON ps.id = fd.subject_id
+ LEFT JOIN relation_types pr ON pr.id = fd.predicate_id
+ LEFT JOIN entities po ON po.id = fd.object_id
WHERE fd.derived_fact_id = d.id),
ARRAY[]::text[]
) AS premises
@@ -1999,14 +2412,14 @@ pub async fn derived_for_entity(
ps.canonical_name || ' · '
|| COALESCE(pr.label, '?') || ' · '
|| COALESCE(po.canonical_name,
- pf.object_value #>> '{{value}}',
+ fd.object_value #>> '{{value}}',
+ fd.object_value #>> '{{class}}',
'?')
ORDER BY fd.seq)
- FROM fact_derivations fd
- JOIN facts pf ON pf.id = fd.premise_fact_id
- JOIN entities ps ON ps.id = pf.subject_id
- LEFT JOIN relation_types pr ON pr.id = pf.predicate_id
- LEFT JOIN entities po ON po.id = pf.object_id
+ FROM derivation_premises fd
+ JOIN entities ps ON ps.id = fd.subject_id
+ LEFT JOIN relation_types pr ON pr.id = fd.predicate_id
+ LEFT JOIN entities po ON po.id = fd.object_id
WHERE fd.derived_fact_id = d.id),
ARRAY[]::text[]
) AS premises
diff --git a/crates/utopia-store/tests/a_rule_reads_what_a_rule_concluded.rs b/crates/utopia-store/tests/a_rule_reads_what_a_rule_concluded.rs
new file mode 100644
index 00000000..cc4bb386
--- /dev/null
+++ b/crates/utopia-store/tests/a_rule_reads_what_a_rule_concluded.rs
@@ -0,0 +1,613 @@
+//! 规则接规则(0030 / #477)。
+//!
+//! 0021 的规则只读断言,只跑一趟,所以 `A → B → C` 得压成一条规则重写一遍。
+//! 现在一轮的结论进下一轮的输入,这里钉的是那件事在真库上的四个后果:
+//!
+//! - **链接得上**:第二条规则读第一条的结论,前提里一条是断言、一条是派生,
+//! 两列各存各的
+//! - **派生归类带区间**:它是当条件进的,不是当筛子——2020–2021 是 A 的实体,
+//! 2022 的读数不该满足一条 A 上的规则
+//! - **叶子变了整条链退场**:抬高第一条规则的阈值,第二条推出来的那行跟着
+//! 作废。这不是谁去追的,是「全量重算 + 对账」的自然结果
+//! - **自反馈停得下来**:规则推出自己主类的类,第二轮推出的是同一个键,
+//! 不动点在那里收敛
+//!
+//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。
+
+use sqlx::PgPool;
+use uuid::Uuid;
+
+struct Fixture {
+ org: Uuid,
+ kb: Uuid,
+ well: Uuid,
+ gas_bearing: Uuid,
+ producer: Uuid,
+ thc: Uuid,
+ completed: Uuid,
+ w1: Uuid,
+}
+
+async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {
+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let (well, gas_bearing, producer) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let (thc, completed, is_a) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let w1 = Uuid::now_v7();
+
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'chain-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'chain-test')")
+ .bind(ws)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'chain-test')",
+ )
+ .bind(kb)
+ .bind(ws)
+ .execute(pool)
+ .await?;
+ for (id, key, label) in [
+ (well, "well", "Well"),
+ (gas_bearing, "gas_well", "GasBearingWell"),
+ (producer, "producer", "Producer"),
+ ] {
+ sqlx::query("INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, $3, $4)")
+ .bind(id)
+ .bind(kb)
+ .bind(key)
+ .bind(label)
+ .execute(pool)
+ .await?;
+ }
+ for (id, key, label, datatype) in [
+ (thc, "total_hydrocarbon", "全烃", "number"),
+ (completed, "completion", "完井", "text"),
+ (is_a, "is_a", "is a", "text"),
+ ] {
+ sqlx::query(
+ "INSERT INTO relation_types (id, kb_id, key, label, kind, datatype, builtin)
+ VALUES ($1, $2, $3, $4, 'attribute', $5, $6)",
+ )
+ .bind(id)
+ .bind(kb)
+ .bind(key)
+ .bind(label)
+ .bind(datatype)
+ .bind(key == "is_a")
+ .execute(pool)
+ .await?;
+ }
+ // 实体断言的类是 Well。GasBearingWell 只能是推出来的——这正是要钉的那条路
+ sqlx::query(
+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, 'W-1')",
+ )
+ .bind(w1)
+ .bind(kb)
+ .bind(well)
+ .execute(pool)
+ .await?;
+ Ok(Fixture {
+ org,
+ kb,
+ well,
+ gas_bearing,
+ producer,
+ thc,
+ completed,
+ w1,
+ })
+}
+
+/// 一条属性事实,区间两端都给死——链上的区间是交出来的,端点含糊就看不出交没交
+async fn attr(
+ pool: &PgPool,
+ f: &Fixture,
+ predicate: Uuid,
+ value: serde_json::Value,
+ from: &str,
+ to: Option<&str>,
+) -> anyhow::Result<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_value,
+ valid_from, valid_from_precision,
+ valid_to, valid_to_precision, confidence)
+ VALUES ($1, $2, $3, $4, $5, $6, 'day', $7, $8, 0.9)",
+ )
+ .bind(id)
+ .bind(f.kb)
+ .bind(f.w1)
+ .bind(predicate)
+ .bind(serde_json::json!({ "value": value }))
+ .bind(from.parse::<chrono::DateTime<chrono::Utc>>()?)
+ .bind(
+ to.map(|t| t.parse::<chrono::DateTime<chrono::Utc>>())
+ .transpose()?,
+ )
+ .bind(to.map(|_| "day"))
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+/// 一条归类规则:主类上的一个属性条件 → 结论类。条件三格捆成一个参数——
+/// 它们本来就是一句话
+async fn rule(
+ pool: &PgPool,
+ f: &Fixture,
+ name: &str,
+ subject: Uuid,
+ condition: (Uuid, &str, Option<serde_json::Value>),
+ concludes: Uuid,
+) -> anyhow::Result<Uuid> {
+ let (predicate, op, operand) = condition;
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO attribute_rules (id, kb_id, name, subject_type_id, conclusion, conclude_type_id)
+ VALUES ($1, $2, $3, $4, 'typing', $5)",
+ )
+ .bind(id)
+ .bind(f.kb)
+ .bind(name)
+ .bind(subject)
+ .bind(concludes)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO attribute_rule_conditions (id, rule_id, seq, predicate_id, op, operand)
+ VALUES ($1, $2, 0, $3, $4, $5)",
+ )
+ .bind(Uuid::now_v7())
+ .bind(id)
+ .bind(predicate)
+ .bind(op)
+ .bind(operand)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+#[derive(sqlx::FromRow)]
+struct Derived {
+ id: Uuid,
+ class: Option<String>,
+ valid_to: Option<chrono::DateTime<chrono::Utc>>,
+ invalidated_at: Option<chrono::DateTime<chrono::Utc>>,
+}
+
+async fn derived(pool: &PgPool, f: &Fixture) -> anyhow::Result<Vec<Derived>> {
+ Ok(sqlx::query_as(
+ "SELECT id, object_value ->> 'class' AS class,
+ valid_to, invalidated_at
+ FROM derived_facts WHERE kb_id = $1 ORDER BY derived_at, id",
+ )
+ .bind(f.kb)
+ .fetch_all(pool)
+ .await?)
+}
+
+/// `Well → GasBearingWell → Producer`:第二条规则读的是第一条的结论。
+///
+/// 钉的是链上那一行的**前提长什么样**:一条断言(完井)、一条派生(归类),
+/// 分别落在 `premise_fact_id` 与 `premise_derived_id` 上。合成一列的话,
+/// 「这一步还要不要再往下问」在库里就答不出来。
+#[tokio::test]
+async fn a_conclusion_is_a_premise_for_the_next_rule() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let run = async {
+ let thc_fact = attr(
+ &pool,
+ &f,
+ f.thc,
+ serde_json::json!(12.3),
+ "2023-06-01T00:00:00Z",
+ None,
+ )
+ .await?;
+ let done = attr(
+ &pool,
+ &f,
+ f.completed,
+ serde_json::json!("yes"),
+ "2023-06-01T00:00:00Z",
+ None,
+ )
+ .await?;
+ rule(
+ &pool,
+ &f,
+ "gas-bearing",
+ f.well,
+ (f.thc, "gt", Some(serde_json::json!(8.0))),
+ f.gas_bearing,
+ )
+ .await?;
+ rule(
+ &pool,
+ &f,
+ "producer",
+ f.gas_bearing,
+ (f.completed, "present", None),
+ f.producer,
+ )
+ .await?;
+
+ let report = utopia_store::reasoning::materialize(&pool, f.kb).await?;
+ assert_eq!(report.attribute_rules, 2);
+ assert_eq!(report.rule_hits, 2, "两条结论:含气井,以及在产井");
+ assert!(
+ report.rule_rounds >= 2,
+ "链上一环一轮,一轮跑不出第二条:{}",
+ report.rule_rounds
+ );
+ assert!(!report.rule_rounds_capped, "两环没到上限");
+
+ let rows = derived(&pool, &f).await?;
+ assert_eq!(rows.len(), 2);
+ let gas = rows
+ .iter()
+ .find(|d| d.class.as_deref() == Some("gas_well"))
+ .expect("含气井那一行");
+ let prod = rows
+ .iter()
+ .find(|d| d.class.as_deref() == Some("producer"))
+ .expect("在产井那一行");
+
+ // 含气井:两条前提都是断言
+ let leaf: Vec<(Option<Uuid>, Option<Uuid>)> = sqlx::query_as(
+ "SELECT premise_fact_id, premise_derived_id
+ FROM fact_derivations WHERE derived_fact_id = $1 ORDER BY seq",
+ )
+ .bind(gas.id)
+ .fetch_all(&pool)
+ .await?;
+ assert_eq!(leaf, vec![(Some(thc_fact), None)], "含气井只凭那条全烃读数");
+
+ // 在产井:一条断言 + 一条派生。**这一条就是链**
+ let chained: Vec<(Option<Uuid>, Option<Uuid>)> = sqlx::query_as(
+ "SELECT premise_fact_id, premise_derived_id
+ FROM fact_derivations WHERE derived_fact_id = $1 ORDER BY seq",
+ )
+ .bind(prod.id)
+ .fetch_all(&pool)
+ .await?;
+ assert_eq!(chained.len(), 2, "完井那条读数,加上「它是含气井」那条结论");
+ assert!(
+ chained.contains(&(Some(done), None)),
+ "断言前提落在 premise_fact_id 上"
+ );
+ assert!(
+ chained.contains(&(None, Some(gas.id))),
+ "派生前提落在 premise_derived_id 上,指的是含气井那一行"
+ );
+
+ // 证明顺着链往下走一层:在产井 → 含气井 → 全烃那句话
+ let proof = utopia_store::reasoning::proof(&pool, f.kb, prod.id)
+ .await?
+ .expect("在产井有证明");
+ let step = proof
+ .steps
+ .iter()
+ .find(|s| s.derived)
+ .expect("证明里有一步是推出来的");
+ assert_eq!(step.premises.len(), 1, "那一步自己也有前提,再往下一层");
+ assert!(!step.premises[0].derived, "再下一层是断言,链到此为止");
+
+ // 重跑不该多出行,也不该把自己判成陈旧——链上那一行认的是上一轮留下的
+ // 那个行 id,认错了这里会看见「作废一条、插入一条」
+ let again = utopia_store::reasoning::materialize(&pool, f.kb).await?;
+ assert_eq!(again.inserted, 0, "同一条链重跑不再插");
+ assert_eq!(again.invalidated, 0, "也不该把自己判成陈旧");
+ assert_eq!(derived(&pool, &f).await?.len(), 2);
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await?;
+ run
+}
+
+/// 推出来的类**带着区间**:它是当条件进的,不是当筛子。
+///
+/// 一口井 2020–2021 是含气井,完井那条读数在 2022——两段不相交,就不该有
+/// 在产井。范围若还是个无区间的筛子,这里会多推出一行,而且那一行的区间
+/// 说不出它凭什么成立。
+#[tokio::test]
+async fn a_concluded_class_only_holds_where_it_was_concluded() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let run = async {
+ attr(
+ &pool,
+ &f,
+ f.thc,
+ serde_json::json!(12.3),
+ "2020-01-01T00:00:00Z",
+ Some("2021-01-01T00:00:00Z"),
+ )
+ .await?;
+ attr(
+ &pool,
+ &f,
+ f.completed,
+ serde_json::json!("yes"),
+ "2022-01-01T00:00:00Z",
+ None,
+ )
+ .await?;
+ rule(
+ &pool,
+ &f,
+ "gas-bearing",
+ f.well,
+ (f.thc, "gt", Some(serde_json::json!(8.0))),
+ f.gas_bearing,
+ )
+ .await?;
+ rule(
+ &pool,
+ &f,
+ "producer",
+ f.gas_bearing,
+ (f.completed, "present", None),
+ f.producer,
+ )
+ .await?;
+
+ utopia_store::reasoning::materialize(&pool, f.kb).await?;
+ let rows = derived(&pool, &f).await?;
+ assert_eq!(
+ rows.len(),
+ 1,
+ "只有含气井那一行;完井那条读数落在它成立的区间之外"
+ );
+ assert_eq!(rows[0].class.as_deref(), Some("gas_well"));
+ assert_eq!(
+ rows[0].valid_to.map(|t| t.to_rfc3339()),
+ Some("2021-01-01T00:00:00+00:00".into()),
+ "结论的区间就是那条读数的区间"
+ );
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await?;
+ run
+}
+
+/// 叶子变了,整条链退场——**而且没有一行代码是为这件事写的**。
+///
+/// 抬高第一条规则的阈值,含气井不再成立;在产井站在它上面,这一轮压根没被
+/// 重新算出来,于是从 `wanted` 里掉出去,跟含气井在同一条语句里作废。
+#[tokio::test]
+async fn a_chain_retires_with_the_reading_it_stood_on() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let run = async {
+ attr(
+ &pool,
+ &f,
+ f.thc,
+ serde_json::json!(12.3),
+ "2023-06-01T00:00:00Z",
+ None,
+ )
+ .await?;
+ attr(
+ &pool,
+ &f,
+ f.completed,
+ serde_json::json!("yes"),
+ "2023-06-01T00:00:00Z",
+ None,
+ )
+ .await?;
+ let first = rule(
+ &pool,
+ &f,
+ "gas-bearing",
+ f.well,
+ (f.thc, "gt", Some(serde_json::json!(8.0))),
+ f.gas_bearing,
+ )
+ .await?;
+ rule(
+ &pool,
+ &f,
+ "producer",
+ f.gas_bearing,
+ (f.completed, "present", None),
+ f.producer,
+ )
+ .await?;
+ utopia_store::reasoning::materialize(&pool, f.kb).await?;
+ assert_eq!(derived(&pool, &f).await?.len(), 2);
+
+ // 抬到 20:那条 12.3 的读数不再满足第一条规则
+ sqlx::query("UPDATE attribute_rule_conditions SET operand = '20.0' WHERE rule_id = $1")
+ .bind(first)
+ .execute(&pool)
+ .await?;
+ let report = utopia_store::reasoning::materialize(&pool, f.kb).await?;
+ assert_eq!(report.invalidated, 2, "含气井与站在它上面的在产井一起退场");
+ assert_eq!(report.inserted, 0);
+
+ let rows = derived(&pool, &f).await?;
+ assert_eq!(rows.len(), 2, "作废不是删除:记录轴上留着「曾据此推出」");
+ assert!(
+ rows.iter().all(|d| d.invalidated_at.is_some()),
+ "两行都作废"
+ );
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await?;
+ run
+}
+
+/// 一条规则读自己推出来的类,不动点照样收敛。
+///
+/// 第一条把井推成含气井;第二条写在含气井上,推出的还是含气井。第二轮算出来的
+/// 是同一个键——主语、谓词、值、区间都一样——于是不再进池子,第三轮无事可做。
+/// **上限是兜底,不是靠它停的**:这里 `rule_rounds` 远小于 `MAX_DEPTH`。
+#[tokio::test]
+async fn a_rule_that_feeds_itself_settles() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let run = async {
+ attr(
+ &pool,
+ &f,
+ f.thc,
+ serde_json::json!(12.3),
+ "2023-06-01T00:00:00Z",
+ None,
+ )
+ .await?;
+ rule(
+ &pool,
+ &f,
+ "gas-bearing",
+ f.well,
+ (f.thc, "gt", Some(serde_json::json!(8.0))),
+ f.gas_bearing,
+ )
+ .await?;
+ // 主类是含气井,结论也是含气井:它读的正是自己推出来的那条
+ rule(
+ &pool,
+ &f,
+ "still gas-bearing",
+ f.gas_bearing,
+ (f.thc, "gt", Some(serde_json::json!(8.0))),
+ f.gas_bearing,
+ )
+ .await?;
+
+ let report = utopia_store::reasoning::materialize(&pool, f.kb).await?;
+ assert_eq!(report.rule_hits, 1, "两条规则推出的是同一条结论,只算一条");
+ assert!(
+ report.rule_rounds < utopia_reason::MAX_DEPTH,
+ "收敛靠的是「这一轮没有新键」,不是撞上上限:{}",
+ report.rule_rounds
+ );
+ assert!(!report.rule_rounds_capped);
+ assert_eq!(derived(&pool, &f).await?.len(), 1, "库里就一行");
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await?;
+ run
+}
+
+/// 结论没变,理由变了:那一行留着,**证明跟着换**。
+///
+/// 对账的键是主宾谓加区间,前提不在里面——同一句话换一条读数支撑,行不动。
+/// 不重写的话,它会一直挂着上一轮那条已经撤了的读数,而链让这件事更容易撞上:
+/// 站在它上面的那条前提可能刚刚作废。
+#[tokio::test]
+async fn a_conclusion_that_stands_on_a_new_reading_gets_a_new_proof() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let run = async {
+ let first = attr(
+ &pool,
+ &f,
+ f.thc,
+ serde_json::json!(12.3),
+ "2023-06-01T00:00:00Z",
+ None,
+ )
+ .await?;
+ rule(
+ &pool,
+ &f,
+ "gas-bearing",
+ f.well,
+ (f.thc, "gt", Some(serde_json::json!(8.0))),
+ f.gas_bearing,
+ )
+ .await?;
+ utopia_store::reasoning::materialize(&pool, f.kb).await?;
+ let rows = derived(&pool, &f).await?;
+ assert_eq!(rows.len(), 1);
+ let row = rows[0].id;
+
+ // 撤掉那条读数,换一条区间一样、值也过阈值的:结论一字不差,凭的却是
+ // 另一句话
+ sqlx::query("UPDATE facts SET invalidated_at = now() WHERE id = $1")
+ .bind(first)
+ .execute(&pool)
+ .await?;
+ let second = attr(
+ &pool,
+ &f,
+ f.thc,
+ serde_json::json!(30.0),
+ "2023-06-01T00:00:00Z",
+ None,
+ )
+ .await?;
+
+ let report = utopia_store::reasoning::materialize(&pool, f.kb).await?;
+ assert_eq!(report.inserted, 0, "结论没变,不该多一行");
+ assert_eq!(report.invalidated, 0, "也不该把它判成陈旧");
+ assert_eq!(report.reproved, 1, "证明换了一条");
+
+ let now: Vec<(Option<Uuid>, Option<Uuid>)> = sqlx::query_as(
+ "SELECT premise_fact_id, premise_derived_id
+ FROM fact_derivations WHERE derived_fact_id = $1 ORDER BY seq",
+ )
+ .bind(row)
+ .fetch_all(&pool)
+ .await?;
+ assert_eq!(now, vec![(Some(second), None)], "挂的是现在成立的那条读数");
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await?;
+ run
+}
diff --git a/docs/decisions/0030-a-rule-may-read-what-a-rule-concluded.md b/docs/decisions/0030-a-rule-may-read-what-a-rule-concluded.md
new file mode 100644
index 00000000..7feca84e
--- /dev/null
+++ b/docs/decisions/0030-a-rule-may-read-what-a-rule-concluded.md
@@ -0,0 +1,64 @@
+# 0030 · A rule may read what a rule concluded
+
+- **Status**: cuts 1 and 2 implemented · the record, and the runner: a fixed point inside one `materialize()` (rounds bounded by `MAX_DEPTH`, rules loaded in id order so a run is reproducible), a concluded value back in the fact pool, a concluded typing joining the subject scope **as a condition** so it carries its interval and its premise, `fact_derivations` widened by `premise_derived_id` (migration `0040`) with a `derivation_premises` view so all six readers see both kinds, `proof()` walking the tree, and a kept row re-proved when its premises changed · five database tests · the page showing which rules feed which is the next cut
+- **Written**: 2026-09-08 (conventions in the [README](README.md))
+- **Related**: [0021](0021-a-rule-reads-attributes-and-concludes-a-type.md) built the rule; [0029](0029-a-rule-may-say-or-once.md) settled the shape of **one** rule, and this record settles how **several** compose — the two are independent. [0002](0002-reasoning-engine.md) built the axiom fixed point this borrows from, and left R3 (incremental maintenance) open, which this record does not close. **[0013](0013-a-source-should-hand-over-its-history.md) is where the invariant this overturns was written down**, in the DDL comment on `fact_derivations`. [0024](0024-the-world-axis-reaches-the-second.md) decides which premise sets a derived bound's precision, and a chained bound obeys it one level up. From #477.
+
+> A well whose total hydrocarbon is above 8 and whose interpretation reads as a gas anomaly is **gas-bearing**. A gas-bearing well with a completion date is a **producer**. Two criteria, written by the same person on the same afternoon, and the second one never fires — because the first one's conclusion is not something the second one can read. To get the producer you write the hydrocarbon condition again inside the producer rule, and now two rules share a premise that nothing in the base says they share. Change what "gas-bearing" means and one of them quietly stops agreeing with the other.
+
+## Why it does not chain today
+
+Three sites, none of them an oversight, all of them from when a rule was a single pass over asserted readings:
+
+- **`attribute_facts()` reads `facts`.** A rule's conclusion lands in `derived_facts`, which no input query touches.
+- **Subject scope is the asserted type.** `materialize()` filters an entity into a rule by `entities.type_id`. A rule that concludes class `B` does not make its subjects members of `B` for a rule scoped to `B`.
+- **One pass.** Each rule is evaluated once, in load order. Nothing re-reads what the round produced.
+
+The contrast is worth naming, because it makes the shape of the answer obvious: **the axiom reasoner already chains.** `derive()` runs a semi-naive fixed point exactly so `ceo_of → works_at → employs` connects, bounded by `MAX_DEPTH` rounds and a per-predicate output cap, with the frontier sorted every round so two runs over the same base give the same answer. Chaining is not foreign here. It was never wired for business rules.
+
+## The objection that has to be answered first
+
+The `fact_derivations` DDL says it plainly:
+
+> premises are always assertions: derivation excludes derived facts as inputs, or the output of one call becomes the input of the next and a re-run's result depends on what the round before left behind.
+
+That objection is correct, and this record does not waive it. It answers it.
+
+**The feedback happens inside one run, in memory.** A round's conclusions become the next round's inputs *within the same `materialize()` call*, in a fixed point that starts from the asserted facts every time. No input query reads `derived_facts`. A run stays a pure function of `(facts, rules, axioms)` — which is the property that objection protects. That property does not actually follow from "premises are assertions"; it follows from "the run does not read its own past output". The two coincided while there was one pass, and this record separates them.
+
+Reading the *previous* run's `derived_facts` as input stays forbidden, for exactly the reason 0013 gave.
+
+## What is decided
+
+**A fixed point, not an ordering.** Round after round until a round adds nothing, bounded by `MAX_DEPTH` rounds and by premise-chain length, with the frontier sorted so the answer does not depend on hash order. Without a fixed point, whether `A → B → C` fires depends on the order rules happen to load — which works on one machine, fails on another, and is the worst answer available.
+
+**Conclusions rejoin on both channels.** A concluded attribute value becomes an `AttrFact` in the pool, its value read out of `{"value": …}` the same way an asserted one is. A concluded typing joins the subject scope: a rule scoped to `B` sees an entity whose derived `is_a` names `B`, matched by class IRI and falling back to key — the same identity 0021 chose so that renaming a label does not turn a conclusion into a different one.
+
+**Derived membership is timed; asserted membership is not, so the two enter differently.** `entities.type_id` carries no interval: it is a filter and stays one. A derived typing holds only on the interval it was concluded for, and an entity that is a `B` from 2019 to 2022 must not satisfy a `B` rule on a 2024 reading. So a derived typing enters **as a premise**: it lands in the hit's premise list, `validity()` intersects its span with the conditions', and the conclusion narrows to the window in which the entity actually was a `B`. This is not symmetry for its own sake. It is the only way the interval comes out right, and it is what makes the retirement below work without a line written for it.
+
+**A rule may read its own conclusions.** The alternative — only *other* rules' — needs a rule-dependency graph that cannot be computed: a rule's inputs are predicates, not rules, so "does R feed R" is only ever an approximation, and an approximation that forbids a legitimate criterion is worse than the loop it prevents. The loop is safe. The derivable space is finite: subjects are finite, a conclusion's value is a constant written in the rule, and every interval endpoint comes from the finitely many endpoints already in the fact set. Each round only adds, and a conclusion that reproduces a key already reached does not re-enter the frontier. `X is_a B because X is_a B` is not a contradiction the way `A p A` is on a transitive antisymmetric predicate — it is a no-op, and the dedupe eats it. The bound is the round cap, not a prohibition.
+
+**The proof becomes a tree, and the schema has to say so.** `fact_derivations.premise_fact_id` references `facts(id)`, so a derived premise cannot be stored at all today. It gains a nullable sibling, `premise_derived_id` referencing `derived_facts(id)`, with a CHECK that exactly one of the two is set, one `seq` ordering across both kinds so the proof still reads in order, and an index on the new column for the reverse lookup. `proof()` stops being a flat list of assertions and becomes a walk: a derived premise expands into its own step and its own premises, down to the assertions and their chunks. `ProofStep` and its doc comment — "premises are always assertions, so the proof is a chain rather than a tree" — are wrong from that commit and change with it.
+
+**Retirement cascades, and it is free.** This sounds like the expensive part and is not. Retirement here is not an incremental walk down a dependency graph. Every run builds `wanted`, the whole set of what should hold now, and invalidates every live `derived_facts` row that is not in it. If a leaf reading changes, the chain that stood on it is simply not rebuilt this round; the whole tail falls out of `wanted` and retires in the same pass, in the same statement, with nothing in the code aware that a chain existed. **The cascade is a consequence of full recompute, not a feature anyone writes.**
+
+**Row identity is resolved after the diff, not during the round.** A conclusion reached in round 2 has premises that are rows the round has not written yet — and may never write, because an unchanged conclusion keeps its existing row instead of getting a new one. So the fixed point carries a provisional id per conclusion; the diff maps every key to its final id (the live row's for a kept conclusion, a fresh one for a new conclusion); premise ids are rewritten through that map before `fact_derivations` is written. Getting this backwards — writing derivations against provisional ids — points every chained proof at rows that do not exist.
+
+**Asserted and derived readings are both readings.** If a rule concludes `grade = A` on an entity that also asserts `grade = B`, both sit in the pool, and a downstream rule can fire on either, producing two hits with different premises and usually different intervals. This is the 0021 position unchanged — a derived fact never replaces an asserted one — and the proof is what tells them apart. Suppressing the derived reading would need a preference order that 0021 deliberately did not build.
+
+## What it costs
+
+**Display depth**, and only that. The entity panel draws a proof one level deep; a chained conclusion is two or more. That is cut 3's problem, along with the rule table saying which rules feed which — a chain is worth seeing before you delete the rule in the middle of it. On the schema diagram the edges already compose visually: `Well → GasBearingWell → Producer` is two rule edges in a row, drawn with no change.
+
+**A report that says the cap was hit.** Rounds stopped by `MAX_DEPTH` have to be counted and reported, for the same reason the combination cap is: a conclusion that was not reached and a criterion that was not met look identical in the result.
+
+## Not in this record
+
+- **Axioms and rules stay two reasoners.** Rules read literal values, axioms read entity-to-entity edges. The one place they meet is a derived typing, which is a literal on `is_a` and therefore already on the rules' side. Folding both into one fixed point is a different question with a different cost, and nobody has asked it.
+- **Incremental maintenance is still open** (0002 R3). This record makes the full recompute do more, not less. If it becomes too slow, that is the record to write — and the cascade being free is exactly what an incremental version would have to reproduce, and would find hard.
+- **Reading the previous run's output.** Forbidden, per 0013. The fixed point is what makes it unnecessary.
+
+## Open
+
+- ~~A kept row can keep a stale proof.~~ **Closed in cut 2.** `wanted` is keyed by subject, predicate, value and interval, with premises outside the key, so a conclusion reached this round by a different path than last round used to keep its old `fact_derivations` — already true with asserted premises, and easier to hit with chains, where the stale premise can be a row that was just invalidated. The run now reads the stored premises of every kept row in one query and rewrites the ones that differ; the count is `reproved` in the report.
+- **How deep is worth drawing.** Twelve rounds is the bound, not the expectation. If real bases produce chains longer than two or three, the panel needs a shape for that rather than an ever-deeper nest.
diff --git a/docs/decisions/README.md b/docs/decisions/README.md
index 6c680777..52070f4c 100644
--- a/docs/decisions/README.md
+++ b/docs/decisions/README.md
@@ -53,6 +53,7 @@ The test for writing one: if someone (including us) looks at a piece of code in
| 0027 | [An automatic merge is gated by what it can undo](0027-an-automatic-merge-is-gated-by-what-it-can-undo.md) | Implemented · `execution_gate` in the store, asked by the batch adjudicator and the governor before an automatic merge: a contradiction the consistency check would open, a derivation resting on either side, or an answer that named either side holds the pair for a person as `escalate_impact` whatever the confidence · keeps are not gated · exports and a per-deployment opt-in stay open |
| 0028 | [The adjudicator looks before it asks](0028-the-adjudicator-looks-before-it-asks.md) | Implemented · `consequences` joins the second look's tools (what a merge would touch, from 0027's gate, and whether the types share a family) · with governance off the batch adjudicator sends its unsettled pairs through the same loop under the same budget, each look a row in `agent_decisions` · the number that justifies or retires it comes from 0026's sample split by `via` |
| 0029 | [A rule may say "or", once](0029-a-rule-may-say-or-once.md) | Implemented · a `group_seq` on a rule's conditions (migration `0039`): same group joins with **and**, groups join with **or**, one level and no nesting — because a hit carries the readings that made it true and a disjunction has no premises of its own · the combination cap is per group, two groups on one interval are one conclusion with the first group's proof, `not_in` joins the ops · "no such attribute at all" is deliberately not here (no premise, and a missing reading means nobody wrote it down) · the editor writes blocks and the table reads the sentence back with its "or" in it |
+| 0030 | [A rule may read what a rule concluded](0030-a-rule-may-read-what-a-rule-concluded.md) | Cuts 1–2 · A rule could not read another rule's conclusion (`attribute_facts()` reads `facts`, subject scope is `entities.type_id`, one pass), so `A → B → C` has to be written as one flattened rule. The answer is the fixed point the axiom side already runs, **inside one call and in memory** — which answers 0013's objection instead of waiving it, since a run stays a pure function of the asserted facts. A derived typing enters as a **premise**, not a filter, so the conclusion narrows to the window the entity was actually a `B`; a rule may read its own conclusions because the derivable space is finite; `fact_derivations` gains `premise_derived_id` and the proof becomes a tree; retirement cascades for free because recompute is total. The page showing which rules feed which is next |
| 0031 | [An event holds at the moment it names](0031-an-event-holds-at-the-moment-it-names.md) | Implemented (#486) · `Validity::under` normalises every write by the predicate's `temporal` (an event is one moment written at both ends, an eternal fact has no dates), `world_axis` and `read_span` read an event as the bucket it names and an undated event at no moment, an eternal fact at every moment · the prompt marks `[event]` / `[eternal]` and says what to write · no schema change, old rows read correctly · the panel's point rendering and the ontology hint are the UI cut |
## Not a decision record
diff --git a/migrations/0040_a_premise_may_be_derived.sql b/migrations/0040_a_premise_may_be_derived.sql
new file mode 100644
index 00000000..f35874b6
--- /dev/null
+++ b/migrations/0040_a_premise_may_be_derived.sql
@@ -0,0 +1,42 @@
+-- 0030:一条派生事实的前提可以是另一条派生事实。
+--
+-- 0013 建这张表时写着「前提一律是断言」,理由是「同一次调用的输出会变成下一次
+-- 的输入,重跑结果依赖上一轮的残留」。那个理由现在还成立,被守住的方式也没变:
+-- **规则之间的反馈发生在同一次 `materialize()` 里,在内存的不动点上**,输入侧
+-- 一行 `derived_facts` 都不读。一次推理仍然是 (facts, rules, axioms) 的纯函数。
+-- 变的只是:证明从一条链变成一棵树,所以这张表得存得下树的中间那一层。
+--
+-- 两列二选一而不是加一个 kind 列:外键在两边都留着,删哪一侧都跟得上;
+-- `seq` 仍然是**跨两种前提的一个序**——证明读起来是一个顺序,不是两段。
+ALTER TABLE fact_derivations ALTER COLUMN premise_fact_id DROP NOT NULL;
+
+ALTER TABLE fact_derivations
+ ADD COLUMN premise_derived_id UUID REFERENCES derived_facts(id) ON DELETE CASCADE;
+
+ALTER TABLE fact_derivations
+ ADD CONSTRAINT fact_derivations_one_premise
+ CHECK ((premise_fact_id IS NOT NULL) <> (premise_derived_id IS NOT NULL));
+
+-- 「这条派生被作废了,哪些派生站在它上面」——与 `fact_derivations_premise_idx`
+-- 同一件事,只是另一侧
+CREATE INDEX fact_derivations_derived_premise_idx
+ ON fact_derivations (premise_derived_id);
+
+-- 一条派生的直接前提,两种前提长成同一副样子。
+--
+-- **有这个视图是因为读的地方有六处**:实体面板的证明、派生那一档、规则命中
+-- 列表、导出、图上的边。每一处都写一遍 `JOIN facts ... UNION ALL JOIN
+-- derived_facts ...`,六份里迟早有一份漏掉后半段——而漏掉的表现是「前提少了
+-- 一条」,不是报错。`derived` 那一列答的是「这一步还要不要再往下问一次」。
+CREATE VIEW derivation_premises AS
+SELECT fd.derived_fact_id, fd.seq, FALSE AS derived,
+ f.id, f.subject_id, f.predicate_id, f.object_id, f.object_value,
+ f.valid_from, f.valid_to, f.confidence, f.invalidated_at
+ FROM fact_derivations fd
+ JOIN facts f ON f.id = fd.premise_fact_id
+UNION ALL
+SELECT fd.derived_fact_id, fd.seq, TRUE AS derived,
+ d.id, d.subject_id, d.predicate_id, d.object_id, d.object_value,
+ d.valid_from, d.valid_to, d.confidence, d.invalidated_at
+ FROM fact_derivations fd
+ JOIN derived_facts d ON d.id = fd.premise_derived_id;
diff --git a/web/src/api.ts b/web/src/api.ts
index 73b50ab5..66ac1594 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -1778,6 +1778,10 @@ export const api = {
capped: number;
inserted: number;
invalidated: number;
+ /** 链跑了几轮:1 就是没有链,2 就是一条规则读了另一条的结论(0030) */
+ rounds: number;
+ /** 跑满上限还在产出:链比 MAX_DEPTH 长,后面那几环没接上 */
+ rounds_capped: boolean;
}>(`/api/v1/kbs/${kbId}/rules/run`, { method: "POST" }),
entityHistory: (kbId: string, entityId: string, page: number, per = 30) =>
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 894b6ef0..c895e20e 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -1182,6 +1182,9 @@ export const en = {
`${hits} matched · ${inserted} new · ${invalidated} retired`,
ruleRunCapped: (n: number) =>
`${n} entity/rule pairs had too many readings to expand; their conclusions are incomplete`,
+ /** 链跑满上限就停了。**说出来**:没接上的那一环与「不满足」长得一样 */
+ ruleRunRoundsCapped: (n: number): string =>
+ `Rules kept concluding after ${n} rounds; anything further down the chain was not reached`,
ruleNeedsCondition: "A rule needs at least one condition.",
/* ---- 打磨:可点的计数、常驻的 capped 提示、改结论 ---- */
ruleEdit: "Edit",
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 177451bb..afadf184 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -1046,6 +1046,8 @@ export const zh: Strings = {
`命中 ${hits} · 新增 ${inserted} · 退场 ${invalidated}`,
ruleRunCapped: (n: number) =>
`${n} 对(规则,实体)的读数组合太多没有展开完,它们的结论不完整`,
+ ruleRunRoundsCapped: (n: number) =>
+ `跑满 ${n} 轮还在往下推,链再往后的那几环没有接上`,
ruleNeedsCondition: "一条规则至少要有一个条件。",
ruleEdit: "编辑",
ruleEditing: "正在编辑",
diff --git a/web/src/pages/RulesPanel.tsx b/web/src/pages/RulesPanel.tsx
index e6cd7052..3efd026c 100644
--- a/web/src/pages/RulesPanel.tsx
+++ b/web/src/pages/RulesPanel.tsx
@@ -312,6 +312,8 @@ export function RulesPanel({
toast.success(S.ontology.ruleRunDone(r.hits, r.inserted, r.invalidated));
// 展开不全要单独说:少推几条与「不满足」在结果里长得一样
if (r.capped) toast.error(S.ontology.ruleRunCapped(r.capped));
+ // 链没跑到头也是「少推了东西」,与组合展不完同一类提示(0030)
+ if (r.rounds_capped) toast.error(S.ontology.ruleRunRoundsCapped(r.rounds));
invalidate();
},
onError,