Skip to content

World's first open-source enterprise world model.

Keep Y-only rules within their subject class (#1210)

Danielac023d0518d1
diff --git a/crates/utopia-reason/src/rules.rs b/crates/utopia-reason/src/rules.rs
index 93d70163..9f5dd0cb 100644
--- a/crates/utopia-reason/src/rules.rs
+++ b/crates/utopia-reason/src/rules.rs
@@ -264,6 +264,8 @@ pub fn evaluate(
///
/// `facts` stays scoped to the conclusion's subject type. A one-hop join can
/// reach another entity type, so its conditions read from `pool_facts`.
+/// A joined X may have no attribute facts, so callers must also scope `edges`
+/// by their subjects or add an X-side scope condition.
pub fn evaluate_with_pool(
rules: &[BusinessRule],
facts: &[AttrFact],
diff --git a/crates/utopia-store/src/reasoning.rs b/crates/utopia-store/src/reasoning.rs
index de49b18d..61bdd4e1 100644
--- a/crates/utopia-store/src/reasoning.rs
+++ b/crates/utopia-store/src/reasoning.rs
@@ -1807,8 +1807,7 @@ async fn descendants_of(conn: &mut PgConnection, kb_id: Uuid, root: Uuid) -> App
Ok(rows.into_iter().map(|(id,)| id).collect())
}
-/// 属性事实查询回来的一行:事实、主语、谓词、字面值、区间两端与精度、置信度,
-/// 以及主语当下的断言类型(规则要按主类过滤)
+/// 属性事实查询回来的一行:事实、主语、谓词、字面值、区间两端与精度、置信度和证据日期。
type AttrFactRow = (
Uuid,
Uuid,
@@ -1819,7 +1818,6 @@ type AttrFactRow = (
Option<String>,
Option<String>,
f32,
- Option<Uuid>,
Option<chrono::DateTime<chrono::Utc>>,
Option<chrono::DateTime<chrono::Utc>>,
);
@@ -1835,12 +1833,11 @@ async fn attribute_facts(
Vec<utopia_reason::rules::AttrFact>,
HashMap<Uuid, (Option<i64>, Option<i64>)>,
HashMap<Uuid, PremiseMeta>,
- HashMap<Uuid, Option<Uuid>>,
)> {
let rows: Vec<AttrFactRow> = sqlx::query_as(
"SELECT f.id, f.subject_id, f.predicate_id, f.object_value,
f.valid_from, f.valid_to, f.valid_from_precision, f.valid_to_precision,
- f.confidence, e.type_id, f.attested_from, f.attested_to
+ f.confidence, f.attested_from, f.attested_to
FROM facts f
JOIN entities e ON e.id = f.subject_id
WHERE f.kb_id = $1
@@ -1856,21 +1853,7 @@ async fn attribute_facts(
let mut facts = Vec::with_capacity(rows.len());
let mut spans = HashMap::new();
let mut meta = HashMap::new();
- let mut type_of = HashMap::new();
- for (
- id,
- subject,
- predicate,
- value,
- from,
- to,
- fp,
- tp,
- conf,
- type_id,
- attested_from,
- attested_to,
- ) in rows
+ for (id, subject, predicate, value, from, to, fp, tp, conf, attested_from, attested_to) in rows
{
// 与公理那一路同一种读法(0022):读数没日期就从它的文档起算。
// 属性一律是状态(建属性时固定 state,界面也不给改)
@@ -1894,9 +1877,8 @@ async fn attribute_facts(
});
spans.insert(id, (f, t));
meta.insert(id, (fp, tp, conf, fa, ta));
- type_of.insert(subject, type_id);
}
- Ok((facts, spans, meta, type_of))
+ Ok((facts, spans, meta))
}
/// 推一遍,把派生事实落进账本。
@@ -2105,7 +2087,16 @@ async fn resolve(conn: &mut PgConnection, kb_id: Uuid) -> AppResult<Resolved> {
// 落库那边的陈旧对账扫的是整张 `derived_facts`,两趟各做各的 diff 会把对方
// 落的行每一轮都判成陈旧
if !loaded.rules.is_empty() {
- let (asserted, attr_spans, attr_meta, type_of) = attribute_facts(&mut *conn, kb_id).await?;
+ let (asserted, attr_spans, attr_meta) = attribute_facts(&mut *conn, kb_id).await?;
+ // 只读 Y 的连接规则不要求 X 有属性;主类范围必须独立从实体读取。
+ let entity_types: Vec<(Uuid, Uuid)> = sqlx::query_as(
+ "SELECT id, type_id FROM entities
+ WHERE kb_id = $1 AND merged_into IS NULL AND type_id IS NOT NULL",
+ )
+ .bind(kb_id)
+ .fetch_all(&mut *conn)
+ .await?;
+ let type_of: HashMap<Uuid, Uuid> = entity_types.into_iter().collect();
asserted_ids.extend(asserted.iter().map(|f| f.id));
// 前提的精度与置信度:落地那一段与不动点这一段共用,所以两份 meta 先合起来;
// 区间也要——认出派生的哪一端是被前提的锚点顶上来的,靠的就是它
@@ -2186,16 +2177,17 @@ async fn resolve(conn: &mut PgConnection, kb_id: Uuid) -> AppResult<Resolved> {
let mut fresh: Vec<(usize, utopia_reason::rules::RuleHit)> = Vec::new();
capped_by_rule.clear();
for (ri, lr) in loaded.rules.iter().enumerate() {
+ let matches_asserted_scope = |subject: &Uuid| {
+ type_of
+ .get(subject)
+ .is_some_and(|t| lr.subject_types.contains(t))
+ };
// 主类是断言的:范围是个筛子,不带区间、不进前提
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))
- {
+ if matches_asserted_scope(&f.subject) {
by_assertion.push(f.clone());
} else if derived_types
.get(&f.subject)
@@ -2204,12 +2196,24 @@ async fn resolve(conn: &mut PgConnection, kb_id: Uuid) -> AppResult<Resolved> {
by_conclusion.push(f.clone());
}
}
+ // X 从连接边枚举,只筛属性挡不住一组全部读取 Y 的条件。
+ let assertion_edges: Vec<_> = if let Some(join_predicate) = lr.rule.join_predicate {
+ evaluation_edges
+ .iter()
+ .filter(|e| {
+ e.predicate == join_predicate && matches_asserted_scope(&e.subject)
+ })
+ .cloned()
+ .collect()
+ } else {
+ Vec::new()
+ };
let (hits, rr) = utopia_reason::rules::evaluate_with_pool(
std::slice::from_ref(&lr.rule),
&by_assertion,
&fact_pool,
&spans,
- &evaluation_edges,
+ &assertion_edges,
);
let mut capped = rr.capped;
fresh.extend(hits.into_iter().map(|h| (ri, h)));
diff --git a/crates/utopia-store/tests/a_rule_concludes_a_relation.rs b/crates/utopia-store/tests/a_rule_concludes_a_relation.rs
index 3a926ffa..e01ba2d9 100644
--- a/crates/utopia-store/tests/a_rule_concludes_a_relation.rs
+++ b/crates/utopia-store/tests/a_rule_concludes_a_relation.rs
@@ -5,6 +5,7 @@
//! may be any entity the declared join reaches. It also checks that the
//! persisted row carries its object and the full three-part proof.
+use chrono::{DateTime, Utc};
use sqlx::PgPool;
use utopia_store::business_rules::{self, ConclusionInput, ConditionInput};
use uuid::Uuid;
@@ -29,6 +30,8 @@ type DerivedRows = Vec<(
chrono::DateTime<chrono::Utc>,
)>;
+type TimedRelationRow = (Uuid, Uuid, Option<Uuid>, DateTime<Utc>, DateTime<Utc>);
+
async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {
let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
let (well, field) = (Uuid::now_v7(), Uuid::now_v7());
@@ -327,6 +330,224 @@ async fn dropping_the_join_is_refused_while_the_rule_keeps_y_conditions() -> any
run
}
+#[tokio::test]
+async fn a_y_only_join_scopes_x_without_requiring_x_attributes() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ utopia_store::db::migrate(&pool).await?;
+ let f = seed(&pool).await?;
+
+ let run = async {
+ let (horizontal_well, plant_type) = (Uuid::now_v7(), Uuid::now_v7());
+ let (subclass_subject, plant_subject) = (Uuid::now_v7(), Uuid::now_v7());
+ sqlx::query(
+ "INSERT INTO entity_types (id, kb_id, key, label)
+ VALUES ($1, $2, 'horizontal_well', 'HorizontalWell'), ($3, $2, 'plant', 'Plant')",
+ )
+ .bind(horizontal_well)
+ .bind(f.kb)
+ .bind(plant_type)
+ .execute(&pool)
+ .await?;
+ sqlx::query("INSERT INTO entity_type_parents (child_id, parent_id) VALUES ($1, $2)")
+ .bind(horizontal_well)
+ .bind(f.well)
+ .execute(&pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO entities (id, kb_id, type_id, canonical_name)
+ VALUES ($1, $2, $3, 'HW-1'), ($4, $2, $5, 'P-1')",
+ )
+ .bind(subclass_subject)
+ .bind(f.kb)
+ .bind(horizontal_well)
+ .bind(plant_subject)
+ .bind(plant_type)
+ .execute(&pool)
+ .await?;
+ // None of the three subjects has attributes; only Y supplies the reading.
+ attr(&pool, &f, f.y, f.pressure, 120.0, "2024-01-15T00:00:00Z").await?;
+ let join = edge(
+ &pool,
+ &f,
+ f.supplies,
+ "2024-01-01T00:00:00Z",
+ "2024-02-01T00:00:00Z",
+ )
+ .await?;
+ for subject in [subclass_subject, plant_subject] {
+ sqlx::query(
+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id,
+ valid_from, valid_from_precision, valid_to, valid_to_precision,
+ confidence)
+ SELECT $1, kb_id, $2, predicate_id, object_id,
+ valid_from, valid_from_precision, valid_to, valid_to_precision, confidence
+ FROM facts WHERE id = $3",
+ )
+ .bind(Uuid::now_v7())
+ .bind(subject)
+ .bind(join)
+ .execute(&pool)
+ .await?;
+ }
+ let rule = business_rules::create(
+ &pool,
+ f.kb,
+ "a Well connected to a high-pressure Field",
+ "",
+ f.well,
+ "relation",
+ None,
+ Some(f.upstream_of),
+ None,
+ None,
+ Some(f.supplies),
+ &pressure_condition(&f, "y"),
+ )
+ .await?;
+ utopia_store::reasoning::materialize(&pool, f.kb).await?;
+ let subjects: Vec<Uuid> = sqlx::query_scalar(
+ "SELECT subject_id FROM derived_facts
+ WHERE kb_id = $1 AND attribute_rule_id = $2 AND invalidated_at IS NULL",
+ )
+ .bind(f.kb)
+ .bind(rule)
+ .fetch_all(&pool)
+ .await?;
+ assert_eq!(subjects.len(), 2, "only Well and its subclass may conclude");
+ assert!(subjects.contains(&f.x));
+ assert!(subjects.contains(&subclass_subject));
+ assert!(!subjects.contains(&plant_subject));
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await?;
+ run
+}
+
+#[tokio::test]
+async fn a_y_only_join_keeps_a_concluded_class_in_its_proof() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ utopia_store::db::migrate(&pool).await?;
+ let f = seed(&pool).await?;
+
+ let run = async {
+ let gas_well = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, 'gas_well', 'GasWell')",
+ )
+ .bind(gas_well)
+ .bind(f.kb)
+ .execute(&pool)
+ .await?;
+ let x_pressure = attr(&pool, &f, f.x, f.pressure, 120.0, "2024-01-01T00:00:00Z").await?;
+ sqlx::query(
+ "UPDATE facts SET valid_to = '2024-02-01T00:00:00Z', valid_to_precision = 'day' WHERE id = $1",
+ )
+ .bind(x_pressure)
+ .execute(&pool)
+ .await?;
+ let y_pressure = attr(&pool, &f, f.y, f.pressure, 120.0, "2024-01-15T00:00:00Z").await?;
+ let join = edge(
+ &pool,
+ &f,
+ f.supplies,
+ "2024-01-01T00:00:00Z",
+ "2024-03-01T00:00:00Z",
+ )
+ .await?;
+ // The same pair's later edge falls entirely outside its concluded GasWell interval.
+ edge(
+ &pool,
+ &f,
+ f.supplies,
+ "2024-04-01T00:00:00Z",
+ "2024-05-01T00:00:00Z",
+ )
+ .await?;
+ let typing_rule = business_rules::create(
+ &pool,
+ f.kb,
+ "high pressure makes a GasWell",
+ "",
+ f.well,
+ "typing",
+ Some(gas_well),
+ None,
+ None,
+ None,
+ None,
+ &pressure_condition(&f, "x"),
+ )
+ .await?;
+ let relation_rule = business_rules::create(
+ &pool,
+ f.kb,
+ "a GasWell connected to a high-pressure Field",
+ "",
+ gas_well,
+ "relation",
+ None,
+ Some(f.upstream_of),
+ None,
+ None,
+ Some(f.supplies),
+ &pressure_condition(&f, "y"),
+ )
+ .await?;
+ utopia_store::reasoning::materialize(&pool, f.kb).await?;
+ let rows: Vec<TimedRelationRow> = sqlx::query_as(
+ "SELECT id, subject_id, object_id, valid_from, valid_to FROM derived_facts
+ WHERE kb_id = $1 AND attribute_rule_id = $2 AND invalidated_at IS NULL",
+ )
+ .bind(f.kb)
+ .bind(relation_rule)
+ .fetch_all(&pool)
+ .await?;
+ assert_eq!(rows.len(), 1, "the disjoint join must not conclude a relation");
+ let (derived, subject, object, from, to) = rows[0];
+ assert_eq!((subject, object), (f.x, Some(f.y)));
+ assert_eq!(from.to_rfc3339(), "2024-01-15T00:00:00+00:00");
+ assert_eq!(to.to_rfc3339(), "2024-02-01T00:00:00+00:00");
+ let concluded_class: Uuid = sqlx::query_scalar(
+ "SELECT id FROM derived_facts
+ WHERE kb_id = $1 AND attribute_rule_id = $2 AND invalidated_at IS NULL",
+ )
+ .bind(f.kb)
+ .bind(typing_rule)
+ .fetch_one(&pool)
+ .await?;
+ let premises: 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(derived)
+ .fetch_all(&pool)
+ .await?;
+ assert_eq!(premises.len(), 3);
+ assert!(premises.contains(&(Some(y_pressure), None)));
+ assert!(premises.contains(&(Some(join), None)));
+ assert!(premises.contains(&(None, Some(concluded_class))));
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await?;
+ run
+}
+
#[tokio::test]
async fn a_joined_rule_reads_the_other_side_of_a_declared_edge() -> anyhow::Result<()> {
let Some(url) = utopia_store::test_db::url() else {