Skip to content

World's first open-source enterprise world model.

The ontology decides a pushed phrase it declares (#1245)

Szabo Bogdan962d06b5ac25
diff --git a/crates/utopia-cli/src/main.rs b/crates/utopia-cli/src/main.rs
index 3d700e9d..7a9ba501 100644
--- a/crates/utopia-cli/src/main.rs
+++ b/crates/utopia-cli/src/main.rs
@@ -82,7 +82,7 @@ struct ManifestDataDir {
/// not a side effect of a code change.
// 是迁移文件的**个数**,不是最大的编号(守卫 `schema_version_policy_compares_against_current`
// 按个数比):编号有空缺时两者不同——0071 由一个开放 PR 占着,0072 先落,个数是 71
-const CURRENT_SCHEMA_VERSION: u32 = 100;
+const CURRENT_SCHEMA_VERSION: u32 = 101;
fn main() -> anyhow::Result<()> {
dotenvy::dotenv().ok();
diff --git a/crates/utopia-server/src/extraction_open.rs b/crates/utopia-server/src/extraction_open.rs
index 7e60a624..cf7e0302 100644
--- a/crates/utopia-server/src/extraction_open.rs
+++ b/crates/utopia-server/src/extraction_open.rs
@@ -1150,6 +1150,21 @@ pub(crate) async fn run_open(
serde_json::json!({ "kb_id": kb_id }),
)
.await?;
+ // 推送来的文档(0054):短语正好是一条声明了的关系的签名,本体当场判(#1242);再排一份
+ // 物化,绑着的签名下新来的陈述不等对齐器跑完就成类型化行——没配对话模型的库,对齐器
+ // 一次也不会跑完。排着就不重复:连推一百篇只算一遍
+ if pushed {
+ let bound = crate::phrase_alignment::bind_declared(pool, kb_id, document_id).await?;
+ if bound > 0 {
+ tracing::info!(%document_id, bound, "推送的短语按声明的关系绑上");
+ }
+ utopia_store::jobs::enqueue_unless_queued(
+ pool,
+ utopia_store::phrase_bindings::MATERIALIZE_KIND,
+ serde_json::json!({ "kb_id": kb_id }),
+ )
+ .await?;
+ }
// 队列里多了东西才叫醒人:Review 的计数与对话里那张确认卡都靠这一声
if pending_count > 0 {
tracing::info!(%document_id, pending_count, "记忆抽出的陈述进了待确认队列");
diff --git a/crates/utopia-server/src/phrase_alignment.rs b/crates/utopia-server/src/phrase_alignment.rs
index c158788b..8082f7be 100644
--- a/crates/utopia-server/src/phrase_alignment.rs
+++ b/crates/utopia-server/src/phrase_alignment.rs
@@ -163,6 +163,118 @@ fn invalid_agent_direction(
})
}
+/// 这条关系叫这个短语:键或标签归一后与它相等(同类别词的归一)。像不算——
+/// 「validated by tests」不是 validated_by,那是模型的题
+fn named_by(p: &RelationTypeView, phrase: &str) -> bool {
+ phrase_bindings::normalize(&p.key) == phrase || phrase_bindings::normalize(&p.label) == phrase
+}
+
+/// 签名的短语正好是一条声明了的关系(#1242):它叫这个短语,主语的类落在声明的域里、
+/// 宾语的类落在值域里(经继承也算),只认正向。域或值域没声明的不算——没声明是「不限」,
+/// 不是「就是它」;一端没有类的也不算。状态关系不算:绑上它还得说只带一个日期的陈述那个
+/// 日期标哪一端(`marks`,#966),本体答不了,留给对齐器——它绑上、顺带问这一格,问不到的
+/// 进队列等人。叫这个短语、两端也都对得上的不止一条,谁也不认:两条关系叫得一样,该由人
+/// 或模型来挑
+fn declared<'a>(
+ sig: &PhraseSignature,
+ props: &'a [RelationTypeView],
+ closure: &Closure,
+) -> Option<&'a RelationTypeView> {
+ if sig.object_is_value {
+ return None;
+ }
+ let mut fitting = props.iter().filter(|p| {
+ p.kind == "relation"
+ && p.temporal != "state"
+ && !p.domains.is_empty()
+ && !p.ranges.is_empty()
+ && named_by(p, &sig.phrase)
+ && fits_direction(p, sig, closure, Direction::Forward).is_some()
+ });
+ let only = fitting.next()?;
+ fitting.next().is_none().then_some(only)
+}
+
+/// 对齐器不再判的判定:人的;本体判的、此刻仍是它声明的那条关系的。本体判的行没有指纹,
+/// 按指纹比永远「过期」——不先放过它,每轮都会把它送去问模型、收尾时又以为变了再排一份
+fn settled(
+ b: &phrase_bindings::Binding,
+ sig: &PhraseSignature,
+ props: &[RelationTypeView],
+ closure: &Closure,
+) -> bool {
+ b.decided_by == "person"
+ || (b.decided_by == "ontology"
+ && b.relation_type_id.is_some()
+ && declared(sig, props, closure).map(|p| p.id) == b.relation_type_id)
+}
+
+/// 推送来的文档抽完(0054):它的陈述落在的签名里,短语正好是一条声明了的关系的,由本体
+/// 直接绑上,记成本体判的(#1242)。不问模型,没配对话模型也照判;别的签名照旧留给对齐器。
+/// 判定照旧是签名上的一行(0044 决定 3),人看得见、改得了;人的判定不动(`decide_on`
+/// 的规矩),已经由本体按同一条关系判过的不重写——判定时刻和回归记录不该随每次推送翻新。
+/// 返回写下的判定数
+pub(crate) async fn bind_declared(
+ pool: &sqlx::PgPool,
+ kb_id: Uuid,
+ document_id: Uuid,
+) -> anyhow::Result<usize> {
+ let props = utopia_store::ontology::relation_type_views(pool, kb_id).await?;
+ let keys: HashSet<SignatureKey> =
+ phrase_bindings::signature_keys_of_document(pool, kb_id, document_id)
+ .await?
+ .into_iter()
+ .filter(|(phrase, ..)| props.iter().any(|p| named_by(p, phrase)))
+ .collect();
+ // 多数推送没有一个短语叫得出关系的名字:库级的签名就不必数了
+ if keys.is_empty() {
+ return Ok(0);
+ }
+ let classes = utopia_store::graph::entity_types(pool, kb_id).await?;
+ let closure = closures(classes.iter().map(|c| (c.id, c.parents.as_slice())));
+ let existing: HashMap<_, _> = phrase_bindings::bindings(pool, kb_id)
+ .await?
+ .into_iter()
+ .map(|b| (b.key(), b))
+ .collect();
+ let mut written = 0;
+ for s in phrase_bindings::signatures(pool, kb_id)
+ .await?
+ .iter()
+ .filter(|s| keys.contains(&s.key()))
+ {
+ let Some(p) = declared(s, &props, &closure) else {
+ continue;
+ };
+ if existing
+ .get(&s.key())
+ .is_some_and(|b| settled(b, s, &props, &closure))
+ {
+ continue;
+ }
+ if phrase_bindings::decide(
+ pool,
+ kb_id,
+ s,
+ Decision {
+ relation_type_id: Some(p.id),
+ direction: Some(Direction::Forward.as_str()),
+ status: "bound",
+ votes: &serde_json::json!({ "reason": "declared_relation" }),
+ decided_by: "ontology",
+ basis: None,
+ marks: None,
+ marks_asked: false,
+ },
+ )
+ .await?
+ {
+ written += 1;
+ }
+ }
+ Ok(written)
+}
+
/// 签名的键:短语 + 两端的类 + 宾语是不是字面值(与 `PhraseSignature::key` 同形)
type SignatureKey = (String, Option<Uuid>, Option<Uuid>, bool);
/// 每条签名此刻的候选与指纹
@@ -614,14 +726,14 @@ async fn align_phrases_locked(
let short = shortlist(state, settings, kb_id, &sigs, &full).await?;
let considered = consider(&sigs, &props, &closure, &versions, Some(&short));
// 过期 = 存下的指纹和此刻的不一样(没有指纹的是这一列出现前判的,各重判一次)。
- // 不再按时间戳:父边的增删、请求途中的编辑(#795)时间戳看不见。人的判定不重判。
- // 绑到状态属性、从没问过一刻标哪一端的代理判定也问(`awaits_marks`,#966)
+ // 不再按时间戳:父边的增删、请求途中的编辑(#795)时间戳看不见。人的判定、本体仍认的
+ // 判定(`settled`)不重判。绑到状态属性、从没问过一刻标哪一端的代理判定也问(`awaits_marks`,#966)
let todo: Vec<&PhraseSignature> = sigs
.iter()
.filter(|s| match existing.get(&s.key()) {
None => true,
Some(b) => {
- b.decided_by != "person"
+ !settled(b, s, &props, &closure)
&& (b.basis.as_deref() != Some(considered[&s.key()].1.as_str())
|| awaits_marks(b, &props)
|| invalid_agent_direction(b, s, &props, &closure))
@@ -1267,7 +1379,7 @@ async fn align_phrases_locked(
sigs.iter().any(|s| match now.get(&s.key()) {
None => !attempted.contains(&s.key()),
Some(b) => {
- b.decided_by != "person"
+ !settled(b, s, &props, &closure)
&& b.basis.as_deref() != Some(now_considered[&s.key()].1.as_str())
}
})
@@ -1322,6 +1434,10 @@ async fn align_phrases_locked(
#[path = "phrase_alignment_tests.rs"]
mod lifecycle_tests;
+#[cfg(test)]
+#[path = "phrase_alignment_declared_tests.rs"]
+mod declared_tests;
+
#[cfg(test)]
mod tests {
#[test]
diff --git a/crates/utopia-server/src/phrase_alignment_declared_tests.rs b/crates/utopia-server/src/phrase_alignment_declared_tests.rs
new file mode 100644
index 00000000..ac2a8cce
--- /dev/null
+++ b/crates/utopia-server/src/phrase_alignment_declared_tests.rs
@@ -0,0 +1,441 @@
+//! 推送来的短语正好是一条声明了的关系(#1242):本体自己判,不问模型。只认键或标签
+//! 归一后相等、两端的类落在域与值域里、只有一条对得上的;人的判定不动;推送的文档抽完
+//! 排一份物化。真库、推送路径(0054),没有对话模型。
+use super::*;
+use serde_json::{json, Value};
+use std::sync::Arc;
+use utopia_store::{materialize, phrase_bindings};
+
+/// 一个库:类 statement、test、other,三个类别词都已绑上;关系 validated_by 声明在
+/// statement → test;一个 `statements` 来源
+struct Rig {
+ pool: sqlx::PgPool,
+ state: AppState,
+ org: Uuid,
+ ws: Uuid,
+ kb: Uuid,
+ source: Uuid,
+ statement: Uuid,
+ test: Uuid,
+ other: Uuid,
+ validated_by: Uuid,
+ _dir: tempfile::TempDir,
+}
+
+impl Rig {
+ async fn new() -> anyhow::Result<Option<Self>> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(None);
+ };
+ let pool = sqlx::PgPool::connect(&url).await?;
+ utopia_store::db::migrate(&pool).await?;
+ let (org, ws, kb, source, statement, test, other, validated_by) = (
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ );
+ sqlx::raw_sql(&format!(
+ "INSERT INTO organizations(id,name) VALUES ('{org}','declared-binding');
+ INSERT INTO workspaces(id,org_id,name) VALUES ('{ws}','{org}','declared-binding');
+ INSERT INTO knowledge_bases(id,workspace_id,name) VALUES ('{kb}','{ws}','declared-binding');
+ INSERT INTO sources(id,kb_id,kind,name) VALUES ('{source}','{kb}','statements','ci');
+ INSERT INTO entity_types(id,kb_id,key,label,color,shape) VALUES
+ ('{statement}','{kb}','statement','Statement','#000','circle'),
+ ('{test}','{kb}','test','Test','#000','circle'),
+ ('{other}','{kb}','other','Other','#000','circle');
+ INSERT INTO type_bindings(id,kb_id,kind_word,type_id,status,decided_by) VALUES
+ ('{}','{kb}','statement','{statement}','bound','person'),
+ ('{}','{kb}','test','{test}','bound','person'),
+ ('{}','{kb}','other','{other}','bound','person');
+ INSERT INTO relation_types(id,kb_id,key,label,kind,temporal,description) VALUES
+ ('{validated_by}','{kb}','validated_by','validatedBy','relation','eternal','a test that validates a statement');
+ INSERT INTO relation_type_domains(relation_type_id,entity_type_id) VALUES ('{validated_by}','{statement}');
+ INSERT INTO relation_type_ranges(relation_type_id,entity_type_id) VALUES ('{validated_by}','{test}');",
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ ))
+ .execute(&pool)
+ .await?;
+ let dir = tempfile::tempdir()?;
+ let cfg = utopia_core::config::AppConfig {
+ data_dir: dir.path().to_string_lossy().into_owned(),
+ ..Default::default()
+ };
+ let search = Arc::new(utopia_search::SearchIndex::open(
+ &dir.path().join("search"),
+ )?);
+ let state = AppState::new(pool.clone(), &cfg, search, "test-only".into());
+ Ok(Some(Self {
+ pool,
+ state,
+ org,
+ ws,
+ kb,
+ source,
+ statement,
+ test,
+ other,
+ validated_by,
+ _dir: dir,
+ }))
+ }
+
+ /// 推一篇文档并抽取:一条陈述,写成 [主语, 它的类别词, 短语, 宾语, 它的类别词]
+ async fn push(&self, external_id: &str, said: [&str; 5]) -> anyhow::Result<()> {
+ let [subject, subject_kind, phrase, object, object_kind] = said;
+ let payload: Value = json!({
+ "external_id": external_id,
+ "e": [[subject, subject_kind, true], [object, object_kind, true]],
+ "s": [[null, subject, phrase, object, null, {}, null, null]],
+ "n": []
+ });
+ let (doc, chunk) = (Uuid::now_v7(), Uuid::now_v7());
+ sqlx::query(
+ "INSERT INTO documents(id,kb_id,filename,sha256,source_id) VALUES ($1,$2,$3,$4,$5)",
+ )
+ .bind(doc)
+ .bind(self.kb)
+ .bind(format!("{external_id}.json"))
+ .bind(format!("x{doc}"))
+ .bind(self.source)
+ .execute(&self.pool)
+ .await?;
+ sqlx::query("INSERT INTO chunks(id,kb_id,document_id,seq,text) VALUES ($1,$2,$3,0,$4)")
+ .bind(chunk)
+ .bind(self.kb)
+ .bind(doc)
+ .bind(serde_json::to_string_pretty(&payload)?)
+ .execute(&self.pool)
+ .await?;
+ crate::extraction::extract_document(
+ &self.state,
+ doc,
+ utopia_core::models::Proposer::default(),
+ )
+ .await
+ }
+
+ async fn bindings(&self) -> anyhow::Result<Vec<phrase_bindings::Binding>> {
+ Ok(phrase_bindings::bindings(&self.pool, self.kb).await?)
+ }
+
+ /// statement → test 这条签名
+ fn signature(&self, phrase: &str) -> PhraseSignature {
+ PhraseSignature {
+ phrase: phrase.into(),
+ subject_type_id: Some(self.statement),
+ subject_type_key: Some("statement".into()),
+ object_type_id: Some(self.test),
+ object_type_key: Some("test".into()),
+ object_is_value: false,
+ count: 1,
+ examples: Vec::new(),
+ quotes: Vec::new(),
+ example_statement_ids: Vec::new(),
+ }
+ }
+
+ /// 配上一个不通的对话端点:对齐照跑,真问了模型这一轮会记失败、再排
+ async fn unreachable_model(&self) -> anyhow::Result<()> {
+ utopia_store::settings::upsert(
+ &self.pool,
+ self.ws,
+ Some("http://127.0.0.1:9"),
+ None,
+ Some("unreachable"),
+ None,
+ None,
+ None,
+ None,
+ )
+ .await?;
+ Ok(())
+ }
+
+ async fn queued(&self, kind: &str) -> anyhow::Result<i64> {
+ Ok(sqlx::query_scalar(
+ "SELECT count(*) FROM jobs WHERE kind=$1 AND status='queued' AND payload->>'kb_id'=$2",
+ )
+ .bind(kind)
+ .bind(self.kb.to_string())
+ .fetch_one(&self.pool)
+ .await?)
+ }
+
+ async fn clear_jobs(&self) -> anyhow::Result<()> {
+ sqlx::query(
+ "DELETE FROM jobs WHERE payload->>'kb_id'=$1
+ OR payload->>'document_id' IN (SELECT id::text FROM documents WHERE kb_id=$2)",
+ )
+ .bind(self.kb.to_string())
+ .bind(self.kb)
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ async fn cleanup(self) -> anyhow::Result<()> {
+ self.clear_jobs().await?;
+ sqlx::query("DELETE FROM organizations WHERE id=$1")
+ .bind(self.org)
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+}
+
+#[tokio::test]
+async fn a_pushed_phrase_equal_to_a_declared_relation_binds_and_materializes_without_a_model(
+) -> anyhow::Result<()> {
+ let Some(rig) = Rig::new().await? else {
+ return Ok(());
+ };
+ rig.push("obs-1", ["S-1", "statement", "validated_by", "T-1", "test"])
+ .await?;
+ let found: Vec<_> = rig
+ .bindings()
+ .await?
+ .into_iter()
+ .map(|b| {
+ (
+ b.phrase,
+ b.status,
+ b.relation_type_id,
+ b.direction,
+ b.decided_by,
+ )
+ })
+ .collect();
+ assert_eq!(
+ found,
+ vec![(
+ "validated_by".to_string(),
+ "bound".to_string(),
+ Some(rig.validated_by),
+ Some("forward".to_string()),
+ "ontology".to_string(),
+ )]
+ );
+ materialize::materialize(&rig.pool, rig.kb).await?;
+ assert_eq!(materialize::count(&rig.pool, rig.kb).await?, 1);
+ rig.cleanup().await
+}
+
+/// 像不算、两端不在域与值域里不算、两条关系叫同一个名字也不算:这些都留给对齐器。
+/// 同一个库里那条恰好对得上的照样绑上,否则「什么都没绑」什么也证明不了
+#[tokio::test]
+async fn only_a_phrase_naming_one_relation_that_fits_both_ends_binds() -> anyhow::Result<()> {
+ let Some(rig) = Rig::new().await? else {
+ return Ok(());
+ };
+ let (checked_by, reviewed_by) = (Uuid::now_v7(), Uuid::now_v7());
+ sqlx::raw_sql(&format!(
+ "INSERT INTO relation_types(id,kb_id,key,label,kind,temporal,description) VALUES
+ ('{checked_by}','{kb}','checked_by','checkedBy','relation','eternal',''),
+ ('{reviewed_by}','{kb}','reviewed_by','checked_by','relation','eternal','');
+ INSERT INTO relation_type_domains(relation_type_id,entity_type_id) VALUES
+ ('{checked_by}','{s}'), ('{reviewed_by}','{s}');
+ INSERT INTO relation_type_ranges(relation_type_id,entity_type_id) VALUES
+ ('{checked_by}','{t}'), ('{reviewed_by}','{t}');",
+ kb = rig.kb,
+ s = rig.statement,
+ t = rig.test,
+ ))
+ .execute(&rig.pool)
+ .await?;
+ for (n, said) in [
+ ["S-1", "statement", "validated_by", "T-1", "test"],
+ ["S-2", "statement", "validated by tests", "T-2", "test"],
+ ["O-3", "other", "validated_by", "T-3", "test"],
+ ["T-4", "test", "validated_by", "S-4", "statement"],
+ ["S-5", "statement", "checked_by", "T-5", "test"],
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ rig.push(&format!("obs-{n}"), said).await?;
+ }
+ let bound: Vec<_> = rig
+ .bindings()
+ .await?
+ .into_iter()
+ .map(|b| (b.phrase, b.subject_type_id))
+ .collect();
+ assert_eq!(
+ bound,
+ vec![("validated_by".to_string(), Some(rig.statement))]
+ );
+ rig.cleanup().await
+}
+
+#[tokio::test]
+async fn a_person_decision_is_not_overwritten_by_the_ontology() -> anyhow::Result<()> {
+ let Some(rig) = Rig::new().await? else {
+ return Ok(());
+ };
+ phrase_bindings::decide(
+ &rig.pool,
+ rig.kb,
+ &rig.signature("validated_by"),
+ Decision {
+ relation_type_id: None,
+ direction: None,
+ status: "none",
+ votes: &json!({}),
+ decided_by: "person",
+ basis: None,
+ marks: None,
+ marks_asked: false,
+ },
+ )
+ .await?;
+ rig.push("obs-1", ["S-1", "statement", "validated_by", "T-1", "test"])
+ .await?;
+ let found: Vec<_> = rig
+ .bindings()
+ .await?
+ .into_iter()
+ .map(|b| (b.status, b.decided_by))
+ .collect();
+ assert_eq!(found, vec![("none".to_string(), "person".to_string())]);
+ rig.cleanup().await
+}
+
+#[tokio::test]
+async fn pushed_documents_queue_one_materialization() -> anyhow::Result<()> {
+ let Some(rig) = Rig::new().await? else {
+ return Ok(());
+ };
+ rig.push("obs-1", ["S-1", "statement", "validated_by", "T-1", "test"])
+ .await?;
+ rig.push("obs-2", ["S-2", "statement", "validated_by", "T-2", "test"])
+ .await?;
+ assert_eq!(rig.queued(phrase_bindings::MATERIALIZE_KIND).await?, 1);
+ rig.cleanup().await
+}
+
+/// 配了对话模型的库照样跑对齐:本体判的签名不送模型,也不让这一轮以为它过期了再排一次。
+/// 端点是个不通的地址——真问了,这一轮会记失败、再排
+#[tokio::test]
+async fn the_aligner_leaves_a_binding_the_ontology_decided_alone() -> anyhow::Result<()> {
+ let Some(rig) = Rig::new().await? else {
+ return Ok(());
+ };
+ rig.push("obs-1", ["S-1", "statement", "validated_by", "T-1", "test"])
+ .await?;
+ rig.unreachable_model().await?;
+ rig.clear_jobs().await?;
+ align_phrases_reasking(&rig.state, rig.kb, 0).await?;
+ let found: Vec<_> = rig
+ .bindings()
+ .await?
+ .into_iter()
+ .map(|b| (b.status, b.decided_by))
+ .collect();
+ assert_eq!(found, vec![("bound".to_string(), "ontology".to_string())]);
+ assert_eq!(rig.queued("align_phrases").await?, 0);
+ rig.cleanup().await
+}
+
+/// 关系改了名,本体判的行就像代理的一样重判:签名送去问模型。端点不通——这一轮记失败、再排;
+/// 本体还认的行不会走到这一步(上一条)
+#[tokio::test]
+async fn a_renamed_relation_sends_the_ontology_binding_back_to_the_aligner() -> anyhow::Result<()> {
+ let Some(rig) = Rig::new().await? else {
+ return Ok(());
+ };
+ rig.push("obs-1", ["S-1", "statement", "validated_by", "T-1", "test"])
+ .await?;
+ sqlx::query("UPDATE relation_types SET key='verified_by', label='verifiedBy' WHERE id=$1")
+ .bind(rig.validated_by)
+ .execute(&rig.pool)
+ .await?;
+ rig.unreachable_model().await?;
+ rig.clear_jobs().await?;
+ align_phrases_reasking(&rig.state, rig.kb, 0).await?;
+ assert_eq!(rig.queued("align_phrases").await?, 1);
+ rig.cleanup().await
+}
+
+/// 状态关系本体不判:绑上它还得说只带一个日期的陈述那个日期标哪一端,那是对齐器的题——
+/// 它绑上、顺带问这一格,问不到的进队列等人。同一个库里那条不是状态的照样绑上
+#[tokio::test]
+async fn a_pushed_phrase_equal_to_a_declared_state_relation_is_left_to_the_aligner(
+) -> anyhow::Result<()> {
+ let Some(rig) = Rig::new().await? else {
+ return Ok(());
+ };
+ let assigned_to = Uuid::now_v7();
+ sqlx::raw_sql(&format!(
+ "INSERT INTO relation_types(id,kb_id,key,label,kind,temporal,description) VALUES
+ ('{assigned_to}','{kb}','assigned_to','assignedTo','relation','state','');
+ INSERT INTO relation_type_domains(relation_type_id,entity_type_id) VALUES ('{assigned_to}','{s}');
+ INSERT INTO relation_type_ranges(relation_type_id,entity_type_id) VALUES ('{assigned_to}','{t}');",
+ kb = rig.kb,
+ s = rig.statement,
+ t = rig.test,
+ ))
+ .execute(&rig.pool)
+ .await?;
+ rig.push("obs-1", ["S-1", "statement", "assigned_to", "T-1", "test"])
+ .await?;
+ rig.push("obs-2", ["S-2", "statement", "validated_by", "T-2", "test"])
+ .await?;
+ let bound: Vec<_> = rig
+ .bindings()
+ .await?
+ .into_iter()
+ .map(|b| (b.phrase, b.decided_by))
+ .collect();
+ assert_eq!(
+ bound,
+ vec![("validated_by".to_string(), "ontology".to_string())]
+ );
+ rig.cleanup().await
+}
+
+/// 本体判的绑定,关系不再声明它(这里是域收窄到别的类)就和代理的判定一样重判:这条签名
+/// 没了候选,对齐器不问模型就记成 none,物化收回那一行。端点不通——真问了,这一轮会记失败、再排
+#[tokio::test]
+async fn an_ontology_binding_is_redecided_once_the_relation_stops_declaring_it(
+) -> anyhow::Result<()> {
+ let Some(rig) = Rig::new().await? else {
+ return Ok(());
+ };
+ rig.push("obs-1", ["S-1", "statement", "validated_by", "T-1", "test"])
+ .await?;
+ materialize::materialize(&rig.pool, rig.kb).await?;
+ assert_eq!(materialize::count(&rig.pool, rig.kb).await?, 1);
+ sqlx::query("UPDATE relation_type_domains SET entity_type_id=$1 WHERE relation_type_id=$2")
+ .bind(rig.other)
+ .bind(rig.validated_by)
+ .execute(&rig.pool)
+ .await?;
+ rig.unreachable_model().await?;
+ rig.clear_jobs().await?;
+ align_phrases_reasking(&rig.state, rig.kb, 0).await?;
+ let found: Vec<(String, String, Option<String>)> = sqlx::query_as(
+ "SELECT status, decided_by, votes->>'reason' FROM phrase_bindings WHERE kb_id=$1",
+ )
+ .bind(rig.kb)
+ .fetch_all(&rig.pool)
+ .await?;
+ assert_eq!(
+ found,
+ vec![(
+ "none".to_string(),
+ "agent".to_string(),
+ Some("no_candidates".to_string())
+ )]
+ );
+ assert_eq!(rig.queued("align_phrases").await?, 0);
+ materialize::materialize(&rig.pool, rig.kb).await?;
+ assert_eq!(materialize::count(&rig.pool, rig.kb).await?, 0);
+ rig.cleanup().await
+}
diff --git a/crates/utopia-store/src/phrase_bindings.rs b/crates/utopia-store/src/phrase_bindings.rs
index cf0c3683..a54a933c 100644
--- a/crates/utopia-store/src/phrase_bindings.rs
+++ b/crates/utopia-store/src/phrase_bindings.rs
@@ -110,6 +110,31 @@ pub async fn signatures(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<PhraseSigna
Ok(sqlx::query_as(&sql).bind(kb_id).fetch_all(pool).await?)
}
+/// 一篇文档里活着的开放陈述落在哪些签名上(键同 [`PhraseSignature::key`])。推送来的
+/// 文档抽完,本体只判这些签名(#1242);别的签名还是对齐器的
+pub async fn signature_keys_of_document(
+ pool: &PgPool,
+ kb_id: Uuid,
+ document_id: Uuid,
+) -> AppResult<Vec<(String, Option<Uuid>, Option<Uuid>, bool)>> {
+ let sql = format!(
+ "SELECT DISTINCT {phrase}, s.type_id, o.type_id, (f.object_id IS NULL)
+ FROM facts f
+ JOIN entities s ON s.id = f.subject_id
+ LEFT JOIN entities o ON o.id = f.object_id
+ WHERE f.kb_id = $1 AND f.layer = 'open' AND f.invalidated_at IS NULL
+ AND f.phrase IS NOT NULL AND btrim(f.phrase) <> ''
+ AND EXISTS (SELECT 1 FROM fact_evidence fe JOIN chunks c ON c.id = fe.chunk_id
+ WHERE fe.fact_id = f.id AND c.document_id = $2)",
+ phrase = phrase_sql("f.phrase")
+ );
+ Ok(sqlx::query_as(&sql)
+ .bind(kb_id)
+ .bind(document_id)
+ .fetch_all(pool)
+ .await?)
+}
+
/// 按 id 取一条绑定的签名(人在队列里定它时用):短语、两端的类、宾语是不是字面值,
/// 例句照判定时记下的,陈述数同。
pub async fn signature_of(
@@ -147,7 +172,7 @@ pub struct Binding {
/// bound / none / undecided
pub status: String,
pub decided_at: DateTime<Utc>,
- /// agent / person
+ /// agent / person / ontology(短语正好是一条声明了的关系,#1242)
pub decided_by: String,
/// 判定时输入的指纹;NULL = 这一列出现之前的判定
pub basis: Option<String>,
@@ -275,7 +300,7 @@ pub struct Decision<'a> {
/// bound / none / undecided
pub status: &'a str,
pub votes: &'a serde_json::Value,
- /// agent / person
+ /// agent / person / ontology
pub decided_by: &'a str,
/// 判定时输入的指纹([`basis_of`]):代理的判定必带,人的判定不带——人不按指纹重判
pub basis: Option<&'a str>,
@@ -289,8 +314,8 @@ pub struct Decision<'a> {
/// 记下一条签名的判定(有则改)。返回是否写入了。
///
-/// **人的判定不被代理覆盖**:已有行是人判的而这次是代理,原样留着、返回 false。
-/// 反过来人可以改代理的。
+/// **人的判定不被代理覆盖**:已有行是人判的而这次是代理或本体,原样留着、返回 false。
+/// 反过来人可以改代理的、本体的。
pub async fn decide(
pool: &PgPool,
kb_id: Uuid,
@@ -334,7 +359,7 @@ fn validate_decision(sig: &PhraseSignature, d: &Decision<'_>) -> AppResult<Strin
return Err(AppError::Validation(format!("unknown marks {marks:?}")));
}
}
- if !matches!(d.decided_by, "agent" | "person") {
+ if !matches!(d.decided_by, "agent" | "person" | "ontology") {
return Err(AppError::Validation(format!(
"unknown decider {:?}",
d.decided_by
@@ -421,7 +446,7 @@ pub async fn decide_on(
basis = EXCLUDED.basis,
marks = EXCLUDED.marks,
marks_asked_at = EXCLUDED.marks_asked_at
- WHERE NOT (phrase_bindings.decided_by = 'person' AND EXCLUDED.decided_by = 'agent')",
+ WHERE NOT (phrase_bindings.decided_by = 'person' AND EXCLUDED.decided_by <> 'person')",
)
.bind(Uuid::now_v7())
.bind(kb_id)
diff --git a/docs/decisions/0044-the-ontology-is-a-view-over-what-documents-say.md b/docs/decisions/0044-the-ontology-is-a-view-over-what-documents-say.md
index cae18cc2..d8895511 100644
--- a/docs/decisions/0044-the-ontology-is-a-view-over-what-documents-say.md
+++ b/docs/decisions/0044-the-ontology-is-a-view-over-what-documents-say.md
@@ -68,6 +68,12 @@ This is how the facts a reader draws without the text stating them (a place's co
When the ontology changes, only facts under changed signatures and rules are recomputed. A signature with no property stays in the open graph, loses nothing, and counts toward the workbench's suggestions.
+**Revision 2026-10-15 (the ontology decides a phrase it declares, [#1242](https://github.com/deeplethe/utopia/issues/1242)):** a signature from a document a `statements` source pushed ([0054](0054-a-source-may-push-statements-in-the-open-contract.md)) is bound without the model when its phrase, normalised as kind words are, equals the key or label of exactly one declared relation that is not a state, and the relation's declared domain admits the subject's class and its declared range the object's class, through the class hierarchy and forward only. The binding is recorded `decided_by = 'ontology'` (migration 0113), with `votes = {"reason": "declared_relation"}` and no basis. It is decided when the document's extraction finishes, and that extraction then queues `materialize` unless one is queued, so a base with no chat model gets typed facts from what it is pushed; on a base of 1,220 pushed entities every class was bound up front and every relation stayed open, because the aligner is the only writer of phrase bindings and needs a model.
+
+Why it keeps this decision: it binds a signature, never a fact, and it leaves a row the alignment endpoints show and overturn. A person's decision is never replaced (the rule of `decide_on`, which now holds against the ontology too). The aligner leaves an ontology decision alone while the relation still declares it, and re-decides it like any agent decision once it does not (a renamed relation, a narrowed domain). Why it keeps [0012](0012-the-ontology-is-a-contract-not-a-suggestion.md): it fires only on equality with a relation a person declared by importing or editing the ontology, and only when the declared ends agree, so it reads the contract rather than guessing at it.
+
+Not done: no typed write and no predicate slot in the push contract (0054 decision 5 stands; a pushed statement is still an open statement that becomes typed through its binding). A phrase that only resembles a relation (`validated by tests`), a relation with no declared domain or range, an end with no class, a literal object, the reverse direction, two relations that both fit, a state relation, and every signature no pushed document reaches still go to the aligner: in prose, a phrase that happens to spell a label is not a statement written in the ontology's terms. A binding is per signature, so a prose statement that shares a signature with a pushed one is bound with it. A state relation is left to the aligner because binding one also says what a single date marks (`marks`, #966), which the declaration does not answer; the aligner binds it and asks, and a person sets what it could not. An ontology decision whose relation stops matching is re-decided like an agent's: when no declared relation fits its ends any more it is unbound without the model, and when one still might (a renamed relation) it goes to the model, so in a base with no model it stays bound until a person decides it.
+
**Revision 2026-09-23 (implication rules built):** a rule is keyed like a binding (a phrase signature) or by a kind word, concludes one property, and takes its object either from the statement's own object or from a *reading* of the object's words (`country_of_nationality`, `country_of_place`, `year_of_phrase`). The aligner proposes rules after it has decided the signatures of a run and for every kind word once; a person approves or rejects on the alignment queue; approval commits with its job (0051). Readings are model calls made once per distinct phrase by a `read_phrases` job and cached in `phrase_readings`, so `materialize` stays free of model calls: it reads the cache and produces facts marked `implied`, with the triggering statement's evidence, retired by source like any other typed row. What is not read cannot be implied: a phrase the model cannot place caches as "no answer" and is never asked again until it is asked about differently.
**Revision 2026-09-23:** [0053](0053-a-phrase-decision-records-the-inputs-it-considered.md) replaces "a binding goes stale by timestamp" with a recorded basis: candidates are admitted through the class hierarchy, a decision stores a fingerprint of the closures and candidates it saw, and it is stale when the current fingerprint differs. No-candidate and overflow become recorded outcomes; the requeue condition reads live signatures only (#807, #795).
diff --git a/docs/decisions/0054-a-source-may-push-statements-in-the-open-contract.md b/docs/decisions/0054-a-source-may-push-statements-in-the-open-contract.md
index 9d66596d..3965eb34 100644
--- a/docs/decisions/0054-a-source-may-push-statements-in-the-open-contract.md
+++ b/docs/decisions/0054-a-source-may-push-statements-in-the-open-contract.md
@@ -92,3 +92,4 @@ Content-Type: application/json
## Revisions
- 2026-09-25 (#899, #900): typed materialization now reconciles the rows it writes along their uniqueness timelines, as the write path always did, so a later observation of a functional attribute closes the earlier one without a manual reconcile. A document version records the `doc_time` it was pushed with, and a fact's evidence date is taken from its own version, so a same-identity update no longer makes the earlier statement look simultaneous with the later one. The stored document carries the observation's identity and date ahead of the three arrays, so the same payload under a new identity is a second document, never a rename of the first.
+- 2026-10-15 ([#1242](https://github.com/deeplethe/utopia/issues/1242)): a pushed signature whose phrase equals exactly one declared relation, not a state, that admits both of its ends is bound by the ontology when the document's extraction finishes, and that extraction queues `materialize`, so a base with no chat model types what it is pushed. It binds the signature as [0044](0044-the-ontology-is-a-view-over-what-documents-say.md)'s revision of decision 3 describes, reviewable like any binding; it is not a typed write, decisions 3 and 5 stand, and no other pushed phrase binds before alignment reads it.
diff --git a/docs/design/ontology.md b/docs/design/ontology.md
index 183235e3..65fdaed6 100644
--- a/docs/design/ontology.md
+++ b/docs/design/ontology.md
@@ -96,6 +96,14 @@ if that basis still matches the rows when it is written; otherwise it is discard
word asked again [0053 revision, #795]. Cosmetic edits to a candidate class still count as a
change.
+**A pushed phrase that names a declared relation binds without the model** [0044 revision, #1242].
+A signature from a document a `statements` source pushed (0054) whose phrase equals the key or label
+of exactly one declared relation that is not a state, with the subject's class in its declared
+domain and the object's in its declared range, is bound when the document's extraction finishes,
+`decided_by = 'ontology'`; the extraction then queues `materialize`. A person's decision stands over
+it, and the aligner re-decides it only once the relation stops declaring it. Anything short of that
+equality, and every state relation, goes to the aligner.
+
**A shape of statement can imply a fact of another property** [0044 decision 3, migration 0073].
An implication rule is keyed like a binding (a signature) or by a kind word, names the property it
concludes, and takes its object from the statement's own object or from a *reading* of the object's
diff --git a/migrations/0113_the_ontology_decides_a_phrase_it_declares.sql b/migrations/0113_the_ontology_decides_a_phrase_it_declares.sql
new file mode 100644
index 00000000..3fa78c09
--- /dev/null
+++ b/migrations/0113_the_ontology_decides_a_phrase_it_declares.sql
@@ -0,0 +1,13 @@
+-- 推送来的短语正好是一条声明了的关系时,签名由本体判(#1242,0044 决定 3 的修订)。
+--
+-- 一个 `statements` 来源(0054)推来 `[Statement] validated_by [Test]`,而导入的本体里
+-- validated_by 就是一条声明了域 Statement、值域 Test 的关系:短语归一后等于它的键或标签、
+-- 两端的类落在域与值域里、且只有这一条对得上,这条签名不问模型直接绑上。判定照旧是
+-- 签名上的一行,人看得见、改得了;记成谁判的得说实话——不是代理(没有模型投过票),
+-- 也不是人(没有人点过头),是本体:
+-- ontology 按声明判的。人的判定它不覆盖;它不再对得上(关系改了名、改了域)时
+-- 对齐器照常重判
+ALTER TABLE phrase_bindings
+ DROP CONSTRAINT phrase_bindings_decided_by_check,
+ ADD CONSTRAINT phrase_bindings_decided_by_check
+ CHECK (decided_by IN ('agent', 'person', 'ontology'));