Skip to content

World's first open-source enterprise world model.

A rule computes what it concludes (#495)

WaylandYang3c33a5224947
diff --git a/crates/utopia-reason/src/rules.rs b/crates/utopia-reason/src/rules.rs
index e8d66901..747d789e 100644
--- a/crates/utopia-reason/src/rules.rs
+++ b/crates/utopia-reason/src/rules.rs
@@ -77,9 +77,113 @@ pub enum Operand {
/// 类别集合。**逐字匹配**——同一类别换个语言就不算命中,这是 0021 记下的
/// 未决问题,不在这里偷偷做模糊
Set(Vec<String>),
+ /// 算出来的数(0032):拿这个实体别的读数算一个门槛,而不是写死一个
+ Calc(Expr),
None,
}
+/// 四则。**只有这四个**:再多一个就得回答它对缺读数、对除零、对单位各是什么
+/// 语义,而那是一门语言的开头(0002 / 0032)
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Arith {
+ Add,
+ Sub,
+ Mul,
+ Div,
+}
+
+impl Arith {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Arith::Add => "add",
+ Arith::Sub => "sub",
+ Arith::Mul => "mul",
+ Arith::Div => "div",
+ }
+ }
+ pub fn parse(s: &str) -> Option<Self> {
+ Some(match s {
+ "add" => Arith::Add,
+ "sub" => Arith::Sub,
+ "mul" => Arith::Mul,
+ "div" => Arith::Div,
+ _ => return None,
+ })
+ }
+}
+
+/// 一个数是怎么算出来的(0032)。叶子要么是这个实体的一条属性读数,要么是
+/// 写死的数;中间是四则。
+///
+/// **树,不是字符串。** 存下来的就是这棵树,界面照着它渲染,求值照着它算——
+/// 两者不会漂移,而这正是 0002 拒掉「用户自定义规则语言」时真正在守的东西。
+#[derive(Debug, Clone, PartialEq)]
+pub enum Expr {
+ /// 这个实体在这个谓词上的读数
+ Attr(Uuid),
+ Const(f64),
+ Arith {
+ op: Arith,
+ l: Box<Expr>,
+ r: Box<Expr>,
+ },
+}
+
+/// 一棵算式最深几层。太深的树是「有人在这里写程序」的信号,编译时就该拦下
+pub const MAX_EXPR_DEPTH: usize = 4;
+
+impl Expr {
+ /// 这棵树读了哪些谓词,按出现顺序、去重。求值前要为它们各留一个槽位
+ pub fn predicates(&self, out: &mut Vec<Uuid>) {
+ match self {
+ Expr::Attr(p) => {
+ if !out.contains(p) {
+ out.push(*p);
+ }
+ }
+ Expr::Const(_) => {}
+ Expr::Arith { l, r, .. } => {
+ l.predicates(out);
+ r.predicates(out);
+ }
+ }
+ }
+
+ pub fn depth(&self) -> usize {
+ match self {
+ Expr::Attr(_) | Expr::Const(_) => 1,
+ Expr::Arith { l, r, .. } => 1 + l.depth().max(r.depth()),
+ }
+ }
+
+ /// 按这一轮选中的读数算一个数。
+ ///
+ /// **算不出来就是 None,不是 0**:读数不在(没记 ≠ 零)、值不是数、除零,
+ /// 三种情况一律没有值,于是这条规则在这个组合上不出结论(0032)。把它们
+ /// 当零,等于在无知的地方填一个确定的答案。
+ pub fn eval(&self, bound: &HashMap<Uuid, &AttrFact>) -> Option<f64> {
+ Some(match self {
+ Expr::Attr(p) => num(&bound.get(p)?.value)?,
+ Expr::Const(n) => *n,
+ Expr::Arith { op, l, r } => {
+ let (a, b) = (l.eval(bound)?, r.eval(bound)?);
+ match op {
+ Arith::Add => a + b,
+ Arith::Sub => a - b,
+ Arith::Mul => a * b,
+ Arith::Div => {
+ if b == 0.0 {
+ return None;
+ }
+ a / b
+ }
+ }
+ }
+ })
+ .filter(|n: &f64| n.is_finite())
+ }
+}
+
#[derive(Debug, Clone, PartialEq)]
pub struct Condition {
/// 同组的条件用「与」连,组与组之间用「或」连(0029)。老规则全是第 0 组
@@ -94,6 +198,9 @@ pub struct Condition {
pub enum Conclusion {
/// 派生归类:结论是一个类,落成 `is_a` 上的字面值
Typing { class: String },
+ /// 派生属性:算出来的数(0032)。与上面那支的区别只在值从哪来——
+ /// 算式读的那几条读数**一并进前提**,所以结论仍然说得出「凭什么」
+ Computed { predicate: Uuid, expr: Expr },
/// 派生属性:某个属性谓词上的一个字面值
Attribute {
predicate: Uuid,
@@ -119,6 +226,9 @@ pub struct RuleHit {
pub premises: Vec<Uuid>,
pub from: Option<i64>,
pub to: Option<i64>,
+ /// 算出来的结论值(0032)。**每个组合各算各的**——两条 revenue 三条 cost
+ /// 就是六个数、六段区间、六行结论;常量结论这里是 None
+ pub value: Option<f64>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
@@ -180,53 +290,108 @@ pub fn evaluate(
for (subject, own) in &by_subject {
// 同一实体上,一条规则的多个组可能推出同一段区间。去重跨组,
// 因为它们落成的是同一行派生事实
- let mut seen: Vec<(Option<i64>, Option<i64>)> = Vec::new();
+ // 去重的键带上算出来的值(0032):同一区间上两个不同的值是两行
+ let mut seen: Vec<(Option<i64>, Option<i64>, Option<u64>)> = Vec::new();
// 这条规则在这个实体上有没有哪一组因组合太多没展开完。**按 (规则, 实体)
// 记一次**:报出来的是「这里少推了东西」,不是「少推了几组」
let mut capped_here = false;
for group in &groups {
- // 每个条件的命中集。任何一个为空,这一组在这个实体上就不成立
- let mut per_condition: Vec<Vec<Uuid>> = Vec::with_capacity(group.len());
- let mut satisfiable = true;
+ // ---- 槽位:这一组要各挑一条读数的那几处。
+ //
+ // 前 group.len() 个是条件自己的谓词(**一个条件一个槽**,与
+ // 0032 之前一样:两个写在同一属性上的条件仍然各挑各的读数);
+ // 后面是算式里读到、而条件没覆盖的谓词(0032)。算式引用一个
+ // 谓词时绑到**第一个**同谓词的槽——`thc > thc * 0.5` 两边说的
+ // 就是同一条读数,而不是同一属性的两条
+ let mut slots: Vec<Uuid> = group.iter().map(|c| c.predicate).collect();
+ let mut extra: Vec<Uuid> = Vec::new();
for c in group {
+ if let Operand::Calc(e) = &c.operand {
+ e.predicates(&mut extra);
+ }
+ }
+ if let Conclusion::Computed { expr, .. } = &rule.conclusion {
+ expr.predicates(&mut extra);
+ }
+ for p in extra {
+ if !slots.contains(&p) {
+ slots.push(p);
+ }
+ }
+
+ // 每个槽位的候选读数。任何一个为空,这一组在这个实体上就不成立
+ let mut per_slot: Vec<Vec<Uuid>> = Vec::with_capacity(slots.len());
+ let mut satisfiable = true;
+ for p in &slots {
let matched: Vec<Uuid> = own
.iter()
- .filter(|f| f.predicate == c.predicate && satisfies(c, &f.value))
+ .filter(|f| f.predicate == *p)
.map(|f| f.id)
.collect();
if matched.is_empty() {
satisfiable = false;
break;
}
- per_condition.push(matched);
+ per_slot.push(matched);
}
if !satisfiable {
continue;
}
// 封顶按组算:一组展不开,不该把另一组也拦下
- let combos: usize = per_condition.iter().map(|v| v.len()).product();
+ let combos: usize = per_slot.iter().map(|v| v.len()).product();
if combos > MAX_COMBOS {
capped_here = true;
continue;
}
- // 笛卡尔积。同一区间可能由多个组合得出(同一读数报了两遍),
- // 按区间去重——它们本来就会落成同一行
- for combo in cartesian(&per_condition) {
+ let by_id: HashMap<Uuid, &AttrFact> = own.iter().map(|f| (f.id, *f)).collect();
+
+ // 笛卡尔积。**条件要等组合定下来才判得了**(0032):一个算出来的
+ // 门槛读的是这一轮选中的那几条读数,判断不再只看一条事实。
+ // 同一区间可能由多个组合得出(同一读数报了两遍),按区间去重
+ for combo in cartesian(&per_slot) {
+ // 槽位 → 这一轮选中的那条读数。算式与条件都照着它读
+ let mut bound: HashMap<Uuid, &AttrFact> = HashMap::new();
+ for (i, id) in combo.iter().enumerate() {
+ let Some(f) = by_id.get(id) else { continue };
+ bound.entry(slots[i]).or_insert(f);
+ }
+ let holds = group.iter().enumerate().all(|(i, c)| {
+ combo
+ .get(i)
+ .and_then(|id| by_id.get(id))
+ .is_some_and(|f| satisfies(c, &f.value, &bound))
+ });
+ if !holds {
+ continue;
+ }
+ // 算出来的结论:这个组合上算不出数就不出结论(缺读数、
+ // 不是数、除零),而不是落一行没有值的派生
+ let value = match &rule.conclusion {
+ Conclusion::Computed { expr, .. } => match expr.eval(&bound) {
+ Some(v) => Some(v),
+ None => continue,
+ },
+ _ => None,
+ };
let Some((from, to)) = validity(&combo, spans) else {
continue;
};
- if seen.contains(&(from, to)) {
+ // 去重按 (区间, 值):算出来的结论同一区间可以有不同的值,
+ // 那是两行,不是一行
+ let key = (from, to, value.map(f64::to_bits));
+ if seen.contains(&key) {
continue;
}
- seen.push((from, to));
+ seen.push(key);
hits.push(RuleHit {
rule: rule.id,
subject: *subject,
premises: combo,
from,
to,
+ value,
});
}
}
@@ -271,7 +436,20 @@ fn cartesian(sets: &[Vec<Uuid>]) -> Vec<Vec<Uuid>> {
///
/// **类型不对就是不满足,不是报错。** 一个本该是数字的属性被抽成了
/// "十二点三",这条规则在这个实体上不成立——而不是让整轮物化失败。
-fn satisfies(c: &Condition, value: &serde_json::Value) -> bool {
+fn satisfies(c: &Condition, value: &serde_json::Value, bound: &HashMap<Uuid, &AttrFact>) -> bool {
+ // 算出来的门槛:先按这一轮选中的读数算个数,算不出来就是不满足(0032)
+ if let Operand::Calc(e) = &c.operand {
+ let Some(n) = e.eval(bound) else { return false };
+ let Some(v) = num(value) else { return false };
+ return match c.op {
+ Op::Gt => v > n,
+ Op::Gte => v >= n,
+ Op::Lt => v < n,
+ Op::Lte => v <= n,
+ // 算式给的是一个数:区间、集合、有记录都不是它能填的位置
+ _ => false,
+ };
+ }
match (&c.op, &c.operand) {
(Op::Present, _) => !value.is_null(),
// 值不在集合里就算满足;**没有值不算**——那是「没记」,不是「不是它」
@@ -707,4 +885,182 @@ mod tests {
assert_eq!(report.capped, 1, "100 种组合超过上限,要计数");
assert!(hits.is_empty());
}
+
+ fn attr(p: u8) -> Expr {
+ Expr::Attr(id(p))
+ }
+ fn arith(op: Arith, l: Expr, r: Expr) -> Expr {
+ Expr::Arith {
+ op,
+ l: Box::new(l),
+ r: Box::new(r),
+ }
+ }
+
+ /// 结论是算出来的:margin = revenue − cost。**算式读的两条读数都进前提**,
+ /// 所以这条结论说得出凭什么,也会在任一条读数变了的时候退场(0032)
+ #[test]
+ fn a_computed_conclusion_carries_the_readings_it_read() {
+ let rule = BusinessRule {
+ id: id(90),
+ conclusion: Conclusion::Computed {
+ predicate: id(12),
+ expr: arith(Arith::Sub, attr(10), attr(11)),
+ },
+ conditions: vec![Condition {
+ group: 0,
+ predicate: id(10),
+ op: Op::Present,
+ operand: Operand::None,
+ }],
+ };
+ let facts = vec![fact(1, 50, 10, json!(300.0)), fact(2, 50, 11, json!(120.0))];
+ let spans = HashMap::from([(id(1), (Some(100), None)), (id(2), (Some(100), None))]);
+ let (hits, _) = evaluate(&[rule], &facts, &spans);
+ assert_eq!(hits.len(), 1);
+ assert_eq!(hits[0].value, Some(180.0));
+ // 条件只提到 revenue,可 cost 也读了——它照样是前提
+ assert_eq!(hits[0].premises.len(), 2);
+ assert!(hits[0].premises.contains(&id(1)) && hits[0].premises.contains(&id(2)));
+ }
+
+ /// **每个组合各算各的。** 两条 revenue 一条 cost,就是两个数、两段区间、
+ /// 两行结论——而不是挑一条算一次(0032 里说的「行数才是真代价」)
+ #[test]
+ fn each_combination_of_readings_computes_its_own_value() {
+ let rule = BusinessRule {
+ id: id(90),
+ conclusion: Conclusion::Computed {
+ predicate: id(12),
+ expr: arith(Arith::Sub, attr(10), attr(11)),
+ },
+ conditions: vec![Condition {
+ group: 0,
+ predicate: id(10),
+ op: Op::Present,
+ operand: Operand::None,
+ }],
+ };
+ let facts = vec![
+ fact(1, 50, 10, json!(300.0)),
+ fact(2, 50, 10, json!(400.0)),
+ fact(3, 50, 11, json!(120.0)),
+ ];
+ let spans = HashMap::from([
+ (id(1), (Some(100), Some(200))),
+ (id(2), (Some(200), Some(300))),
+ (id(3), (Some(100), Some(300))),
+ ]);
+ let (hits, _) = evaluate(&[rule], &facts, &spans);
+ assert_eq!(hits.len(), 2, "两条 revenue 各算一个 margin");
+ let mut values: Vec<f64> = hits.iter().filter_map(|h| h.value).collect();
+ values.sort_by(f64::total_cmp);
+ assert_eq!(values, vec![180.0, 280.0]);
+ }
+
+ /// 缺一条读数就不出结论——**不是当零**。没记不等于零,在无知的地方填一个
+ /// 确定的答案正是这套账本最不该做的事
+ #[test]
+ fn a_missing_reading_computes_nothing_rather_than_zero() {
+ let rule = BusinessRule {
+ id: id(90),
+ conclusion: Conclusion::Computed {
+ predicate: id(12),
+ expr: arith(Arith::Sub, attr(10), attr(11)),
+ },
+ conditions: vec![Condition {
+ group: 0,
+ predicate: id(10),
+ op: Op::Present,
+ operand: Operand::None,
+ }],
+ };
+ let facts = vec![fact(1, 50, 10, json!(300.0))];
+ let spans = HashMap::from([(id(1), (Some(100), None))]);
+ let (hits, _) = evaluate(&[rule], &facts, &spans);
+ assert!(hits.is_empty(), "cost 没记,margin 就不该有");
+ }
+
+ /// 除零同样什么都不出。一条算不出来的结论与一条不成立的结论一样:没有
+ #[test]
+ fn dividing_by_zero_computes_nothing() {
+ let rule = BusinessRule {
+ id: id(90),
+ conclusion: Conclusion::Computed {
+ predicate: id(12),
+ expr: arith(Arith::Div, attr(10), attr(11)),
+ },
+ conditions: vec![Condition {
+ group: 0,
+ predicate: id(10),
+ op: Op::Present,
+ operand: Operand::None,
+ }],
+ };
+ let facts = vec![fact(1, 50, 10, json!(300.0)), fact(2, 50, 11, json!(0.0))];
+ let spans = HashMap::from([(id(1), (Some(100), None)), (id(2), (Some(100), None))]);
+ let (hits, _) = evaluate(&[rule], &facts, &spans);
+ assert!(hits.is_empty());
+ }
+
+ /// 门槛也能是算出来的:`revenue > cost × 1.5`。判断要等组合定下来才做得了,
+ /// 因为门槛读的正是这一轮选中的那条 cost
+ #[test]
+ fn a_threshold_can_be_computed_from_another_reading() {
+ let rule = |factor: f64| BusinessRule {
+ id: id(90),
+ conclusion: Conclusion::Typing {
+ class: "Healthy".into(),
+ },
+ conditions: vec![Condition {
+ group: 0,
+ predicate: id(10),
+ op: Op::Gt,
+ operand: Operand::Calc(arith(Arith::Mul, attr(11), Expr::Const(factor))),
+ }],
+ };
+ let facts = vec![fact(1, 50, 10, json!(300.0)), fact(2, 50, 11, json!(120.0))];
+ let spans = HashMap::from([(id(1), (Some(100), None)), (id(2), (Some(100), None))]);
+
+ let (hits, _) = evaluate(&[rule(1.5)], &facts, &spans);
+ assert_eq!(hits.len(), 1, "300 > 120 × 1.5");
+ assert_eq!(hits[0].premises.len(), 2, "门槛读的那条也是前提");
+
+ let (none, _) = evaluate(&[rule(3.0)], &facts, &spans);
+ assert!(none.is_empty(), "300 不大于 120 × 3");
+ }
+
+ /// 同一区间上两个不同的值是**两行**,不是一行。去重的键带上值,否则
+ /// 后算出来的那个会被当成重复丢掉
+ #[test]
+ fn two_values_on_one_interval_are_two_hits() {
+ let rule = BusinessRule {
+ id: id(90),
+ conclusion: Conclusion::Computed {
+ predicate: id(12),
+ expr: attr(10),
+ },
+ conditions: vec![Condition {
+ group: 0,
+ predicate: id(10),
+ op: Op::Present,
+ operand: Operand::None,
+ }],
+ };
+ let facts = vec![fact(1, 50, 10, json!(300.0)), fact(2, 50, 10, json!(400.0))];
+ let spans = HashMap::from([(id(1), (Some(100), None)), (id(2), (Some(100), None))]);
+ let (hits, _) = evaluate(&[rule], &facts, &spans);
+ assert_eq!(hits.len(), 2, "同一段区间,两个值");
+ }
+
+ /// 算式的深度算得对——编译那一侧靠它拦住「有人在这里写程序」
+ #[test]
+ fn depth_counts_the_deepest_branch() {
+ assert_eq!(attr(10).depth(), 1);
+ assert_eq!(arith(Arith::Add, attr(10), attr(11)).depth(), 2);
+ assert_eq!(
+ arith(Arith::Div, arith(Arith::Sub, attr(10), attr(11)), attr(10)).depth(),
+ 3
+ );
+ }
}
diff --git a/crates/utopia-server/src/api/rule_routes.rs b/crates/utopia-server/src/api/rule_routes.rs
index afcbea5b..33d3c323 100644
--- a/crates/utopia-server/src/api/rule_routes.rs
+++ b/crates/utopia-server/src/api/rule_routes.rs
@@ -30,6 +30,9 @@ pub struct RuleReq {
pub conclude_predicate_id: Option<Uuid>,
#[serde(default)]
pub conclude_value: Option<serde_json::Value>,
+ /// 算出来的结论那棵树(0032):`conclusion = "computed"` 时给
+ #[serde(default)]
+ pub conclude_expr: Option<serde_json::Value>,
pub conditions: Vec<ConditionInput>,
}
@@ -53,6 +56,8 @@ pub struct RulePatch {
pub conclude_predicate_id: Option<Uuid>,
#[serde(default)]
pub conclude_value: Option<serde_json::Value>,
+ #[serde(default)]
+ pub conclude_expr: Option<serde_json::Value>,
}
pub async fn list(
@@ -82,6 +87,7 @@ pub async fn create(
req.conclude_type_id,
req.conclude_predicate_id,
req.conclude_value.clone(),
+ req.conclude_expr.clone(),
&req.conditions,
)
.await?;
@@ -110,6 +116,7 @@ pub async fn update(
type_id: req.conclude_type_id,
predicate_id: req.conclude_predicate_id,
value: req.conclude_value.clone(),
+ expr: req.conclude_expr.clone(),
});
utopia_store::business_rules::update(
&state.pool,
diff --git a/crates/utopia-store/src/business_rules.rs b/crates/utopia-store/src/business_rules.rs
index fcc5276c..13694786 100644
--- a/crates/utopia-store/src/business_rules.rs
+++ b/crates/utopia-store/src/business_rules.rs
@@ -63,6 +63,8 @@ type RuleRow = (
Option<Uuid>,
Option<String>,
Option<serde_json::Value>,
+ // 算出来的结论那棵树(0032)
+ Option<serde_json::Value>,
bool,
i64,
i32,
@@ -104,6 +106,8 @@ pub async fn create(
conclude_type_id: Option<Uuid>,
conclude_predicate_id: Option<Uuid>,
conclude_value: Option<serde_json::Value>,
+ // 算出来的结论那棵树(0032)
+ conclude_expr: Option<serde_json::Value>,
conditions: &[ConditionInput],
) -> AppResult<Uuid> {
let name = name.trim();
@@ -130,6 +134,7 @@ pub async fn create(
type_id: conclude_type_id,
predicate_id: conclude_predicate_id,
value: conclude_value.clone(),
+ expr: conclude_expr.clone(),
},
)
.await?;
@@ -148,8 +153,8 @@ pub async fn create(
sqlx::query(
"INSERT INTO attribute_rules
(id, kb_id, name, description, subject_type_id, conclusion,
- conclude_type_id, conclude_predicate_id, conclude_value)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)",
+ conclude_type_id, conclude_predicate_id, conclude_value, conclude_expr)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
)
.bind(id)
.bind(kb_id)
@@ -160,6 +165,7 @@ pub async fn create(
.bind(conclude_type_id)
.bind(conclude_predicate_id)
.bind(&conclude_value)
+ .bind(&conclude_expr)
.execute(&mut *tx)
.await
.map_err(|e| match e {
@@ -181,11 +187,13 @@ pub async fn create(
/// 结论的一次改写。**两种形状各自完整地给**,不做「只改类、别的不动」——
/// 结论的三格是互相定义的,部分更新会留下 typing 却带着值这种半截状态。
pub struct ConclusionInput {
- /// typing | attribute
+ /// typing | attribute | computed
pub kind: String,
pub type_id: Option<Uuid>,
pub predicate_id: Option<Uuid>,
pub value: Option<serde_json::Value>,
+ /// 算出来的结论那棵树(0032)。`computed` 时必给,别的两支必空
+ pub expr: Option<serde_json::Value>,
}
#[allow(clippy::too_many_arguments)]
@@ -224,6 +232,7 @@ pub async fn update(
conclude_type_id = CASE WHEN $6 IS NULL THEN conclude_type_id ELSE $7 END,
conclude_predicate_id = CASE WHEN $6 IS NULL THEN conclude_predicate_id ELSE $8 END,
conclude_value = CASE WHEN $6 IS NULL THEN conclude_value ELSE $9 END,
+ conclude_expr = CASE WHEN $6 IS NULL THEN conclude_expr ELSE $10 END,
updated_at = now()
WHERE id = $2 AND kb_id = $1",
)
@@ -236,6 +245,7 @@ pub async fn update(
.bind(conclusion.and_then(|c| c.type_id))
.bind(conclusion.and_then(|c| c.predicate_id))
.bind(conclusion.and_then(|c| c.value.clone()))
+ .bind(conclusion.and_then(|c| c.expr.clone()))
.execute(&mut *tx)
.await?;
if res.rows_affected() == 0 {
@@ -271,7 +281,7 @@ pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<serde_json::Value
let rules: Vec<RuleRow> = sqlx::query_as(
"SELECT r.id, r.name, r.description, r.subject_type_id, st.label,
r.conclusion, r.conclude_type_id, ct.label,
- r.conclude_predicate_id, cp.label, r.conclude_value, r.enabled,
+ r.conclude_predicate_id, cp.label, r.conclude_value, r.conclude_expr, r.enabled,
(SELECT count(*) FROM derived_facts d
WHERE d.attribute_rule_id = r.id AND d.invalidated_at IS NULL),
r.capped_at_last_run
@@ -315,6 +325,7 @@ pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<serde_json::Value
cp,
cp_label,
cv,
+ cx,
enabled,
derived,
capped,
@@ -344,6 +355,7 @@ pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<serde_json::Value
"conclude_predicate_id": cp,
"conclude_predicate_label": cp_label,
"conclude_value": cv,
+ "conclude_expr": cx,
"enabled": enabled,
"derived_count": derived,
"capped": capped,
@@ -501,13 +513,84 @@ async fn validate_conclusion(pool: &PgPool, kb_id: Uuid, c: &ConclusionInput) ->
}
attribute_predicate(pool, kb_id, p).await
}
+ // 算出来的属性(0032):谓词照旧要在,值换成一棵算式树
+ "computed" => {
+ let p = c.predicate_id.ok_or_else(|| {
+ AppError::invalid(
+ "no_predicate",
+ "A computed rule needs the attribute it sets.",
+ )
+ })?;
+ let Some(expr) = c.expr.as_ref() else {
+ return Err(AppError::invalid(
+ "no_expression",
+ "A computed rule needs the expression it computes.",
+ ));
+ };
+ // **这几条挡在入口而不是留给求值器。** 读不懂的树在求值时只会
+ // 「这条规则什么都不推」,而写它的人看不见任何理由(`not_in`
+ // 那次就是这么丢的,见 #494)
+ let reads = validate_expr(expr, 0)?;
+ if reads.is_empty() {
+ return Err(AppError::invalid(
+ "constant_expression",
+ "A computed rule that reads no attribute is a constant; set the value directly.",
+ ));
+ }
+ for r in reads {
+ attribute_predicate(pool, kb_id, r).await?;
+ }
+ attribute_predicate(pool, kb_id, p).await
+ }
_ => Err(AppError::invalid(
"bad_conclusion",
- "A conclusion is either a typing or an attribute.",
+ "A conclusion is a typing, an attribute or a computed attribute.",
)),
}
}
+/// 一棵算式树的校验,返回它读到的谓词。
+///
+/// **形状不对就说清哪里不对。** 库里的 CHECK 只管「computed 得有一棵树」,
+/// 树自己长得对不对得在这里判——否则一棵写坏的树要等到下一次物化才表现为
+/// 「这条规则不推东西」,而那时候没有任何地方说得出为什么。
+fn validate_expr(raw: &serde_json::Value, depth: usize) -> AppResult<Vec<Uuid>> {
+ use utopia_reason::rules::{Arith, MAX_EXPR_DEPTH};
+ if depth > MAX_EXPR_DEPTH {
+ return Err(AppError::invalid(
+ "expression_too_deep",
+ "That expression nests too deeply; a rule computes with a few operations, not a program.",
+ ));
+ }
+ let bad = || {
+ AppError::invalid(
+ "bad_expression",
+ "An expression is an attribute, a number, or two of those combined with + − × ÷.",
+ )
+ };
+ let obj = raw.as_object().ok_or_else(bad)?;
+ if let Some(a) = obj.get("attr") {
+ let id: Uuid = a.as_str().ok_or_else(bad)?.parse().map_err(|_| bad())?;
+ return Ok(vec![id]);
+ }
+ if let Some(c) = obj.get("const") {
+ let n = c
+ .as_f64()
+ .or_else(|| c.as_str()?.trim().parse().ok())
+ .ok_or_else(bad)?;
+ if !n.is_finite() {
+ return Err(bad());
+ }
+ return Ok(Vec::new());
+ }
+ Arith::parse(obj.get("op").and_then(|v| v.as_str()).ok_or_else(bad)?).ok_or_else(bad)?;
+ let mut reads = validate_expr(obj.get("l").ok_or_else(bad)?, depth + 1)?;
+ reads.extend(validate_expr(obj.get("r").ok_or_else(bad)?, depth + 1)?);
+ reads.sort();
+ reads.dedup();
+ Ok(reads)
+}
+
/// 条件的校验。**报错要说人话**:库里的 CHECK 只会回一个约束名。
async fn validate_conditions(
pool: &PgPool,
diff --git a/crates/utopia-store/src/reasoning.rs b/crates/utopia-store/src/reasoning.rs
index d0c08ecf..2da92b2f 100644
--- a/crates/utopia-store/src/reasoning.rs
+++ b/crates/utopia-store/src/reasoning.rs
@@ -1257,6 +1257,8 @@ type RuleDefRow = (
Option<Uuid>,
Option<Uuid>,
Option<serde_json::Value>,
+ // 算出来的结论那棵树(0032)
+ Option<serde_json::Value>,
Option<String>,
Option<String>,
);
@@ -1272,7 +1274,7 @@ async fn attribute_rules(pool: &PgPool, kb_id: Uuid) -> AppResult<LoadedRules> {
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
+ r.conclude_expr, 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
@@ -1343,8 +1345,17 @@ async fn attribute_rules(pool: &PgPool, kb_id: Uuid) -> AppResult<LoadedRules> {
}
let mut out = Vec::new();
- for (id, subject_type, conclusion, conclude_type, conclude_pred, conclude_value, iri, key) in
- rows
+ for (
+ id,
+ subject_type,
+ conclusion,
+ conclude_type,
+ conclude_pred,
+ conclude_value,
+ conclude_expr,
+ iri,
+ key,
+ ) in rows
{
if broken.contains(&id) {
continue;
@@ -1363,6 +1374,16 @@ async fn attribute_rules(pool: &PgPool, kb_id: Uuid) -> AppResult<LoadedRules> {
let Some(class) = iri.or(key) else { continue };
(Conclusion::Typing { class }, is_a)
}
+ // 算出来的结论(0032):谓词照旧,值由算式在求值时按选中的读数算
+ "computed" => {
+ let (Some(p), Some(e)) = (conclude_pred, conclude_expr) else {
+ continue;
+ };
+ let Some(expr) = parse_expr(&e, 0) else {
+ continue;
+ };
+ (Conclusion::Computed { predicate: p, expr }, p)
+ }
"attribute" => {
let (Some(p), Some(v)) = (conclude_pred, conclude_value) else {
continue;
@@ -1400,6 +1421,34 @@ async fn attribute_rules(pool: &PgPool, kb_id: Uuid) -> AppResult<LoadedRules> {
})
}
+/// 算式的 JSON 形状 → 树(0032)。
+///
+/// `{"attr": "<uuid>"} | {"const": 12.5} | {"op": "sub", "l": {…}, "r": {…}}`
+///
+/// **认不出来返回 None**,调用方整条规则跳过——一棵读不懂的算式算不出数,
+/// 而算不出数的规则不该带着半棵树去求值。深度也在这里拦:太深的树是
+/// 「有人在这里写程序」的信号(0032)。
+fn parse_expr(raw: &serde_json::Value, depth: usize) -> Option<utopia_reason::rules::Expr> {
+ use utopia_reason::rules::{Arith, Expr, MAX_EXPR_DEPTH};
+ if depth > MAX_EXPR_DEPTH {
+ return None;
+ }
+ let obj = raw.as_object()?;
+ if let Some(a) = obj.get("attr") {
+ return Some(Expr::Attr(a.as_str()?.parse().ok()?));
+ }
+ if let Some(c) = obj.get("const") {
+ let n = c.as_f64().or_else(|| c.as_str()?.trim().parse().ok())?;
+ return n.is_finite().then_some(Expr::Const(n));
+ }
+ let op = Arith::parse(obj.get("op")?.as_str()?)?;
+ Some(Expr::Arith {
+ op,
+ l: Box::new(parse_expr(obj.get("l")?, depth + 1)?),
+ r: Box::new(parse_expr(obj.get("r")?, depth + 1)?),
+ })
+}
+
/// 操作数按 op 解析。形状不对返回 None,调用方整条规则跳过。
fn parse_operand(
op: utopia_reason::rules::Op,
@@ -1427,10 +1476,18 @@ fn parse_operand(
.collect();
(!set.is_empty()).then_some(Operand::Set(set))
}
- _ => Some(Operand::Num(raw?.as_f64().or_else(|| {
- raw.and_then(|v| v.as_str())
- .and_then(|s| s.trim().parse().ok())
- })?)),
+ // 门槛可以是算出来的(0032):一个对象是算式,别的照旧是一个数。
+ // 四种操作数形状互不相同——数、两元数组、字符串数组、对象——所以
+ // 认得出来,不必再加一列说「这是哪一种」
+ _ => {
+ let raw = raw?;
+ if raw.is_object() {
+ return parse_expr(raw, 0).map(Operand::Calc);
+ }
+ Some(Operand::Num(raw.as_f64().or_else(|| {
+ raw.as_str().and_then(|s| s.trim().parse().ok())
+ })?))
+ }
}
}
@@ -1704,6 +1761,16 @@ pub async fn materialize(pool: &PgPool, kb_id: Uuid) -> AppResult<DeriveReport>
utopia_reason::rules::Conclusion::Attribute { value, .. } => {
(serde_json::json!({ "value": value }), value.clone())
}
+ // 算出来的结论:值在命中里,**每个组合各一个**(0032)。
+ // 求值器算不出数的组合根本不会产出命中,所以这里不会没有值
+ utopia_reason::rules::Conclusion::Computed { .. } => {
+ let Some(n) = h.value else { continue };
+ let Some(v) = serde_json::Number::from_f64(n) else {
+ continue;
+ };
+ let v = serde_json::Value::Number(v);
+ (serde_json::json!({ "value": v }), v)
+ }
};
let key = (
h.subject,
diff --git a/crates/utopia-store/tests/a_rule_computes_what_it_concludes.rs b/crates/utopia-store/tests/a_rule_computes_what_it_concludes.rs
new file mode 100644
index 00000000..544dac0a
--- /dev/null
+++ b/crates/utopia-store/tests/a_rule_computes_what_it_concludes.rs
@@ -0,0 +1,320 @@
+//! 算出来的结论打在真库上(0032 / #488)。
+//!
+//! 算式本身的用例在 `utopia-reason::rules`,纯逻辑、不起库。这里钉的是那一层
+//! 看不见的三样:
+//!
+//! - 一棵存进 `conclude_expr` 的树,**编译回来还是同一棵**,算得出同一个数
+//! - **算式读的那几条读数一并进前提**——「这个数凭什么」在库里也得是真的
+//! - 写坏的算式在**写的时候**就被拦下,而不是等到物化时表现成「不推东西」
+//!
+//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。
+
+use sqlx::PgPool;
+use utopia_store::business_rules::ConditionInput;
+use uuid::Uuid;
+
+struct Fixture {
+ org: Uuid,
+ kb: Uuid,
+ well: Uuid,
+ revenue: Uuid,
+ cost: Uuid,
+ margin: 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 = Uuid::now_v7();
+ let (revenue, cost, margin) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let w1 = Uuid::now_v7();
+
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'calc-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'calc-test')")
+ .bind(ws)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'calc-test')",
+ )
+ .bind(kb)
+ .bind(ws)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, 'well', 'Well')")
+ .bind(well)
+ .bind(kb)
+ .execute(pool)
+ .await?;
+ for (id, key) in [(revenue, "revenue"), (cost, "cost"), (margin, "margin")] {
+ sqlx::query(
+ "INSERT INTO relation_types (id, kb_id, key, label, kind, datatype)
+ VALUES ($1, $2, $3, $3, 'attribute', 'number')",
+ )
+ .bind(id)
+ .bind(kb)
+ .bind(key)
+ .execute(pool)
+ .await?;
+ }
+ 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,
+ revenue,
+ cost,
+ margin,
+ w1,
+ })
+}
+
+async fn attr(pool: &PgPool, f: &Fixture, predicate: Uuid, value: f64) -> 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, confidence)
+ VALUES ($1, $2, $3, $4, $5, '2023-06-01T00:00:00Z', 'day', 0.9)",
+ )
+ .bind(id)
+ .bind(f.kb)
+ .bind(f.w1)
+ .bind(predicate)
+ .bind(serde_json::json!({ "value": value }))
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+/// 只有一个条件:revenue 有记录。算式读的是 revenue 与 cost
+fn present_revenue(f: &Fixture) -> Vec<ConditionInput> {
+ vec![ConditionInput {
+ group: 0,
+ predicate_id: f.revenue,
+ op: "present".into(),
+ operand: None,
+ }]
+}
+
+fn margin_expr(f: &Fixture) -> serde_json::Value {
+ serde_json::json!({
+ "op": "sub",
+ "l": { "attr": f.revenue.to_string() },
+ "r": { "attr": f.cost.to_string() },
+ })
+}
+
+/// margin = revenue − cost,**走 `create` 写进去**(不是直接 INSERT:要过的
+/// 正是校验与序列化那一段),跑一遍,看落下来的值和前提。
+#[tokio::test]
+async fn a_computed_conclusion_lands_with_the_readings_it_read() -> 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 rev = attr(&pool, &f, f.revenue, 300.0).await?;
+ let cost = attr(&pool, &f, f.cost, 120.0).await?;
+
+ let rule = utopia_store::business_rules::create(
+ &pool,
+ f.kb,
+ "margin",
+ "",
+ f.well,
+ "computed",
+ None,
+ Some(f.margin),
+ None,
+ Some(margin_expr(&f)),
+ &present_revenue(&f),
+ )
+ .await?;
+
+ let report = utopia_store::reasoning::materialize(&pool, f.kb).await?;
+ assert_eq!(report.attribute_rules, 1, "规则要编译得出来");
+ assert_eq!(report.rule_hits, 1);
+
+ let rows: Vec<(Uuid, Option<serde_json::Value>, Option<Uuid>)> = sqlx::query_as(
+ "SELECT id, object_value, attribute_rule_id FROM derived_facts WHERE kb_id = $1",
+ )
+ .bind(f.kb)
+ .fetch_all(&pool)
+ .await?;
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0].2, Some(rule), "结论指回它的规则");
+ assert_eq!(
+ rows[0]
+ .1
+ .as_ref()
+ .and_then(|v| v.get("value"))
+ .and_then(|v| v.as_f64()),
+ Some(180.0),
+ "300 − 120"
+ );
+
+ // **算式读的两条都在前提里。** 条件只提到 revenue,可 cost 也让这个数
+ // 成立——漏掉它,这一行就说不出自己凭什么,改了 cost 也不会退场
+ let premises: Vec<(Option<Uuid>,)> = sqlx::query_as(
+ "SELECT premise_fact_id FROM fact_derivations WHERE derived_fact_id = $1 ORDER BY seq",
+ )
+ .bind(rows[0].0)
+ .fetch_all(&pool)
+ .await?;
+ let got: Vec<Uuid> = premises.into_iter().filter_map(|(x,)| x).collect();
+ assert_eq!(got.len(), 2);
+ assert!(got.contains(&rev) && got.contains(&cost));
+
+ // 改掉 cost,值跟着变——这正是「算完抄回来当断言」做不到的那一半
+ sqlx::query("UPDATE facts SET object_value = $2 WHERE id = $1")
+ .bind(cost)
+ .bind(serde_json::json!({ "value": 50.0 }))
+ .execute(&pool)
+ .await?;
+ let again = utopia_store::reasoning::materialize(&pool, f.kb).await?;
+ assert_eq!(again.invalidated, 1, "180 那一行退场");
+ assert_eq!(again.inserted, 1, "250 那一行落下");
+ let live: Vec<(Option<serde_json::Value>,)> = sqlx::query_as(
+ "SELECT object_value FROM derived_facts
+ WHERE kb_id = $1 AND invalidated_at IS NULL",
+ )
+ .bind(f.kb)
+ .fetch_all(&pool)
+ .await?;
+ assert_eq!(live.len(), 1);
+ assert_eq!(
+ live[0]
+ .0
+ .as_ref()
+ .and_then(|v| v.get("value"))
+ .and_then(|v| v.as_f64()),
+ Some(250.0)
+ );
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await?;
+ run
+}
+
+/// 缺一条读数**不落行**,而不是落一行零。没记不等于零(0032)
+#[tokio::test]
+async fn a_missing_reading_lands_nothing() -> 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.revenue, 300.0).await?;
+ utopia_store::business_rules::create(
+ &pool,
+ f.kb,
+ "margin",
+ "",
+ f.well,
+ "computed",
+ None,
+ Some(f.margin),
+ None,
+ Some(margin_expr(&f)),
+ &present_revenue(&f),
+ )
+ .await?;
+ let report = utopia_store::reasoning::materialize(&pool, f.kb).await?;
+ assert_eq!(report.rule_hits, 0, "cost 没记,margin 就不该有");
+ let n: (i64,) = sqlx::query_as("SELECT count(*) FROM derived_facts WHERE kb_id = $1")
+ .bind(f.kb)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(n.0, 0);
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await?;
+ run
+}
+
+/// 写坏的算式在**写的时候**就被拒,而不是等到物化时表现成「这条规则不推东西」。
+///
+/// `not_in` 那次(#494)正是后一种:一条读不懂的条件让整条规则被静默跳过,
+/// 而规则页上它开着、看着好好的。这一组用例是那次的教训。
+#[tokio::test]
+async fn a_broken_expression_is_refused_where_it_is_written() -> 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 {
+ for (expr, why) in [
+ (
+ serde_json::json!({ "op": "pow", "l": { "const": 2 }, "r": { "const": 3 } }),
+ "四则以外的运算不收",
+ ),
+ (
+ serde_json::json!({ "const": 12 }),
+ "一条读数都不读的算式就是个常量,该走 attribute 那一支",
+ ),
+ (
+ serde_json::json!({ "attr": "not-a-uuid" }),
+ "认不出的谓词不收",
+ ),
+ (
+ serde_json::json!({
+ "op": "sub",
+ "l": { "attr": f.revenue.to_string() },
+ "r": { "attr": Uuid::now_v7().to_string() },
+ }),
+ "不在这个库里的属性不收",
+ ),
+ ] {
+ let r = utopia_store::business_rules::create(
+ &pool,
+ f.kb,
+ &format!("r-{}", Uuid::now_v7()),
+ "",
+ f.well,
+ "computed",
+ None,
+ Some(f.margin),
+ None,
+ Some(expr),
+ &present_revenue(&f),
+ )
+ .await;
+ assert!(r.is_err(), "{why}");
+ }
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await?;
+ run
+}
diff --git a/crates/utopia-store/tests/a_rule_concludes_a_type.rs b/crates/utopia-store/tests/a_rule_concludes_a_type.rs
index 60caa0b3..0fdc47a6 100644
--- a/crates/utopia-store/tests/a_rule_concludes_a_type.rs
+++ b/crates/utopia-store/tests/a_rule_concludes_a_type.rs
@@ -597,6 +597,7 @@ async fn changing_the_conclusion_retires_the_old_one() -> anyhow::Result<()> {
type_id: None,
predicate_id: Some(verdict),
value: Some(serde_json::json!("含气")),
+ expr: None,
}),
)
.await?;
diff --git a/docs/decisions/0032-a-rule-computes-what-it-concludes.md b/docs/decisions/0032-a-rule-computes-what-it-concludes.md
index b7388335..e029ac71 100644
--- a/docs/decisions/0032-a-rule-computes-what-it-concludes.md
+++ b/docs/decisions/0032-a-rule-computes-what-it-concludes.md
@@ -1,6 +1,6 @@
# 0032 · A rule computes what it concludes
-- **Status**: cut 1 · this record. No code yet
+- **Status**: cuts 1 and 2 implemented · the record, and the capability: `Expr` in `utopia-reason` (`Attr | Const | Arith`, depth capped at `MAX_EXPR_DEPTH`), a third conclusion kind `computed` with the tree in `attribute_rules.conclude_expr` (migration `0041`), an operand that may be an expression on the comparison ops, the evaluator building the combination **before** testing conditions (a computed threshold reads the readings this round picked), every attribute the expression touched landing in the premises, and a malformed tree refused where it is written rather than skipped at materialisation · seven evaluator tests and three database tests · **the picker is the next cut**, so today an expression is reachable through the API and not through the page · reaching an attribute **across a relation** is decided in this record and not yet built
- **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 and made its conclusion a **constant**; this record makes it computable. [0029](0029-a-rule-may-say-or-once.md) widened the shape of one rule by one level of `or`; [0030](0030-a-rule-may-read-what-a-rule-concluded.md) let rules feed each other — this is the third axis and independent of both. [0002](0002-reasoning-engine.md) ruled out a user rule language, and this record says exactly what that ban does and does not forbid. [0024](0024-the-world-axis-reaches-the-second.md) governs the precision a computed bound inherits. From #488.
diff --git a/docs/decisions/README.md b/docs/decisions/README.md
index f694e4fa..7794154b 100644
--- a/docs/decisions/README.md
+++ b/docs/decisions/README.md
@@ -55,7 +55,7 @@ The test for writing one: if someone (including us) looks at a piece of code in
| 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 |
-| 0032 | [A rule computes what it concludes](0032-a-rule-computes-what-it-concludes.md) | Cut 1 · the record. A rule's conclusion is a **constant** today (`attribute_rules.conclude_value` is a JSONB literal), so a criterion about a number nobody wrote down — net pay, a margin, a ratio — gets computed elsewhere and typed back in as an assertion, losing the readings it stood on. An operand on either side becomes an expression tree over attributes: its premises are the readings it touched and its interval is their intersection, so retirement needs no new machinery. **Picked, not typed** — not because a parsed string would break the display (it would not; that reason is wrong and recorded as wrong) but because a picker cannot compose an expression over a predicate that does not exist, and because a text box grows a grammar on request. A value may be reached **across a relation** (a path has definite premises and an interval; a to-many path is just a cartesian product the evaluator already walks), while **aggregation is refused**: a `sum` asserts *these are all the readings*, a completeness claim this base cannot hold — and while recompute still retires it correctly, its proof cannot say why it was withdrawn, and nothing incremental could ever wake it. Row count, unit checking and division by zero are the costs |
+| 0032 | [A rule computes what it concludes](0032-a-rule-computes-what-it-concludes.md) | Cuts 1–2 · A rule's conclusion was a **constant** (`attribute_rules.conclude_value` is a JSONB literal), so a criterion about a number nobody wrote down — net pay, a margin, a ratio — gets computed elsewhere and typed back in as an assertion, losing the readings it stood on. An operand on either side becomes an expression tree over attributes: its premises are the readings it touched and its interval is their intersection, so retirement needs no new machinery. **Picked, not typed** — not because a parsed string would break the display (it would not; that reason is wrong and recorded as wrong) but because a picker cannot compose an expression over a predicate that does not exist, and because a text box grows a grammar on request. A value may be reached **across a relation** (a path has definite premises and an interval; a to-many path is just a cartesian product the evaluator already walks), while **aggregation is refused**: a `sum` asserts *these are all the readings*, a completeness claim this base cannot hold — and while recompute still retires it correctly, its proof cannot say why it was withdrawn, and nothing incremental could ever wake it. Row count, unit checking and division by zero are the costs |
## Not a decision record
diff --git a/migrations/0041_a_rule_computes_what_it_concludes.sql b/migrations/0041_a_rule_computes_what_it_concludes.sql
new file mode 100644
index 00000000..5827feea
--- /dev/null
+++ b/migrations/0041_a_rule_computes_what_it_concludes.sql
@@ -0,0 +1,45 @@
+-- 0032:一条规则的结论可以是**算出来的**,不只是写死的一个值。
+--
+-- 从前 `conclude_value` 是一个 JSONB 字面量,所以写得出 `grade = A`,写不出
+-- `margin = revenue − cost`——那个数只好在别处算完再当断言录回来,既丢了它
+-- 站着的那两条读数,又在任一条读数变了之后立刻过期。
+--
+-- 结论多一支 `computed`:谓词照旧在 `conclude_predicate_id`,怎么算在
+-- `conclude_expr` 里,存的是一棵树而不是一个字符串:
+--
+-- {"attr": "<uuid>"} | {"const": 12.5} | {"op": "sub", "l": {…}, "r": {…}}
+--
+-- **树而不是字符串**,是因为界面照着它渲染、求值照着它算,两者不会漂移;
+-- 存字符串再现解析,就等于把「跑的是什么」和「显示的是什么」分成两件事
+-- (0002 拒掉用户自定义规则语言时,真正在守的是这一条)。
+ALTER TABLE attribute_rules ADD COLUMN conclude_expr JSONB;
+
+-- 三支各填各的那几列,填串了直接挡住。老的两支一个字没动
+ALTER TABLE attribute_rules DROP CONSTRAINT attribute_rule_conclusion_shape;
+ALTER TABLE attribute_rules ADD CONSTRAINT attribute_rule_conclusion_shape CHECK (
+ (conclusion = 'typing'
+ AND conclude_type_id IS NOT NULL
+ AND conclude_predicate_id IS NULL
+ AND conclude_value IS NULL
+ AND conclude_expr IS NULL)
+ OR
+ (conclusion = 'attribute'
+ AND conclude_type_id IS NULL
+ AND conclude_predicate_id IS NOT NULL
+ AND conclude_value IS NOT NULL
+ AND conclude_expr IS NULL)
+ OR
+ (conclusion = 'computed'
+ AND conclude_type_id IS NULL
+ AND conclude_predicate_id IS NOT NULL
+ AND conclude_value IS NULL
+ AND conclude_expr IS NOT NULL)
+);
+ALTER TABLE attribute_rules DROP CONSTRAINT IF EXISTS attribute_rules_conclusion_check;
+ALTER TABLE attribute_rules
+ ADD CONSTRAINT attribute_rules_conclusion_check
+ CHECK (conclusion IN ('typing', 'attribute', 'computed'));
+
+-- 条件那边**一列都不用加**:`operand` 本来就是 JSONB,一个数是数、一个区间是
+-- 两元数组、一个集合是字符串数组,而算式是个对象——四种形状互不相同,读的时候
+-- 认得出来。那条 CHECK 只管「present 不带操作数、别的都得带」,照旧成立。