World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
A merged entity comes back before the merge (#337)
WaylandYangf3d05f36b9fc
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rsindex 28cdde16..bb628c76 100644--- a/crates/utopia-store/src/graph.rs+++ b/crates/utopia-store/src/graph.rs@@ -350,11 +350,16 @@ pub async fn add_evidence(/// `as_of`:绑记录轴参数的位置(`None` = 只答现在,写路径和"当下"视图用这个)。/// 度数跟着画布走——回放时数的是**当时**连在这个节点上的边,否则右上角的数/// 和眼前的图对不上。-fn node_sql(as_of: Option<usize>) -> String {+/// `owner`:**只在真的传了时刻时**才绑(#336)。`fact_owner_at` 包住列之后+/// `facts` 上按主宾的索引就用不上了,而「现在」是每次画图都要走的那条路+fn node_sql(as_of: Option<usize>, owner: Option<usize>) -> String {let held = match as_of {Some(param) => crate::record_axis::facts_held_at("f", param),None => "f.invalidated_at IS NULL".to_string(),};+ // 主宾也跟着倒:三月被合并掉的实体,在二月身上还挂着它自己的那些事实(#336)+ let subject = crate::record_axis::owner_at("f", "subject_id", owner, false);+ let object = crate::record_axis::owner_at("f", "object_id", owner, true);format!("SELECT e.id, e.canonical_name AS name, t.key AS type_key,t.label AS type_label,@@ -362,7 +367,7 @@ fn node_sql(as_of: Option<usize>) -> String {coalesce(t.shape, 'circle') AS shape,e.disambiguator,(SELECT count(*) FROM facts f- WHERE (f.subject_id = e.id OR f.object_id = e.id) AND {held}) AS degree+ WHERE ({subject} = e.id OR {object} = e.id) AND {held}) AS degreeFROM entities e LEFT JOIN entity_types t ON t.id = e.type_id")}@@ -387,8 +392,9 @@ pub async fn overview(as_of: Option<chrono::DateTime<chrono::Utc>>,) -> AppResult<(Vec<GraphNode>, Vec<GraphEdge>, i64, i64)> {let nodes: Vec<GraphNode> = sqlx::query_as(&format!(- "{} WHERE e.kb_id = $1 AND e.merged_into IS NULL ORDER BY degree DESC, e.created_at LIMIT $2",- node_sql(Some(3))+ "{} WHERE e.kb_id = $1 AND {visible} ORDER BY degree DESC, e.created_at LIMIT $2",+ node_sql(Some(3), as_of.map(|_| 3)),+ visible = crate::record_axis::entity_visible_at("e", 3),)).bind(kb_id).bind(limit)@@ -404,12 +410,14 @@ pub async fn overview(// 「150 / 325」里那个 325 会跟用户在别处看到的数对不上——**回放时也一样**,// 边数跟着记录轴走,否则倒回三月的图上写着今天的边数。//- // 节点数没跟着倒:实体身上没有记录轴(`merged_into` 只说合并发生过,- // 时刻在 `entity_merges` 里),要倒得顺着那张表拆合并,是另一刀(0019 遗留问题)- let total_nodes: i64 = sqlx::query_scalar(- "SELECT count(*) FROM entities WHERE kb_id = $1 AND merged_into IS NULL",- )+ // 节点数也跟着倒(#336):实体的时刻在 `entity_merges` 上,不在实体行上——+ // 三月并掉的那个,在二月既该出现在画布上,也该数进这个总数里+ let total_nodes: i64 = sqlx::query_scalar(&format!(+ "SELECT count(*) FROM entities e WHERE e.kb_id = $1 AND {visible}",+ visible = crate::record_axis::entity_visible_at("e", 2),+ )).bind(kb_id)+ .bind(as_of).fetch_one(pool).await?;let total_edges: i64 = sqlx::query_scalar(&format!(@@ -451,7 +459,7 @@ async fn edges_among(// 断言那一段多算一位 `contested`:有 open 的违规或时态冲突指着它。派生撞断言// 时被撞的是 left;right 只是最后一条前提,它本身没有争议let edges: Vec<GraphEdge> = sqlx::query_as(&format!(- "SELECT f.id, f.subject_id AS source, f.object_id AS target,+ "SELECT f.id, {subject} AS source, {object} AS target,COALESCE(r.key, fact_surface_predicate(f.id)) AS predicate,COALESCE(r.label, fact_surface_predicate(f.id)) AS label,r.id IS NULL AS inferred, FALSE AS derived, NULL::text AS rule,@@ -468,7 +476,7 @@ async fn edges_among(FALSE AS blockedFROM facts f LEFT JOIN relation_types r ON r.id = f.predicate_idWHERE f.kb_id = $1 AND {facts_held} AND f.object_id IS NOT NULL- AND f.subject_id = ANY($2) AND f.object_id = ANY($2)+ AND {subject} = ANY($2) AND {object} = ANY($2)AND ($3::timestamptz IS NULLOR ((f.valid_from IS NULL OR f.valid_from <= $3)AND (f.valid_to IS NULL OR f.valid_to > $3)))@@ -511,6 +519,9 @@ async fn edges_among(derived_held = crate::record_axis::derived_held_at("d", 4),violation_open = crate::record_axis::violation_open_at("v", 4),conflict_open = crate::record_axis::conflict_open_at("c", 4),+ // 派生边不跟着倒:它们由引擎按当时的断言推出,主宾从来没被合并改写过+ subject = crate::record_axis::owner_at("f", "subject_id", as_of.map(|_| 4), false),+ object = crate::record_axis::owner_at("f", "object_id", as_of.map(|_| 4), true),)).bind(kb_id).bind(ids)@@ -541,10 +552,12 @@ pub async fn neighborhood(// 铺开也走记录轴:邻居按**当时**的边找,否则回放的图上会长出// 只有今天才连得上的节点let touching: Vec<(Uuid, Option<Uuid>)> = sqlx::query_as(&format!(- "SELECT f.subject_id, f.object_id FROM facts f+ "SELECT {subject}, {object} FROM facts fWHERE f.kb_id = $1 AND {facts_held} AND f.object_id IS NOT NULL- AND (f.subject_id = ANY($2) OR f.object_id = ANY($2))",+ AND ({subject} = ANY($2) OR {object} = ANY($2))",facts_held = crate::record_axis::facts_held_at("f", 3),+ subject = crate::record_axis::owner_at("f", "subject_id", as_of.map(|_| 3), false),+ object = crate::record_axis::owner_at("f", "object_id", as_of.map(|_| 3), true),)).bind(kb_id).bind(&frontier)@@ -568,8 +581,9 @@ pub async fn neighborhood(let ids: Vec<Uuid> = seen.into_iter().collect();let nodes: Vec<GraphNode> = sqlx::query_as(&format!(- "{} WHERE e.kb_id = $1 AND e.id = ANY($2)",- node_sql(Some(3))+ "{} WHERE e.kb_id = $1 AND e.id = ANY($2) AND {visible}",+ node_sql(Some(3), as_of.map(|_| 3)),+ visible = crate::record_axis::entity_visible_at("e", 3),)).bind(kb_id).bind(&ids)@@ -594,7 +608,7 @@ pub async fn search_entities("{} WHERE e.kb_id = $1 AND e.merged_into IS NULLAND e.canonical_name ILIKE $2ORDER BY degree DESC, e.canonical_name LIMIT $3 OFFSET $4",- node_sql(None)+ node_sql(None, None))).bind(kb_id).bind(&pattern)@@ -622,7 +636,7 @@ pub async fn entity_detail() -> AppResult<(GraphNode, Vec<EntityFact>)> {let node: GraphNode = sqlx::query_as(&format!("{} WHERE e.kb_id = $1 AND e.id = $2",- node_sql(Some(3))+ node_sql(Some(3), as_of.map(|_| 3)))).bind(kb_id).bind(entity_id)@@ -633,11 +647,11 @@ pub async fn entity_detail(let facts: Vec<EntityFact> = sqlx::query_as(&format!("SELECT f.id,- CASE WHEN f.subject_id = $2 THEN 'out' ELSE 'in' END AS direction,+ CASE WHEN {subject} = $2 THEN 'out' ELSE 'in' END AS direction,COALESCE(r.key, fact_surface_predicate(f.id)) AS predicate_key,COALESCE(r.label, fact_surface_predicate(f.id)) AS predicate_label,r.id IS NULL AS inferred, r.temporal,- CASE WHEN f.subject_id = $2 THEN f.object_id ELSE f.subject_id END AS other_id,+ CASE WHEN {subject} = $2 THEN {object} ELSE {subject} END AS other_id,o.canonical_name AS other_name, f.object_value,f.valid_from, f.valid_from_precision, f.valid_to, f.valid_to_precision, f.confidence,(SELECT count(*) FROM fact_evidence fe WHERE fe.fact_id = f.id) AS evidence_count,@@ -671,11 +685,13 @@ pub async fn entity_detail(FROM facts fLEFT JOIN relation_types r ON r.id = f.predicate_idLEFT JOIN entities o- ON o.id = CASE WHEN f.subject_id = $2 THEN f.object_id ELSE f.subject_id END+ ON o.id = CASE WHEN {subject} = $2 THEN {object} ELSE {subject} ENDWHERE f.kb_id = $1 AND {facts_held}- AND (f.subject_id = $2 OR f.object_id = $2)+ AND ({subject} = $2 OR {object} = $2)ORDER BY f.valid_from NULLS LAST, f.recorded_at",facts_held = crate::record_axis::facts_held_at("f", 3),+ subject = crate::record_axis::owner_at("f", "subject_id", as_of.map(|_| 3), false),+ object = crate::record_axis::owner_at("f", "object_id", as_of.map(|_| 3), true),chunk_live = crate::record_axis::chunk_live_at("c", 3),violation_open = crate::record_axis::violation_open_at("v", 3),conflict_open = crate::record_axis::conflict_open_at("c", 3),@@ -704,7 +720,7 @@ pub async fn update_entity() -> AppResult<(GraphNode, GraphNode)> {let before: GraphNode = sqlx::query_as(&format!("{} WHERE e.kb_id = $1 AND e.id = $2 AND e.merged_into IS NULL",- node_sql(None)+ node_sql(None, None))).bind(kb_id).bind(entity_id)@@ -781,7 +797,7 @@ pub async fn update_entity(let after: GraphNode = sqlx::query_as(&format!("{} WHERE e.kb_id = $1 AND e.id = $2",- node_sql(None)+ node_sql(None, None))).bind(kb_id).bind(entity_id)@@ -801,7 +817,7 @@ pub async fn same_name_peers("{} WHERE e.kb_id = $1 AND e.merged_into IS NULL AND e.id <> $2AND lower(e.canonical_name) = (SELECT lower(canonical_name) FROM entities WHERE id = $2)ORDER BY degree DESC LIMIT 10",- node_sql(None)+ node_sql(None, None))).bind(kb_id).bind(entity_id)diff --git a/crates/utopia-store/src/record_axis.rs b/crates/utopia-store/src/record_axis.rsindex fa2981c8..6c72ed00 100644--- a/crates/utopia-store/src/record_axis.rs+++ b/crates/utopia-store/src/record_axis.rs@@ -62,3 +62,41 @@ pub fn chunk_live_at(alias: &str, param: usize) -> String {AND ({alias}.superseded_at IS NULL OR {alias}.superseded_at > coalesce(${param}, now()))")}++/// `entity_merges`:这次合并在 T 时刻**生效着**吗(0019 第二刀 / #336)。+///+/// 实体身上没有记录轴——`merged_into` 只说合并发生过,不说何时。时刻在这张表上,+/// 而它和别的表问的是同一个问题,所以列名不同、形状一样。+pub fn merge_in_effect_at(alias: &str, param: usize) -> String {+ format!(+ "{alias}.created_at <= coalesce(${param}, now()) \+ AND ({alias}.reverted_at IS NULL OR {alias}.reverted_at > coalesce(${param}, now()))"+ )+}++/// 实体在 T 时刻是不是一个独立的节点:那时已经存在,且没有被一次生效中的合并吞掉。+///+/// **取代读路径上的 `merged_into IS NULL`。** 参数为 NULL 时两者等价(已撤销的合并+/// 此刻不生效,那个实体本来就该出现),但传了时刻之后,三月被并掉的实体在二月+/// 会重新长回来——那正是这一刀要的。+pub fn entity_visible_at(alias: &str, param: usize) -> String {+ let merged = merge_in_effect_at("m", param);+ format!(+ "{alias}.created_at <= coalesce(${param}, now()) \+ AND NOT EXISTS (SELECT 1 FROM entity_merges m \+ WHERE m.source_id = {alias}.id AND {merged})"+ )+}++/// 一条事实在 T 时刻的主语(`on_object = false`)或宾语。+///+/// **现在这条路不进函数**:`fact_owner_at` 包住列之后索引就用不上了,而+/// 「现在」是每一次画图都要走的路。回放才付这个代价——它本来就少见。+pub fn owner_at(fact_alias: &str, column: &str, as_of: Option<usize>, on_object: bool) -> String {+ match as_of {+ None => format!("{fact_alias}.{column}"),+ Some(param) => {+ format!("fact_owner_at({fact_alias}.id, {fact_alias}.{column}, ${param}, {on_object})")+ }+ }+}diff --git a/crates/utopia-store/tests/a_merge_rewinds_with_the_second_clock.rs b/crates/utopia-store/tests/a_merge_rewinds_with_the_second_clock.rsnew file mode 100644index 00000000..edd8da5d--- /dev/null+++ b/crates/utopia-store/tests/a_merge_rewinds_with_the_second_clock.rs@@ -0,0 +1,256 @@+//! 合并也倒得回去(0019 第二刀 / #336),打在真库上。+//!+//! 合并是**原地改写**:`UPDATE facts SET subject_id = target`。行上只剩合并之后的+//! 样子,所以「三月那天这条事实挂在谁身上」既不在事实行里、也不在实体行里——+//! 只在 `entity_merges` 的数组里。这个测试打的就是那条映射。+//!+//! 三个时刻,因为它们各自会以不同的方式坏掉:+//! - **合并之前**:被并掉的实体要重新长出来,且带着它自己的那些事实+//! - **一次已撤销的合并的窗口之内**:那段时间它们**确实**是一个——撤销把行搬回去了,+//! 当前行里看不见这件事,只能从数组里读出来+//! - **现在**:一切照旧,且不能因为加了映射就变慢或变样++use sqlx::PgPool;+use uuid::Uuid;++fn t(s: &str) -> chrono::DateTime<chrono::Utc> {+ s.parse().unwrap()+}++struct Fixture {+ org: Uuid,+ kb: Uuid,+ /// 留下的那个+ zhang_a: Uuid,+ /// 四月被并进 A,至今仍并着+ zhang_b: Uuid,+ /// 五月被并进 A,六月又撤销了+ zhang_c: Uuid,+ fact_a: Uuid,+ fact_b: Uuid,+ fact_c: Uuid,+}++async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ let (person, company) = (Uuid::now_v7(), Uuid::now_v7());+ let works_for = Uuid::now_v7();+ let (acme, zenith) = (Uuid::now_v7(), Uuid::now_v7());+ let (zhang_a, zhang_b, zhang_c) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());+ let (fact_a, fact_b, fact_c) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());++ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'merge-rewind-test')")+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'merge-rewind-test')")+ .bind(ws)+ .bind(org)+ .execute(pool)+ .await?;+ sqlx::query(+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'merge-rewind-test')",+ )+ .bind(kb)+ .bind(ws)+ .execute(pool)+ .await?;+ for (id, key, label) in [+ (person, "person", "Person"),+ (company, "company", "Company"),+ ] {+ 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?;+ }+ sqlx::query(+ "INSERT INTO relation_types (id, kb_id, key, label) VALUES ($1, $2, 'works_for', 'works for')",+ )+ .bind(works_for)+ .bind(kb)+ .execute(pool)+ .await?;+ // 实体的出生时刻也倒着看:一月的图上它们还不存在+ for (id, type_id, name) in [+ (acme, company, "Acme"),+ (zenith, company, "Zenith"),+ (zhang_a, person, "Zhang Wei"),+ (zhang_b, person, "Zhang Wei"),+ (zhang_c, person, "Zhang Wei"),+ ] {+ sqlx::query(+ "INSERT INTO entities (id, kb_id, type_id, canonical_name, created_at)+ VALUES ($1, $2, $3, $4, $5)",+ )+ .bind(id)+ .bind(kb)+ .bind(type_id)+ .bind(name)+ .bind(t("2026-02-01T00:00:00Z"))+ .execute(pool)+ .await?;+ }+ for (id, subject, object, rec) in [+ (fact_a, zhang_a, acme, "2026-03-01T00:00:00Z"),+ (fact_b, zhang_b, zenith, "2026-03-02T00:00:00Z"),+ (fact_c, zhang_c, acme, "2026-03-03T00:00:00Z"),+ ] {+ sqlx::query(+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, confidence,+ recorded_at)+ VALUES ($1, $2, $3, $4, $5, 0.9, $6)",+ )+ .bind(id)+ .bind(kb)+ .bind(subject)+ .bind(works_for)+ .bind(object)+ .bind(t(rec))+ .execute(pool)+ .await?;+ }++ // 四月:B 并进 A,至今仍并着+ utopia_store::resolution::merge_entities(pool, kb, zhang_b, zhang_a, None, "test").await?;+ backdate(pool, zhang_b, "2026-04-01T00:00:00Z", None).await?;++ // 五月:C 并进 A;六月撤销。**撤销把事实搬回去了**,所以现在的行上看不出+ // 五月到六月之间它们曾是一个——那段窗口只在 entity_merges 里+ let merge_c =+ utopia_store::resolution::merge_entities(pool, kb, zhang_c, zhang_a, None, "test").await?;+ backdate(pool, zhang_c, "2026-05-01T00:00:00Z", None).await?;+ utopia_store::resolution::revert_merge(pool, kb, merge_c).await?;+ backdate(+ pool,+ zhang_c,+ "2026-05-01T00:00:00Z",+ Some("2026-06-01T00:00:00Z"),+ )+ .await?;++ Ok(Fixture {+ org,+ kb,+ zhang_a,+ zhang_b,+ zhang_c,+ fact_a,+ fact_b,+ fact_c,+ })+}++/// 合并的时刻由 `now()` 落库,测试要的是确定的日期。+async fn backdate(+ pool: &PgPool,+ source: Uuid,+ created: &str,+ reverted: Option<&str>,+) -> anyhow::Result<()> {+ sqlx::query("UPDATE entity_merges SET created_at = $2, reverted_at = $3 WHERE source_id = $1")+ .bind(source)+ .bind(t(created))+ .bind(reverted.map(t))+ .execute(pool)+ .await?;+ Ok(())+}++async fn facts_of(+ pool: &PgPool,+ kb: Uuid,+ entity: Uuid,+ as_of: Option<&str>,+) -> anyhow::Result<Vec<Uuid>> {+ let (_, facts) = utopia_store::graph::entity_detail(pool, kb, entity, as_of.map(t)).await?;+ let mut ids: Vec<Uuid> = facts.iter().map(|f| f.id).collect();+ ids.sort();+ Ok(ids)+}++fn sorted(mut v: Vec<Uuid>) -> Vec<Uuid> {+ v.sort();+ v+}++#[tokio::test]+async fn a_merged_entity_comes_back_before_the_merge() -> 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 nodes = |as_of: Option<&'static str>| {+ let pool = pool.clone();+ async move {+ let (nodes, _, total, _) =+ utopia_store::graph::overview(&pool, f.kb, 50, None, as_of.map(t)).await?;+ let mut ids: Vec<Uuid> = nodes.iter().map(|n| n.id).collect();+ ids.sort();+ Ok::<(Vec<Uuid>, i64), anyhow::Error>((ids, total))+ }+ };++ // 1. 现在:B 并着(不出现),C 已撤销(照常出现)+ let (ids, total) = nodes(None).await?;+ assert!(!ids.contains(&f.zhang_b), "仍并着的实体不该出现在画布上");+ assert!(ids.contains(&f.zhang_c), "撤销过的合并不该继续吞掉那个实体");+ assert_eq!(total, 4, "节点总数与画布同一口径");+ assert_eq!(+ facts_of(&pool, f.kb, f.zhang_a, None).await?,+ sorted(vec![f.fact_a, f.fact_b])+ );+ assert_eq!(+ facts_of(&pool, f.kb, f.zhang_c, None).await?,+ vec![f.fact_c]+ );++ // 2. 三月:三个张伟各自站着,各自带着自己的那条事实。+ // 这是这一刀的全部意义——事实行上写的是 A,而三月那天它挂在 B 身上+ let (ids, total) = nodes(Some("2026-03-15T00:00:00Z")).await?;+ assert!(ids.contains(&f.zhang_b) && ids.contains(&f.zhang_c));+ assert_eq!(total, 5);+ assert_eq!(+ facts_of(&pool, f.kb, f.zhang_a, Some("2026-03-15T00:00:00Z")).await?,+ vec![f.fact_a],+ "三月的 A 只有自己那一条"+ );+ assert_eq!(+ facts_of(&pool, f.kb, f.zhang_b, Some("2026-03-15T00:00:00Z")).await?,+ vec![f.fact_b],+ "被并掉的 B 在三月还拿着自己那条事实"+ );++ // 3. 五月中:C 那次合并当时**生效着**(六月才撤销)。撤销已经把行搬回 C,+ // 所以这一格只能从 entity_merges 的数组里读出来+ let (ids, total) = nodes(Some("2026-05-15T00:00:00Z")).await?;+ assert!(!ids.contains(&f.zhang_c), "五月中 C 正并在 A 里");+ assert!(!ids.contains(&f.zhang_b));+ assert_eq!(total, 3);+ assert_eq!(+ facts_of(&pool, f.kb, f.zhang_a, Some("2026-05-15T00:00:00Z")).await?,+ sorted(vec![f.fact_a, f.fact_b, f.fact_c]),+ "五月中三条事实都在 A 身上"+ );++ // 4. 一月:实体还没被建出来,图是空的,而不是退化成现在+ let (ids, total) = nodes(Some("2026-01-01T00:00:00Z")).await?;+ assert!(ids.is_empty(), "一月这些实体还不存在");+ assert_eq!(total, 0);++ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")+ .bind(f.kb)+ .execute(&pool)+ .await?;+ let gone = sqlx::query("DELETE FROM organizations WHERE id = $1")+ .bind(f.org)+ .execute(&pool)+ .await?;+ assert_eq!(gone.rows_affected(), 1, "一次性 org 没删掉");+ Ok(())+}diff --git a/crates/utopia-store/tests/the_second_clock_can_be_rewound.rs b/crates/utopia-store/tests/the_second_clock_can_be_rewound.rsindex d85eb139..9918e162 100644--- a/crates/utopia-store/tests/the_second_clock_can_be_rewound.rs+++ b/crates/utopia-store/tests/the_second_clock_can_be_rewound.rs@@ -84,13 +84,17 @@ async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {(phoenix, project, "Project Phoenix"),(program, project, "Phoenix Program"),] {+ // **实体的出生时刻也要回填**:事实记在三月,实体却是"刚才"建的,那种账本+ // 现实里不存在——而 #336 之后 T 时刻还没出生的实体不再出现在图上sqlx::query(- "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",+ "INSERT INTO entities (id, kb_id, type_id, canonical_name, created_at)+ VALUES ($1, $2, $3, $4, $5)",).bind(id).bind(kb).bind(type_id).bind(name)+ .bind(t("2026-01-01T00:00:00Z")).execute(pool).await?;}diff --git a/migrations/0027_entities_rewind_too.sql b/migrations/0027_entities_rewind_too.sqlnew file mode 100644index 00000000..dd61c047--- /dev/null+++ b/migrations/0027_entities_rewind_too.sql@@ -0,0 +1,72 @@+-- 一条事实在某一时刻属于哪个实体(0019 第二刀 / #336)。+--+-- 合并是**原地改写**:`UPDATE facts SET subject_id = target WHERE subject_id = source`。+-- 行上因此只剩合并之后的样子,而被改写的行 id 一条不落地记在+-- `entity_merges.moved_subject_facts` / `moved_object_facts` 里——「当时属于谁」+-- 查得回来,只是查不出一个列,得走这张表。+--+-- **放成 SQL 函数而不是每个读点各拼一段 CTE**,与 `fact_surface_predicate` 同一个理由:+-- 这类映射一旦散开,漏掉一处就是一张安静地把事实挂错人的图(0019 的风险那一节)。+--+-- `at IS NULL` 直接回当前值:现在这条路一次表都不查,回放才付代价。+CREATE FUNCTION fact_owner_at(+ fact_id UUID,+ current_owner UUID,+ at TIMESTAMPTZ,+ -- false = 主语侧,true = 宾语侧+ on_object BOOLEAN+) RETURNS UUID+LANGUAGE plpgsql+STABLE+AS $$+DECLARE+ owner UUID := current_owner;+ undone UUID;+ applied UUID;+BEGIN+ IF at IS NULL OR current_owner IS NULL THEN+ RETURN current_owner;+ END IF;++ -- ① 撤销:T 之后才发生、且**现在仍生效**的合并。只有它们的移动还留在当前行上。+ -- 已撤销的合并不在此列——`revert_merge` 早把那些行搬回去了,再撤一次+ -- 会把事实挂到一个它从来没待过的实体上。+ -- 链式(A→B 再 B→C)取**最早**的那一次:它的 source 就是 T 时刻的持有者。+ SELECT m.source_id INTO undone+ FROM entity_merges m+ WHERE m.reverted_at IS NULL+ AND m.created_at > at+ AND fact_id = ANY(+ CASE WHEN on_object THEN m.moved_object_facts ELSE m.moved_subject_facts END)+ ORDER BY m.created_at+ LIMIT 1;+ IF undone IS NOT NULL THEN+ owner := undone;+ END IF;++ -- ② 应用:T 当时正生效、后来被撤销的合并。它的移动已经被撤掉,当前行里看不见,+ -- 但在 T 那一刻,这条事实确实挂在 target 上——记录轴上那段窗口是真实存在过的。+ SELECT m.target_id INTO applied+ FROM entity_merges m+ WHERE m.reverted_at IS NOT NULL+ AND m.created_at <= at+ AND m.reverted_at > at+ AND m.source_id = owner+ AND fact_id = ANY(+ CASE WHEN on_object THEN m.moved_object_facts ELSE m.moved_subject_facts END)+ ORDER BY m.created_at DESC+ LIMIT 1;+ IF applied IS NOT NULL THEN+ owner := applied;+ END IF;++ RETURN owner;+END;+$$;++-- 撤销那一步按 (reverted_at, created_at) 找,且要按数组成员判断——数组含判断用不上+-- B-tree,所以先用这个部分索引把行集收窄到「仍生效的合并」,剩下的行数在一个库里+-- 是个位数到几十的量级。+CREATE INDEX entity_merges_live_idx+ ON entity_merges (kb_id, created_at)+ WHERE reverted_at IS NULL;