Skip to content

World's first open-source enterprise world model.

The graph reads rewind the recording axis (#317)

WaylandYang35be42d3d6f2
diff --git a/crates/utopia-server/src/api/graph_routes.rs b/crates/utopia-server/src/api/graph_routes.rs
index 3164703b..9fce3a88 100644
--- a/crates/utopia-server/src/api/graph_routes.rs
+++ b/crates/utopia-server/src/api/graph_routes.rs
@@ -19,8 +19,15 @@ pub(super) async fn require_kb(
utopia_store::access::require_kb(&state.pool, user, kb_id, min).await
}
-/// `at`:可选 as-of 日期(YYYY-MM-DD 或 RFC3339)——服务端时间旅行。
-fn parse_at(raw: Option<&str>) -> Result<Option<chrono::DateTime<chrono::Utc>>, AppError> {
+/// 时刻参数(YYYY-MM-DD 或 RFC3339)——服务端时间旅行。
+///
+/// 两根轴共用这一个解析:`at` 走世界轴(那时世界是什么样),`as_of` 走记录轴
+/// (那时我们以为世界是什么样)。**两个参数一路分开**(0019):合成一个控件,
+/// 答出来的是另一个问题,而屏幕上看不出来
+fn parse_instant(
+ field: &str,
+ raw: Option<&str>,
+) -> Result<Option<chrono::DateTime<chrono::Utc>>, AppError> {
let Some(s) = raw.map(str::trim).filter(|s| !s.is_empty()) else {
return Ok(None);
};
@@ -29,7 +36,11 @@ fn parse_at(raw: Option<&str>) -> Result<Option<chrono::DateTime<chrono::Utc>>,
}
chrono::DateTime::parse_from_rfc3339(s)
.map(|t| Some(t.with_timezone(&chrono::Utc)))
- .map_err(|_| AppError::Validation("Invalid `at` (expected YYYY-MM-DD or RFC3339)".into()))
+ .map_err(|_| {
+ AppError::Validation(format!(
+ "Invalid `{field}` (expected YYYY-MM-DD or RFC3339)"
+ ))
+ })
}
/// 总览一次画多少个节点的**默认值**。上限本身是合理的——画一万个点没人看得懂;
@@ -44,6 +55,9 @@ const GRAPH_NODE_CAP_MAX: i64 = 1000;
pub struct OverviewQuery {
#[serde(default)]
pub at: Option<String>,
+ /// 记录轴:那时**我们持有**的图(0019)。不给就是现在
+ #[serde(default)]
+ pub as_of: Option<String>,
/// 画多少个。不给就用默认值;给了也钳在 [10, GRAPH_NODE_CAP_MAX]——
/// 界面上的按钮只给几档,但接口是公开的,别让一个 `limit=999999` 把库拖垮
#[serde(default)]
@@ -57,7 +71,8 @@ pub async fn overview(
Query(q): Query<OverviewQuery>,
) -> ApiResult<Json<serde_json::Value>> {
require_kb(&state, &user, kb_id, Role::Viewer).await?;
- let at = parse_at(q.at.as_deref())?;
+ let at = parse_instant("at", q.at.as_deref())?;
+ let as_of = parse_instant("as_of", q.as_of.as_deref())?;
// 画多少个是渲染的事,库里有多少是知识库的事——两个数都回,界面才说得出
// 「画了 150 个,共 325 个」而不是把上限说成规模
let limit = q
@@ -65,7 +80,7 @@ pub async fn overview(
.unwrap_or(GRAPH_NODE_CAP)
.clamp(10, GRAPH_NODE_CAP_MAX);
let (nodes, edges, total_nodes, total_edges) =
- utopia_store::graph::overview(&state.pool, kb_id, limit, at).await?;
+ utopia_store::graph::overview(&state.pool, kb_id, limit, at, as_of).await?;
Ok(Json(json!({
"nodes": nodes, "edges": edges,
"total_nodes": total_nodes, "total_edges": total_edges,
@@ -79,6 +94,8 @@ pub struct NeighborhoodQuery {
pub hops: Option<u8>,
#[serde(default)]
pub at: Option<String>,
+ #[serde(default)]
+ pub as_of: Option<String>,
}
pub async fn neighborhood(
@@ -88,10 +105,17 @@ pub async fn neighborhood(
Query(q): Query<NeighborhoodQuery>,
) -> ApiResult<Json<serde_json::Value>> {
require_kb(&state, &user, kb_id, Role::Viewer).await?;
- let at = parse_at(q.at.as_deref())?;
- let (nodes, edges) =
- utopia_store::graph::neighborhood(&state.pool, kb_id, q.entity, q.hops.unwrap_or(2), at)
- .await?;
+ let at = parse_instant("at", q.at.as_deref())?;
+ let as_of = parse_instant("as_of", q.as_of.as_deref())?;
+ let (nodes, edges) = utopia_store::graph::neighborhood(
+ &state.pool,
+ kb_id,
+ q.entity,
+ q.hops.unwrap_or(2),
+ at,
+ as_of,
+ )
+ .await?;
Ok(Json(json!({ "nodes": nodes, "edges": edges })))
}
@@ -127,13 +151,23 @@ pub async fn search_entities(
Ok(Json(json!({ "entities": entities, "total": total })))
}
+#[derive(Deserialize)]
+pub struct EntityDetailQuery {
+ /// 记录轴:回放中的图上点开一个节点,面板该说**当时**的事实(0019)
+ #[serde(default)]
+ pub as_of: Option<String>,
+}
+
pub async fn entity_detail(
State(state): State<AppState>,
AuthUser(user): AuthUser,
Path((kb_id, entity_id)): Path<(Uuid, Uuid)>,
+ Query(q): Query<EntityDetailQuery>,
) -> ApiResult<Json<serde_json::Value>> {
require_kb(&state, &user, kb_id, Role::Viewer).await?;
- let (entity, facts) = utopia_store::graph::entity_detail(&state.pool, kb_id, entity_id).await?;
+ let as_of = parse_instant("as_of", q.as_of.as_deref())?;
+ let (entity, facts) =
+ utopia_store::graph::entity_detail(&state.pool, kb_id, entity_id, as_of).await?;
// 推出来的那些**单独回一个键**,不掺进 `facts`。前端据此给它们自己的一档:
// 一条派生边跟一条断言边混在同一个列表里,用户看不出「这条是文档里写的」
// 和「这条是引擎推的」的区别,而那正是推理会污染知识的样子
diff --git a/crates/utopia-server/src/api/tools.rs b/crates/utopia-server/src/api/tools.rs
index 1c4a414b..8a0d8feb 100644
--- a/crates/utopia-server/src/api/tools.rs
+++ b/crates/utopia-server/src/api/tools.rs
@@ -301,7 +301,7 @@ pub async fn entity_facts(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolRe
json!({ "kind": "facts", "label": "?", "detail": "invalid id" }),
);
};
- match utopia_store::graph::entity_detail(&ctx.state.pool, ctx.kb_id, id).await {
+ match utopia_store::graph::entity_detail(&ctx.state.pool, ctx.kb_id, id, None).await {
Ok((node, mut facts)) => {
if let Some(t) = at {
facts.retain(|f| {
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs
index 1f70f0f0..28cdde16 100644
--- a/crates/utopia-store/src/graph.rs
+++ b/crates/utopia-store/src/graph.rs
@@ -347,18 +347,32 @@ pub async fn add_evidence(
///
/// key 与 label 留 NULL,**颜色和形状给缺省值**:前者是身份,没有就该说没有;
/// 后者是画布必须拿到的东西,编不出来就没法渲染。灰色圆点正是「还没定」的样子
-const NODE_SQL: &str = "SELECT e.id, e.canonical_name AS name, t.key AS type_key,
+/// `as_of`:绑记录轴参数的位置(`None` = 只答现在,写路径和"当下"视图用这个)。
+/// 度数跟着画布走——回放时数的是**当时**连在这个节点上的边,否则右上角的数
+/// 和眼前的图对不上。
+fn node_sql(as_of: 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(),
+ };
+ format!(
+ "SELECT e.id, e.canonical_name AS name, t.key AS type_key,
t.label AS type_label,
coalesce(t.color, '#94a3b8') AS color,
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 f.invalidated_at IS NULL) AS degree
- FROM entities e LEFT JOIN entity_types t ON t.id = e.type_id";
+ WHERE (f.subject_id = e.id OR f.object_id = e.id) AND {held}) AS degree
+ FROM entities e LEFT JOIN entity_types t ON t.id = e.type_id"
+ )
+}
/// 全图概览:按度数取 top N 实体及其间的边。
-/// `at`:服务端 as-of——只返回 T 时刻有效的边(起点不晚于 T 或未知,终点晚于 T 或开放)。
-/// 前端时间滑杆走本地过滤不传此参数;这是给 API/MCP 消费者的时间旅行入口。
+/// `at`:世界轴——只返回 T 时刻**有效**的边(起点不晚于 T 或未知,终点晚于 T 或开放)。
+/// `as_of`:记录轴(0019)——只返回 T 时刻**我们持有**的边,三月被改掉的断言在
+/// 三月之前的位置上应当还在。两个参数一路分开到 API:折成一个控件,就会拿
+/// 「三月的世界,以今天的认知」去答「三月的世界,以三月的认知」,而两者在
+/// 屏幕上都说得通。
/// 图谱总览:度数最高的 `limit` 个节点,以及它们之间的边。
///
/// **一并回总数。** 画多少个是渲染的事,库里有多少是知识库的事,两者从前
@@ -370,34 +384,44 @@ pub async fn overview(
kb_id: Uuid,
limit: i64,
at: Option<chrono::DateTime<chrono::Utc>>,
+ as_of: Option<chrono::DateTime<chrono::Utc>>,
) -> AppResult<(Vec<GraphNode>, Vec<GraphEdge>, i64, i64)> {
let nodes: Vec<GraphNode> = sqlx::query_as(&format!(
- "{NODE_SQL} WHERE e.kb_id = $1 AND e.merged_into IS NULL ORDER BY degree DESC, e.created_at LIMIT $2"
+ "{} WHERE e.kb_id = $1 AND e.merged_into IS NULL ORDER BY degree DESC, e.created_at LIMIT $2",
+ node_sql(Some(3))
))
.bind(kb_id)
.bind(limit)
+ .bind(as_of)
.fetch_all(pool)
.await?;
let ids: Vec<Uuid> = nodes.iter().map(|n| n.id).collect();
- let edges = edges_among(pool, kb_id, &ids, at).await?;
+ let edges = edges_among(pool, kb_id, &ids, at, as_of).await?;
// 总数按与画布同一套口径数:合并掉的实体不算,作废的事实不算,
// 属性事实(宾语是字面值)画不出边所以也不算。口径不同的话,
- // 「150 / 325」里那个 325 会跟用户在别处看到的数对不上
+ // 「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",
)
.bind(kb_id)
.fetch_one(pool)
.await?;
- let total_edges: i64 = sqlx::query_scalar(
- "SELECT (SELECT count(*) FROM facts
- WHERE kb_id = $1 AND invalidated_at IS NULL AND object_id IS NOT NULL)
- + (SELECT count(*) FROM derived_facts
- WHERE kb_id = $1 AND invalidated_at IS NULL)",
- )
+ let total_edges: i64 = sqlx::query_scalar(&format!(
+ "SELECT (SELECT count(*) FROM facts f
+ WHERE f.kb_id = $1 AND {facts_held} AND f.object_id IS NOT NULL)
+ + (SELECT count(*) FROM derived_facts d
+ WHERE d.kb_id = $1 AND {derived_held})",
+ facts_held = crate::record_axis::facts_held_at("f", 2),
+ derived_held = crate::record_axis::derived_held_at("d", 2),
+ ))
.bind(kb_id)
+ .bind(as_of)
.fetch_one(pool)
.await?;
Ok((nodes, edges, total_nodes, total_edges))
@@ -408,6 +432,7 @@ async fn edges_among(
kb_id: Uuid,
ids: &[Uuid],
at: Option<chrono::DateTime<chrono::Utc>>,
+ as_of: Option<chrono::DateTime<chrono::Utc>>,
) -> AppResult<Vec<GraphEdge>> {
if ids.is_empty() {
return Ok(Vec::new());
@@ -425,7 +450,7 @@ async fn edges_among(
//
// 断言那一段多算一位 `contested`:有 open 的违规或时态冲突指着它。派生撞断言
// 时被撞的是 left;right 只是最后一条前提,它本身没有争议
- let edges: Vec<GraphEdge> = sqlx::query_as(
+ let edges: Vec<GraphEdge> = sqlx::query_as(&format!(
"SELECT f.id, f.subject_id AS source, f.object_id AS target,
COALESCE(r.key, fact_surface_predicate(f.id)) AS predicate,
COALESCE(r.label, fact_surface_predicate(f.id)) AS label,
@@ -433,16 +458,16 @@ async fn edges_among(
ARRAY[]::uuid[] AS premises,
f.valid_from, f.valid_to, f.confidence,
(EXISTS (SELECT 1 FROM axiom_violations v
- WHERE v.status = 'open'
+ WHERE {violation_open}
AND (v.left_fact = f.id
OR (v.right_fact = f.id AND v.kind <> 'derived_contradiction')))
OR EXISTS (SELECT 1 FROM fact_conflicts c
- WHERE c.status = 'open'
+ WHERE {conflict_open}
AND (c.old_fact_id = f.id OR c.new_fact_id = f.id))
) AS contested,
FALSE AS blocked
FROM facts f LEFT JOIN relation_types r ON r.id = f.predicate_id
- WHERE f.kb_id = $1 AND f.invalidated_at IS NULL AND f.object_id IS NOT NULL
+ WHERE 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 ($3::timestamptz IS NULL
OR ((f.valid_from IS NULL OR f.valid_from <= $3)
@@ -457,7 +482,7 @@ async fn edges_among(
FALSE AS contested, FALSE AS blocked
FROM derived_facts d JOIN relation_types r ON r.id = d.predicate_id
JOIN rules ru ON ru.id = d.rule_id
- WHERE d.kb_id = $1 AND d.invalidated_at IS NULL
+ WHERE d.kb_id = $1 AND {derived_held}
AND d.subject_id = ANY($2) AND d.object_id = ANY($2)
AND ($3::timestamptz IS NULL
OR ((d.valid_from IS NULL OR d.valid_from <= $3)
@@ -474,7 +499,7 @@ async fn edges_among(
0::real AS confidence,
TRUE AS contested, TRUE AS blocked
FROM axiom_violations v
- WHERE v.kb_id = $1 AND v.kind = 'derived_contradiction' AND v.status = 'open'
+ WHERE v.kb_id = $1 AND v.kind = 'derived_contradiction' AND {violation_open}
AND (v.detail->>'subject_id')::uuid = ANY($2)
AND (v.detail->>'object_id')::uuid = ANY($2)
AND ($3::timestamptz IS NULL
@@ -482,10 +507,15 @@ async fn edges_among(
OR (v.detail->>'valid_from')::timestamptz <= $3)
AND ((v.detail->>'valid_to')::timestamptz IS NULL
OR (v.detail->>'valid_to')::timestamptz > $3)))",
- )
+ facts_held = crate::record_axis::facts_held_at("f", 4),
+ 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),
+ ))
.bind(kb_id)
.bind(ids)
.bind(at)
+ .bind(as_of)
.fetch_all(pool)
.await?;
Ok(edges)
@@ -498,6 +528,7 @@ pub async fn neighborhood(
entity_id: Uuid,
hops: u8,
at: Option<chrono::DateTime<chrono::Utc>>,
+ as_of: Option<chrono::DateTime<chrono::Utc>>,
) -> AppResult<(Vec<GraphNode>, Vec<GraphEdge>)> {
const MAX_NODES: usize = 300;
let mut seen: HashSet<Uuid> = HashSet::from([entity_id]);
@@ -507,13 +538,17 @@ pub async fn neighborhood(
if frontier.is_empty() || seen.len() >= MAX_NODES {
break;
}
- let touching: Vec<(Uuid, Option<Uuid>)> = sqlx::query_as(
- "SELECT subject_id, object_id FROM facts
- WHERE kb_id = $1 AND invalidated_at IS NULL AND object_id IS NOT NULL
- AND (subject_id = ANY($2) OR object_id = ANY($2))",
- )
+ // 铺开也走记录轴:邻居按**当时**的边找,否则回放的图上会长出
+ // 只有今天才连得上的节点
+ let touching: Vec<(Uuid, Option<Uuid>)> = sqlx::query_as(&format!(
+ "SELECT f.subject_id, f.object_id FROM facts f
+ WHERE 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))",
+ facts_held = crate::record_axis::facts_held_at("f", 3),
+ ))
.bind(kb_id)
.bind(&frontier)
+ .bind(as_of)
.fetch_all(pool)
.await?;
@@ -532,13 +567,16 @@ pub async fn neighborhood(
}
let ids: Vec<Uuid> = seen.into_iter().collect();
- let nodes: Vec<GraphNode> =
- sqlx::query_as(&format!("{NODE_SQL} WHERE e.kb_id = $1 AND e.id = ANY($2)"))
- .bind(kb_id)
- .bind(&ids)
- .fetch_all(pool)
- .await?;
- let edges = edges_among(pool, kb_id, &ids, at).await?;
+ let nodes: Vec<GraphNode> = sqlx::query_as(&format!(
+ "{} WHERE e.kb_id = $1 AND e.id = ANY($2)",
+ node_sql(Some(3))
+ ))
+ .bind(kb_id)
+ .bind(&ids)
+ .bind(as_of)
+ .fetch_all(pool)
+ .await?;
+ let edges = edges_among(pool, kb_id, &ids, at, as_of).await?;
Ok((nodes, edges))
}
@@ -553,9 +591,10 @@ pub async fn search_entities(
) -> AppResult<(Vec<GraphNode>, i64)> {
let pattern = format!("%{}%", q.trim());
let nodes: Vec<GraphNode> = sqlx::query_as(&format!(
- "{NODE_SQL} WHERE e.kb_id = $1 AND e.merged_into IS NULL
+ "{} WHERE e.kb_id = $1 AND e.merged_into IS NULL
AND e.canonical_name ILIKE $2
- ORDER BY degree DESC, e.canonical_name LIMIT $3 OFFSET $4"
+ ORDER BY degree DESC, e.canonical_name LIMIT $3 OFFSET $4",
+ node_sql(None)
))
.bind(kb_id)
.bind(&pattern)
@@ -579,15 +618,20 @@ pub async fn entity_detail(
pool: &PgPool,
kb_id: Uuid,
entity_id: Uuid,
+ as_of: Option<chrono::DateTime<chrono::Utc>>,
) -> AppResult<(GraphNode, Vec<EntityFact>)> {
- let node: GraphNode = sqlx::query_as(&format!("{NODE_SQL} WHERE e.kb_id = $1 AND e.id = $2"))
- .bind(kb_id)
- .bind(entity_id)
- .fetch_optional(pool)
- .await?
- .ok_or(AppError::NotFound)?;
+ let node: GraphNode = sqlx::query_as(&format!(
+ "{} WHERE e.kb_id = $1 AND e.id = $2",
+ node_sql(Some(3))
+ ))
+ .bind(kb_id)
+ .bind(entity_id)
+ .bind(as_of)
+ .fetch_optional(pool)
+ .await?
+ .ok_or(AppError::NotFound)?;
- let facts: Vec<EntityFact> = sqlx::query_as(
+ let facts: Vec<EntityFact> = sqlx::query_as(&format!(
"SELECT f.id,
CASE WHEN f.subject_id = $2 THEN 'out' ELSE 'in' END AS direction,
COALESCE(r.key, fact_surface_predicate(f.id)) AS predicate_key,
@@ -600,7 +644,7 @@ pub async fn entity_detail(
(EXISTS (SELECT 1 FROM fact_evidence fe WHERE fe.fact_id = f.id)
AND NOT EXISTS (SELECT 1 FROM fact_evidence fe
JOIN chunks c ON c.id = fe.chunk_id
- WHERE fe.fact_id = f.id AND c.superseded_at IS NULL)
+ WHERE fe.fact_id = f.id AND {chunk_live})
) AS stale,
(f.supersedes IS NOT NULL) AS corrected,
(SELECT MAX(COALESCE(d.doc_time, d.created_at))
@@ -614,13 +658,13 @@ pub async fn entity_detail(
|| (v.detail->>'predicate') || ' · '
|| (v.detail->>'object') END)
FROM axiom_violations v
- WHERE v.status = 'open'
+ WHERE {violation_open}
AND (v.left_fact = f.id
OR (v.right_fact = f.id AND v.kind <> 'derived_contradiction'))
ORDER BY v.detected_at DESC LIMIT 1),
(SELECT jsonb_build_object('kind', 'temporal_conflict', 'ref_id', c.id)
FROM fact_conflicts c
- WHERE c.status = 'open'
+ WHERE {conflict_open}
AND (c.old_fact_id = f.id OR c.new_fact_id = f.id)
ORDER BY c.created_at DESC LIMIT 1)
) AS contested
@@ -628,12 +672,17 @@ pub async fn entity_detail(
LEFT JOIN relation_types r ON r.id = f.predicate_id
LEFT JOIN entities o
ON o.id = CASE WHEN f.subject_id = $2 THEN f.object_id ELSE f.subject_id END
- WHERE f.kb_id = $1 AND f.invalidated_at IS NULL
+ WHERE f.kb_id = $1 AND {facts_held}
AND (f.subject_id = $2 OR f.object_id = $2)
ORDER BY f.valid_from NULLS LAST, f.recorded_at",
- )
+ facts_held = crate::record_axis::facts_held_at("f", 3),
+ 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),
+ ))
.bind(kb_id)
.bind(entity_id)
+ .bind(as_of)
.fetch_all(pool)
.await?;
@@ -654,7 +703,8 @@ pub async fn update_entity(
canonical_name: Option<&str>,
) -> AppResult<(GraphNode, GraphNode)> {
let before: GraphNode = sqlx::query_as(&format!(
- "{NODE_SQL} WHERE e.kb_id = $1 AND e.id = $2 AND e.merged_into IS NULL"
+ "{} WHERE e.kb_id = $1 AND e.id = $2 AND e.merged_into IS NULL",
+ node_sql(None)
))
.bind(kb_id)
.bind(entity_id)
@@ -729,11 +779,14 @@ pub async fn update_entity(
crate::resolution::refresh_disambiguators(pool, kb_id, &before.name).await?;
}
- let after: GraphNode = sqlx::query_as(&format!("{NODE_SQL} WHERE e.kb_id = $1 AND e.id = $2"))
- .bind(kb_id)
- .bind(entity_id)
- .fetch_one(pool)
- .await?;
+ let after: GraphNode = sqlx::query_as(&format!(
+ "{} WHERE e.kb_id = $1 AND e.id = $2",
+ node_sql(None)
+ ))
+ .bind(kb_id)
+ .bind(entity_id)
+ .fetch_one(pool)
+ .await?;
Ok((before, after))
}
@@ -745,9 +798,10 @@ pub async fn same_name_peers(
entity_id: Uuid,
) -> AppResult<Vec<GraphNode>> {
sqlx::query_as(&format!(
- "{NODE_SQL} WHERE e.kb_id = $1 AND e.merged_into IS NULL AND e.id <> $2
+ "{} WHERE e.kb_id = $1 AND e.merged_into IS NULL AND e.id <> $2
AND lower(e.canonical_name) = (SELECT lower(canonical_name) FROM entities WHERE id = $2)
- ORDER BY degree DESC LIMIT 10"
+ ORDER BY degree DESC LIMIT 10",
+ node_sql(None)
))
.bind(kb_id)
.bind(entity_id)
diff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rs
index 3daa6f6b..151fcac4 100644
--- a/crates/utopia-store/src/lib.rs
+++ b/crates/utopia-store/src/lib.rs
@@ -21,6 +21,7 @@ pub mod ontology;
pub mod palette;
pub mod pending;
pub mod reasoning;
+pub mod record_axis;
pub mod resolution;
pub mod review;
pub mod sealing;
diff --git a/crates/utopia-store/src/record_axis.rs b/crates/utopia-store/src/record_axis.rs
new file mode 100644
index 00000000..fa2981c8
--- /dev/null
+++ b/crates/utopia-store/src/record_axis.rs
@@ -0,0 +1,64 @@
+//! 记录轴谓词(0019):`held_at(T)`——**T 时刻我们认为哪些行成立**。
+//!
+//! 世界轴(`valid_from` / `valid_to`)答"那时世界是什么样",记录轴(`recorded_at` /
+//! `invalidated_at`)答"那时我们以为世界是什么样"。写入侧从图谱迁移起就一直记着
+//! 两根轴,读出侧只倒得回第一根——三月被改掉的事实,在任何滑杆位置上都不存在。
+//!
+//! **谓词只在这里拼。** 防御一旦散到每个读点,漏掉一个就悄无声息:SQL 不报错,
+//! `cargo check` 也不会说一个字(0009 栽的正是这一跤,`human_type_decisions`
+//! 那个测试就是那次留下的)。所以读路径引这里的函数,不自己写 `invalidated_at`。
+//!
+//! **写路径不用**(0019):`confirm_fact` / `reject_fact`、采纳的撤销、去重查重
+//! 都是对"当前那一行"的守卫——修正永远发生在现在,没有"以三月的身份改一行"这回事。
+//!
+//! 参数绑 `Option<DateTime<Utc>>`:`NULL` 即"现在",谓词随之退化成
+//! `invalidated_at IS NULL`(不会有哪一行的作废时刻晚于此刻)。读路径因此
+//! 只写一条语句,而不是为回放和当下各写一条——两条就是下一次漏改的地方。
+
+/// 起止两列构成的记录轴区间:`since <= T < invalidated_at`。
+fn held(alias: &str, since: &str, param: usize) -> String {
+ format!(
+ "{alias}.{since} <= coalesce(${param}, now()) \
+ AND ({alias}.invalidated_at IS NULL OR {alias}.invalidated_at > coalesce(${param}, now()))"
+ )
+}
+
+/// `facts`:断言在 T 时刻仍被我们持有。
+pub fn facts_held_at(alias: &str, param: usize) -> String {
+ held(alias, "recorded_at", param)
+}
+
+/// `derived_facts`:派生在 T 时刻已推出且未被推翻——回放的图上留着**当时**推出的边,
+/// 而不是今天这套规则的结论。
+pub fn derived_held_at(alias: &str, param: usize) -> String {
+ held(alias, "derived_at", param)
+}
+
+/// `axiom_violations`:违规在 T 时刻还开着。列名与上面两张表不同(`detected_at` /
+/// `decided_at` + `status`),但问的是同一个问题——所以也归这里,别在读点上现拼。
+///
+/// 已裁掉却没留 `decided_at` 的历史行按"当时就不开着"算:宁可少画一条幽灵边,
+/// 也不要凭空给三月的图加一条今天才发现的矛盾。
+pub fn violation_open_at(alias: &str, param: usize) -> String {
+ format!(
+ "{alias}.detected_at <= coalesce(${param}, now()) \
+ AND ({alias}.status = 'open' OR {alias}.decided_at > coalesce(${param}, now()))"
+ )
+}
+
+/// `fact_conflicts`:时态冲突在 T 时刻还开着。
+pub fn conflict_open_at(alias: &str, param: usize) -> String {
+ format!(
+ "{alias}.created_at <= coalesce(${param}, now()) \
+ AND ({alias}.status = 'open' OR {alias}.resolved_at > coalesce(${param}, now()))"
+ )
+}
+
+/// `chunks`:分块在 T 时刻还是现行版本。证据是否"已消失"要按当时的版本判——
+/// 今天被重解析顶掉的段落,在三月的图上仍然是活证据。
+pub fn chunk_live_at(alias: &str, param: usize) -> String {
+ format!(
+ "{alias}.created_at <= coalesce(${param}, now()) \
+ AND ({alias}.superseded_at IS NULL OR {alias}.superseded_at > coalesce(${param}, now()))"
+ )
+}
diff --git a/crates/utopia-store/tests/a_contradiction_points_upstream.rs b/crates/utopia-store/tests/a_contradiction_points_upstream.rs
index 9b446d63..cb427a90 100644
--- a/crates/utopia-store/tests/a_contradiction_points_upstream.rs
+++ b/crates/utopia-store/tests/a_contradiction_points_upstream.rs
@@ -226,7 +226,7 @@ async fn a_contradiction_points_upstream() -> anyhow::Result<()> {
// 争议在它坐的地方可见(0017 §3):面板行挂 contested,图上有一条幽灵边,
// 「没落地的」一档有一行,它的证明链读得出前提
- let (_, facts) = utopia_store::graph::entity_detail(&pool, f.kb, f.mira).await?;
+ let (_, facts) = utopia_store::graph::entity_detail(&pool, f.kb, f.mira, None).await?;
let hit = facts
.iter()
.find(|x| x.id == old)
@@ -246,7 +246,8 @@ async fn a_contradiction_points_upstream() -> anyhow::Result<()> {
.is_none(),
"the premise is not the disputed one"
);
- let (_, edges) = utopia_store::graph::neighborhood(&pool, f.kb, f.mira, 1, None).await?;
+ let (_, edges) =
+ utopia_store::graph::neighborhood(&pool, f.kb, f.mira, 1, None, None).await?;
let ghost = edges
.iter()
.find(|e| e.blocked)
diff --git a/crates/utopia-store/tests/no_predicate_still_shows.rs b/crates/utopia-store/tests/no_predicate_still_shows.rs
index 27f0ff11..dc7c17e3 100644
--- a/crates/utopia-store/tests/no_predicate_still_shows.rs
+++ b/crates/utopia-store/tests/no_predicate_still_shows.rs
@@ -179,7 +179,8 @@ async fn a_fact_without_a_predicate_is_still_visible_everywhere() -> anyhow::Res
assert!(none.is_none(), "连原文说法都没有时该是空,而不是编一个词");
// 2. 图的边:两条都要在,且都标成 inferred
- let (_, edges) = utopia_store::graph::neighborhood(&pool, f.kb, f.subject, 1, None).await?;
+ let (_, edges) =
+ utopia_store::graph::neighborhood(&pool, f.kb, f.subject, 1, None, None).await?;
let ours: Vec<_> = edges
.iter()
.filter(|e| e.id == f.surfaced || e.id == f.mute)
@@ -192,7 +193,7 @@ async fn a_fact_without_a_predicate_is_still_visible_everywhere() -> anyhow::Res
assert!(m.label.is_none(), "说不出就是说不出,不该回落成「有关联」");
// 3. 实体面板
- let (_, facts) = utopia_store::graph::entity_detail(&pool, f.kb, f.subject).await?;
+ let (_, facts) = utopia_store::graph::entity_detail(&pool, f.kb, f.subject, None).await?;
let panel: Vec<_> = facts
.iter()
.filter(|x| x.id == f.surfaced || x.id == f.mute)
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.rs
new file mode 100644
index 00000000..d85eb139
--- /dev/null
+++ b/crates/utopia-store/tests/the_second_clock_can_be_rewound.rs
@@ -0,0 +1,272 @@
+//! 记录轴回退(0019 / #307),打在真库上。
+//!
+//! 为什么非要连库:这道防御**整个活在 SQL 字符串里**。`cargo check` 看不见
+//! 一个漏写的 WHERE,clippy 也不会说一个字——0009 栽的正是这一跤(`NULL <> uuid`
+//! 不报错、只是什么都不选),`human_type_decisions` 那个测试就是那次留下的。
+//!
+//! 两个方向都要断言,因为它们会以不同的方式坏掉:
+//! - 撤掉的行在 `as_of = 现在` **不出现**(谓词写反了会让作废行全体复活)
+//! - 撤掉的行在作废时刻**之前出现**(谓词没接上就永远是"现在",回放照旧空手)
+//! - `recorded_at` 晚于 T 的行在 T **不出现**(只写下界会让三月看见四月的修正)
+//!
+//! 自建自拆:一次性 org/workspace/kb,跑完连 org 一起删。绝不碰已有的库。
+
+use sqlx::PgPool;
+use uuid::Uuid;
+
+fn t(s: &str) -> chrono::DateTime<chrono::Utc> {
+ s.parse().unwrap()
+}
+
+struct Fixture {
+ kb: Uuid,
+ zhang: Uuid,
+ /// 03-01 记下、03-20 被修正掉的那条断言
+ retracted: Uuid,
+ /// 03-20 记下的修正行
+ correction: Uuid,
+ /// 03-05 推出、03-22 前提没了的派生
+ derived: Uuid,
+}
+
+/// 一个人接过一个项目,我们三月改了主意,引擎在这中间推过一条边。
+async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {
+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let (person, project) = (Uuid::now_v7(), Uuid::now_v7());
+ let (leads, part_of) = (Uuid::now_v7(), Uuid::now_v7());
+ let (zhang, phoenix, program) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let (retracted, correction, derived, rule) = (
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ );
+
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'rewind-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'rewind-test')")
+ .bind(ws)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'rewind-test')",
+ )
+ .bind(kb)
+ .bind(ws)
+ .execute(pool)
+ .await?;
+ for (id, key, label) in [
+ (person, "person", "Person"),
+ (project, "project", "Project"),
+ ] {
+ sqlx::query("INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, $3, $4)")
+ .bind(id)
+ .bind(kb)
+ .bind(key)
+ .bind(label)
+ .execute(pool)
+ .await?;
+ }
+ for (id, key, label) in [(leads, "leads", "leads"), (part_of, "part_of", "part of")] {
+ sqlx::query("INSERT INTO relation_types (id, kb_id, key, label) VALUES ($1, $2, $3, $4)")
+ .bind(id)
+ .bind(kb)
+ .bind(key)
+ .bind(label)
+ .execute(pool)
+ .await?;
+ }
+ for (id, type_id, name) in [
+ (zhang, person, "Zhang San"),
+ (phoenix, project, "Project Phoenix"),
+ (program, project, "Phoenix Program"),
+ ] {
+ sqlx::query(
+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",
+ )
+ .bind(id)
+ .bind(kb)
+ .bind(type_id)
+ .bind(name)
+ .execute(pool)
+ .await?;
+ }
+
+ let fact = |id: Uuid, rec: &str, inv: Option<&str>, sup: Option<Uuid>| {
+ let (rec, inv) = (t(rec), inv.map(t));
+ sqlx::query(
+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id,
+ recorded_at, invalidated_at, supersedes)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
+ )
+ .bind(id)
+ .bind(kb)
+ .bind(zhang)
+ .bind(leads)
+ .bind(phoenix)
+ .bind(rec)
+ .bind(inv)
+ .bind(sup)
+ };
+ fact(
+ retracted,
+ "2026-03-01T00:00:00Z",
+ Some("2026-03-20T00:00:00Z"),
+ None,
+ )
+ .execute(pool)
+ .await?;
+ fact(correction, "2026-03-20T00:00:00Z", None, Some(retracted))
+ .execute(pool)
+ .await?;
+
+ // 派生也有两根轴(derived_at / invalidated_at):回放的图上留着**当时**推出
+ // 的边,而不是今天这套规则的结论
+ sqlx::query(
+ "INSERT INTO rules (id, kb_id, predicate_id, kind) VALUES ($1, $2, $3, 'transitive')",
+ )
+ .bind(rule)
+ .bind(kb)
+ .bind(part_of)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO derived_facts (id, kb_id, subject_id, predicate_id, object_id, rule_id,
+ derived_at, invalidated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
+ )
+ .bind(derived)
+ .bind(kb)
+ .bind(phoenix)
+ .bind(part_of)
+ .bind(program)
+ .bind(rule)
+ .bind(t("2026-03-05T00:00:00Z"))
+ .bind(t("2026-03-22T00:00:00Z"))
+ .execute(pool)
+ .await?;
+
+ Ok(Fixture {
+ kb,
+ zhang,
+ retracted,
+ correction,
+ derived,
+ })
+}
+
+fn edge_ids(edges: &[utopia_core::models::GraphEdge]) -> Vec<Uuid> {
+ let mut v: Vec<Uuid> = edges.iter().map(|e| e.id).collect();
+ v.sort();
+ v
+}
+
+fn sorted(mut v: Vec<Uuid>) -> Vec<Uuid> {
+ v.sort();
+ v
+}
+
+#[tokio::test]
+async fn the_recording_axis_rewinds_on_every_graph_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 overview = |as_of: Option<&'static str>| {
+ let pool = pool.clone();
+ async move { utopia_store::graph::overview(&pool, f.kb, 50, None, as_of.map(t)).await }
+ };
+
+ // 1. 现在:修正行在,被它顶掉的断言不在,前提没了的派生也不在
+ let (nodes, edges, _, total_edges) = overview(None).await?;
+ assert_eq!(
+ edge_ids(&edges),
+ vec![f.correction],
+ "现在只该有修正行那条边"
+ );
+ assert_eq!(total_edges, 1, "边总数跟着画布数,不是历史全量");
+ let degree = |nodes: &[utopia_core::models::GraphNode], id: Uuid| {
+ nodes.iter().find(|n| n.id == id).map(|n| n.degree)
+ };
+ assert_eq!(degree(&nodes, f.zhang), Some(1));
+
+ // 2. 倒回 03-10:作废前的断言回来了,三月才推出的派生也在,
+ // 而 03-20 才记下的修正行**不该出现**——那是当时还没发生的事
+ let (nodes, edges, _, total_edges) = overview(Some("2026-03-10T00:00:00Z")).await?;
+ assert_eq!(
+ edge_ids(&edges),
+ sorted(vec![f.retracted, f.derived]),
+ "03-10 该看见当时持有的断言与派生"
+ );
+ assert_eq!(total_edges, 2);
+ assert_eq!(degree(&nodes, f.zhang), Some(1), "度数按当时的边数");
+ assert!(
+ edges
+ .iter()
+ .find(|e| e.id == f.derived)
+ .is_some_and(|e| e.derived),
+ "派生边要带 derived 位,界面靠它画出区别"
+ );
+
+ // 3. 倒回 03-25:修正行已经记下,派生已经被推翻
+ let (_, edges, _, _) = overview(Some("2026-03-25T00:00:00Z")).await?;
+ assert_eq!(edge_ids(&edges), vec![f.correction]);
+
+ // 4. 更早于一切:图是空的,而不是"退化成现在"
+ let (_, edges, _, total_edges) = overview(Some("2026-02-01T00:00:00Z")).await?;
+ assert!(edges.is_empty(), "02-01 我们还什么都没记下");
+ assert_eq!(total_edges, 0);
+
+ // 5. 邻域铺开也按当时的边找邻居
+ let (_, edges) = utopia_store::graph::neighborhood(
+ &pool,
+ f.kb,
+ f.zhang,
+ 1,
+ None,
+ Some(t("2026-03-10T00:00:00Z")),
+ )
+ .await?;
+ assert_eq!(edge_ids(&edges), vec![f.retracted]);
+ let (_, edges) = utopia_store::graph::neighborhood(&pool, f.kb, f.zhang, 1, None, None).await?;
+ assert_eq!(edge_ids(&edges), vec![f.correction]);
+
+ // 6. 点开节点,面板说的是**当时**的事实——回放的图上点开一个节点,
+ // 侧栏还答今天的事,两个说法就并排摆在同一个屏幕上
+ let facts = |as_of: Option<&'static str>| {
+ let pool = pool.clone();
+ async move {
+ utopia_store::graph::entity_detail(&pool, f.kb, f.zhang, as_of.map(t))
+ .await
+ .map(|(_, facts)| facts)
+ }
+ };
+ let now = facts(None).await?;
+ assert_eq!(now.len(), 1);
+ assert_eq!(now[0].id, f.correction);
+ assert!(now[0].corrected, "修正行认得出自己改写了谁");
+
+ let march = facts(Some("2026-03-10T00:00:00Z")).await?;
+ assert_eq!(march.len(), 1);
+ assert_eq!(march[0].id, f.retracted, "03-10 面板该给出当时那条");
+
+ let before = facts(Some("2026-02-01T00:00:00Z")).await?;
+ assert!(before.is_empty(), "记下之前不该有事实");
+
+ // 拆台:facts/entities/… 全是 ON DELETE CASCADE
+ let gone = sqlx::query(
+ "DELETE FROM organizations WHERE id = (
+ SELECT w.org_id FROM workspaces w
+ JOIN knowledge_bases k ON k.workspace_id = w.id WHERE k.id = $1)",
+ )
+ .bind(f.kb)
+ .execute(&pool)
+ .await?;
+ assert_eq!(gone.rows_affected(), 1, "一次性 org 没删掉");
+ Ok(())
+}