Skip to content

World's first open-source enterprise world model.

An unknown date is not an open one (0022, first cut) (#394)

WaylandYang2c66a92b6443
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index f3b60b64..cb07f09b 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -606,6 +606,11 @@ pub struct GraphEdge {
pub premises: Vec<Uuid>,
pub valid_from: Option<DateTime<Utc>>,
pub valid_to: Option<DateTime<Utc>>,
+ /// **读出来的**区间(0022):没有起点的事实从最早的证据起,结束了不知哪天的
+ /// 到最早说出它的那份文档为止。滑杆按这两个过滤,不再自己解释 NULL——
+ /// 上面那两个是原文说了什么,只用来显示
+ pub holds_from: Option<DateTime<Utc>>,
+ pub holds_to: Option<DateTime<Utc>>,
pub confidence: f32,
/// 有争议(0017 §3):有一条 open 的公理违规或时态冲突指着它。整条边画成
/// 警戒色——环在节点上、边还是灰的,余光分不出来
@@ -642,6 +647,10 @@ pub struct EntityFact {
/// 结束端的粒度,外加一个 `unknown`——**原文说它结束了,但没说哪天**。
/// `valid_to` 与它都为 None 才是「仍在持续」(见 `facts.valid_to_precision`)
pub valid_to_precision: Option<String>,
+ /// **读出来的**区间(0022),与 `GraphEdge` 同义:面板判「此刻成立」按它,
+ /// 不再自己把 NULL 解释成开放
+ pub holds_from: Option<DateTime<Utc>>,
+ pub holds_to: Option<DateTime<Utc>>,
pub confidence: f32,
pub evidence_count: i64,
/// 证据全部停留在来源文档的旧版(未被现行内容确认;不代表事实失效)
diff --git a/crates/utopia-server/src/api/graph_routes.rs b/crates/utopia-server/src/api/graph_routes.rs
index 63565780..aa3b1cf3 100644
--- a/crates/utopia-server/src/api/graph_routes.rs
+++ b/crates/utopia-server/src/api/graph_routes.rs
@@ -166,13 +166,15 @@ pub async fn entity_detail(
) -> ApiResult<Json<serde_json::Value>> {
require_kb(&state, &user, kb_id, Role::Viewer).await?;
let as_of = parse_instant("as_of", q.as_of.as_deref())?;
+ // 世界轴不过滤(at = None):面板要的是整条时间线,「此刻成立」那一档由前端
+ // 按 holds_from / holds_to 分出来(0022)
let (entity, facts) =
- utopia_store::graph::entity_detail(&state.pool, kb_id, entity_id, as_of).await?;
+ utopia_store::graph::entity_detail(&state.pool, kb_id, entity_id, None, as_of).await?;
// 推出来的那些**单独回一个键**,不掺进 `facts`。前端据此给它们自己的一档:
// 一条派生边跟一条断言边混在同一个列表里,用户看不出「这条是文档里写的」
// 和「这条是引擎推的」的区别,而那正是推理会污染知识的样子
let derived =
- utopia_store::reasoning::derived_for_entity(&state.pool, kb_id, entity_id).await?;
+ utopia_store::reasoning::derived_for_entity(&state.pool, kb_id, entity_id, None).await?;
// 同名的那些**打开面板时就给**,不是等改名之后才回。
//
// 从前它只随 `update_entity` 的响应回来,于是「把同名的合并进来」这个动作
@@ -371,6 +373,9 @@ pub async fn update_fact_time(
from_precision: req.valid_from_precision.as_deref(),
to: req.valid_to,
to_precision: req.valid_to_precision.as_deref(),
+ // 修正行从被替代的行继承锚点(correct_interval 的 SQL 里):改区间是重述
+ // 同一份证据,不是更新的证据
+ attested_at: None,
};
let Some(corrected) =
utopia_store::temporal::correct_interval(&state.pool, fact_id, validity).await?
diff --git a/crates/utopia-server/src/api/tools.rs b/crates/utopia-server/src/api/tools.rs
index c5cf1bbc..de1d84e2 100644
--- a/crates/utopia-server/src/api/tools.rs
+++ b/crates/utopia-server/src/api/tools.rs
@@ -308,7 +308,8 @@ pub async fn entity_facts(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolRe
let id = args["entity_id"]
.as_str()
.and_then(|s| s.parse::<Uuid>().ok());
- // 世界轴过滤:T 时刻有效 = 起点不晚于 T(或未知)且终点晚于 T(或开放)
+ // 世界轴过滤在 SQL 里(world_axis,0022):没起点的事实从最早的证据起,结束了
+ // 不知哪天的到说出它的那份文档为止。这里只把 T 传下去,不自己解释 NULL
let at = args["at"].as_str().and_then(parse_when);
// 记录轴(0019 / #347):那一刻**我们持有**的事实。两根轴两个参数,绝不合成
// 一个——合起来就会拿「三月的世界,以今天的认知」去答「三月的世界,以三月的认知」
@@ -319,28 +320,17 @@ 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, as_of).await {
- Ok((node, mut facts)) => {
- if let Some(t) = at {
- facts.retain(|f| {
- f.valid_from.is_none_or(|from| from <= t) && f.valid_to.is_none_or(|to| to > t)
- });
- }
+ match utopia_store::graph::entity_detail(&ctx.state.pool, ctx.kb_id, id, at, as_of).await {
+ Ok((node, facts)) => {
// 规则的结论也是这个实体的一部分(0021)。**不给的话模型会拿那些
// 读数自己再判一遍**——而阈值写在规则里,它看不见,于是两处判断
// 迟早不一致,agent 那次还没有前提链、没有区间、也不进账本
let derived =
- utopia_store::reasoning::derived_for_entity(&ctx.state.pool, ctx.kb_id, id)
+ utopia_store::reasoning::derived_for_entity(&ctx.state.pool, ctx.kb_id, id, at)
.await
.unwrap_or_default();
let mut derived: Vec<String> = derived
.iter()
- .filter(|d| {
- at.is_none_or(|t| {
- d.valid_from.is_none_or(|from| from <= t)
- && d.valid_to.is_none_or(|to| to > t)
- })
- })
.map(|d| {
format!(
"{} · {} · {} [rule: {}]",
@@ -986,6 +976,8 @@ mod tests {
valid_to: Some(t("2024-02-20T00:00:00Z")),
valid_from_precision: Some("day".into()),
valid_to_precision: Some("day".into()),
+ holds_from: Some(t("2023-06-01T00:00:00Z")),
+ holds_to: Some(t("2024-02-20T00:00:00Z")),
confidence: 0.9,
evidence_count: 1,
stale: false,
diff --git a/crates/utopia-server/src/extraction.rs b/crates/utopia-server/src/extraction.rs
index 41be9fd1..f193c336 100644
--- a/crates/utopia-server/src/extraction.rs
+++ b/crates/utopia-server/src/extraction.rs
@@ -1016,6 +1016,9 @@ async fn run(state: &AppState, document_id: Uuid, proposer: Proposer) -> anyhow:
to_precision: to
.map(|(_, p)| p)
.or(ended_unknown.then_some(utopia_store::graph::ENDED_UNKNOWN)),
+ // 这次观察出自哪一天的文档(0022):没起点的事实从它起成立,结束了
+ // 不知哪天的到它为止。没有文档日期就是记下的此刻——账本能给的最好的
+ attested_at: doc.doc_time,
};
// 属性事实:谓词命中属性 → 字面值通道。datatype 校验失败宁缺勿脏;
diff --git a/crates/utopia-server/src/rdf.rs b/crates/utopia-server/src/rdf.rs
index e119a907..b60e6d9c 100644
--- a/crates/utopia-server/src/rdf.rs
+++ b/crates/utopia-server/src/rdf.rs
@@ -481,12 +481,12 @@ pub fn emit_fact(
}
// 现行三元组:**仍被持有,且现在仍成立**。区间已闭合或已撤回的不写这一条,
- // 否则一个忽略具体化的消费者会读到「张三现在还管着那个项目」
+ // 否则一个忽略具体化的消费者会读到「张三现在还管着那个项目」。
+ // 「现在成立」按读出来的区间判(0022):没起点的从最早证据起,结束了不知哪天
+ // 的到说出它的那份文档为止。规则在 world_axis 里,这里只看投影出来的两端
let held = f.invalidated_at.is_none();
- let ended =
- f.valid_to.is_some_and(|t| t <= now) || f.valid_to_precision.as_deref() == Some("unknown");
- let started = f.valid_from.is_none_or(|t| t <= now);
- if held && !ended && started {
+ let holds_now = f.holds_from.is_some_and(|t| t <= now) && f.holds_to.is_none_or(|t| t > now);
+ if held && holds_now {
if let (Some(p), Some(o)) = (&predicate, &object) {
sink.triple(TripleRef::new(subject.as_ref(), p.as_ref(), o.as_ref()))?;
}
@@ -669,6 +669,9 @@ mod tests {
valid_from_precision: None,
valid_to: None,
valid_to_precision: None,
+ // 读出来的区间(0022):没起点就从锚点起,这里让它与记下的时刻同一天
+ holds_from: Some(at("2026-01-01T00:00:00Z")),
+ holds_to: None,
recorded_at: at("2026-01-01T00:00:00Z"),
invalidated_at: None,
confidence: 0.9,
@@ -801,6 +804,9 @@ mod tests {
closed.valid_from_precision = Some("day".into());
closed.valid_to = Some(at("2024-07-01T00:00:00Z"));
closed.valid_to_precision = Some("day".into());
+ // 读出来的区间随原文(0022):两端都给了,就是它们
+ closed.holds_from = Some(at("2023-01-01T00:00:00Z"));
+ closed.holds_to = Some(at("2024-07-01T00:00:00Z"));
let quads = export(Format::Turtle, |sink, names, vocab| {
emit_fact(sink, names, vocab, &closed, at("2026-06-01T00:00:00Z")).unwrap();
});
@@ -846,6 +852,8 @@ mod tests {
let mut ended = fact(5);
ended.valid_to = None;
ended.valid_to_precision = Some("unknown".into());
+ // 结束了不知哪天:读出来的终点是锚点(说出它的那份文档的日期),SQL 就这么投影
+ ended.holds_to = ended.holds_from;
let quads = export(Format::Turtle, |sink, names, vocab| {
emit_fact(sink, names, vocab, &ended, at("2026-06-01T00:00:00Z")).unwrap();
});
diff --git a/crates/utopia-store/src/export.rs b/crates/utopia-store/src/export.rs
index ab12690e..762dbbad 100644
--- a/crates/utopia-store/src/export.rs
+++ b/crates/utopia-store/src/export.rs
@@ -71,6 +71,9 @@ pub struct ExportFact {
pub valid_from_precision: Option<String>,
pub valid_to: Option<DateTime<Utc>>,
pub valid_to_precision: Option<String>,
+ /// 读出来的区间(0022):「现在仍成立」那条三元组按它判,不再自己解释 NULL
+ pub holds_from: Option<DateTime<Utc>>,
+ pub holds_to: Option<DateTime<Utc>>,
pub recorded_at: DateTime<Utc>,
pub invalidated_at: Option<DateTime<Utc>>,
pub confidence: f32,
@@ -173,22 +176,25 @@ pub async fn facts_page(
kb_id: Uuid,
after: Option<Uuid>,
) -> AppResult<Vec<ExportFact>> {
- Ok(sqlx::query_as(
+ Ok(sqlx::query_as(&format!(
"SELECT f.id, f.subject_id, f.predicate_id,
fact_surface_predicate(f.id) AS surface_predicate,
f.object_id, f.object_value,
f.valid_from, f.valid_from_precision, f.valid_to, f.valid_to_precision,
+ {holds_from} AS holds_from, {holds_to} AS holds_to,
f.recorded_at, f.invalidated_at, f.confidence, f.supersedes,
COALESCE(ARRAY(SELECT DISTINCT e.document_id FROM fact_evidence e
- WHERE e.fact_id = f.id AND e.document_id IS NOT NULL), '{}')
+ WHERE e.fact_id = f.id AND e.document_id IS NOT NULL), '{{}}')
AS documents,
COALESCE(ARRAY(SELECT e.quote FROM fact_evidence e
WHERE e.fact_id = f.id AND e.quote IS NOT NULL
- ORDER BY e.chunk_id), '{}') AS quotes
+ ORDER BY e.chunk_id), '{{}}') AS quotes
FROM facts f
WHERE f.kb_id = $1 AND f.id > COALESCE($2, '00000000-0000-0000-0000-000000000000'::uuid)
ORDER BY f.id LIMIT $3",
- )
+ holds_from = crate::world_axis::facts_holds_from("f"),
+ holds_to = crate::world_axis::facts_holds_to("f"),
+ ))
.bind(kb_id)
.bind(after)
.bind(PAGE)
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs
index c2a15fd7..1fb1e030 100644
--- a/crates/utopia-store/src/graph.rs
+++ b/crates/utopia-store/src/graph.rs
@@ -14,6 +14,7 @@ type FactSpanRow = (
Uuid,
Option<chrono::DateTime<chrono::Utc>>,
Option<chrono::DateTime<chrono::Utc>>,
+ Option<String>,
);
/// 采纳时旧事实的去向(`fact_adoptions.mode`):新写一行取代它。
@@ -135,6 +136,11 @@ pub struct Validity<'a> {
pub from_precision: Option<&'a str>,
pub to: Option<chrono::DateTime<chrono::Utc>>,
pub to_precision: Option<&'a str>,
+ /// 这次观察的证据是哪一天的——文档的日期(0022)。`None` 即此刻:人此刻写下
+ /// 的事实,人就是证据。落库成 `attested_at`;同一断言再被观察到时只往早挪。
+ /// 没有起点的事实从它起成立,结束了不知哪天的到它为止——**它不是起点**,所以
+ /// 不写进 `from`(0003 拒绝过把文档日期填进日期列)
+ pub attested_at: Option<chrono::DateTime<chrono::Utc>>,
}
/// `valid_to_precision` 表示「结束了,但不知道是哪天」。
@@ -151,9 +157,16 @@ impl<'a> Validity<'a> {
from_precision,
to: None,
to_precision: None,
+ attested_at: None,
}
}
+ /// 这次观察出自哪一天的文档。
+ pub fn attested(mut self, at: Option<chrono::DateTime<chrono::Utc>>) -> Self {
+ self.attested_at = at;
+ self
+ }
+
/// 原文说它结束了,但没说哪天。
pub fn ended_when_unknown(mut self) -> Self {
self.to = None;
@@ -184,12 +197,12 @@ async fn insert_fact_inner(
) -> AppResult<(Uuid, bool)> {
let same_sql = match object {
FactObject::Entity(_) => {
- "SELECT id, valid_from, valid_to FROM facts
+ "SELECT id, valid_from, valid_to, valid_to_precision FROM facts
WHERE kb_id = $1 AND subject_id = $2 AND predicate_id = $3 AND object_id = $4
AND invalidated_at IS NULL"
}
FactObject::Value(_) => {
- "SELECT id, valid_from, valid_to FROM facts
+ "SELECT id, valid_from, valid_to, valid_to_precision FROM facts
WHERE kb_id = $1 AND subject_id = $2 AND predicate_id = $3 AND object_value = $4
AND object_id IS NULL AND invalidated_at IS NULL"
}
@@ -203,25 +216,62 @@ async fn insert_fact_inner(
FactObject::Value(v) => q.bind(v),
};
let same: Vec<FactSpanRow> = q.fetch_all(pool).await?;
+ // 「结束了,不知哪天」的观察撞上同断言**带起点的开放行**(0022):关上它。
+ // 不并进去——并进去等于把「它结束了」这唯一带来的信息丢掉(同 valid_from 那条
+ // 精确重复的路会这么干);也不另立一行——另立一行让两条各说各话,开放的那条
+ // 照旧被读成「至今仍是」(#345 的那道题正是这样挂的)。
+ // 修正走 supersede:旧行作废,新行终点仍空、精度 'unknown',锚在说出结束的那份
+ // 文档上——读出来就是「到它为止」。只关有起点的:两端都不知道的行一个锚点装不下
+ // 两头,那一半还是开问题
+ if validity.to.is_none() && validity.to_precision == Some(ENDED_UNKNOWN) {
+ let open_dated = same
+ .iter()
+ .filter(|(_, vf, vt, vtp)| {
+ vf.is_some()
+ && vt.is_none()
+ && vtp.is_none()
+ && validity.from.is_none_or(|f| Some(f) == *vf)
+ })
+ .max_by_key(|(_, vf, _, _)| *vf);
+ if let Some((open, _, _, _)) = open_dated {
+ if let Some(closed) =
+ crate::temporal::close_with_unknown_end(pool, *open, validity.attested_at).await?
+ {
+ return Ok((closed, true));
+ }
+ }
+ // 已经关上的(结束了不知哪天)再听到一次「结束了」:同一件事,复用那一行。
+ // 锚点只往早挪——更早的文档说它结束了,它就结束得更早
+ if let Some((ended, _, _, _)) = same.iter().find(|(_, vf, vt, vtp)| {
+ vt.is_none()
+ && vtp.as_deref() == Some(ENDED_UNKNOWN)
+ && validity.from.is_none_or(|f| Some(f) == *vf)
+ }) {
+ attest_earlier(pool, *ended, validity.attested_at).await?;
+ return Ok((*ended, false));
+ }
+ }
// 精确重复:同 valid_from → 复用
- if let Some((existing, _, _)) = same.iter().find(|(_, vf, _)| *vf == validity.from) {
+ if let Some((existing, _, _, _)) = same.iter().find(|(_, vf, _, _)| *vf == validity.from) {
+ attest_earlier(pool, *existing, validity.attested_at).await?;
return Ok((*existing, false));
}
// 弱化陈述:新观察无时间,同断言已有开放行 → 并入(取起点最新的开放行)
if validity.from.is_none() && !validity.has_ended() {
- if let Some((existing, _, _)) = same
+ if let Some((existing, _, _, _)) = same
.iter()
- .filter(|(_, _, vt)| vt.is_none())
- .max_by_key(|(_, vf, _)| *vf)
+ .filter(|(_, _, vt, _)| vt.is_none())
+ .max_by_key(|(_, vf, _, _)| *vf)
{
+ attest_earlier(pool, *existing, validity.attested_at).await?;
return Ok((*existing, false));
}
}
// 时间精化候选:已有无时无终的裸行,本次观察带了起点 → 落库后作废裸行并链上
let refine_target = if validity.from.is_some() {
same.iter()
- .find(|(_, vf, vt)| vf.is_none() && vt.is_none())
- .map(|(id, _, _)| *id)
+ .find(|(_, vf, vt, _)| vf.is_none() && vt.is_none())
+ .map(|(id, _, _, _)| *id)
} else {
None
};
@@ -231,14 +281,14 @@ async fn insert_fact_inner(
FactObject::Entity(_) => {
"INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id,
valid_from, valid_from_precision,
- valid_to, valid_to_precision, confidence)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)"
+ valid_to, valid_to_precision, confidence, attested_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, COALESCE($11, now()))"
}
FactObject::Value(_) => {
"INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_value,
valid_from, valid_from_precision,
- valid_to, valid_to_precision, confidence)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)"
+ valid_to, valid_to_precision, confidence, attested_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, COALESCE($11, now()))"
}
};
let mut ins = sqlx::query(insert_sql)
@@ -255,6 +305,7 @@ async fn insert_fact_inner(
.bind(validity.to)
.bind(validity.to_precision)
.bind(confidence)
+ .bind(validity.attested_at)
.execute(pool)
.await?;
@@ -284,6 +335,24 @@ async fn insert_fact_inner(
Ok((id, true))
}
+/// 同一断言又被观察到一次:锚点只往早挪(0022)。更早的文档是更早的证据;
+/// 更晚的什么也不改——一条事实从有证据的那一刻起成立,之后再被提到不会把它
+/// 往后推。`None`(此刻)也不动它:此刻不会早于任何已有的证据。
+async fn attest_earlier(
+ pool: &PgPool,
+ fact_id: Uuid,
+ at: Option<chrono::DateTime<chrono::Utc>>,
+) -> AppResult<()> {
+ if let Some(at) = at {
+ sqlx::query("UPDATE facts SET attested_at = least(attested_at, $2) WHERE id = $1")
+ .bind(fact_id)
+ .bind(at)
+ .execute(pool)
+ .await?;
+ }
+ Ok(())
+}
+
/// 字面值宾语的事实(object_value 通道,问数映射首个消费者)。
/// 去重:同 (S,P) 且 object_value 完全相等的 live 事实只存一条。
#[allow(clippy::too_many_arguments)]
@@ -467,7 +536,8 @@ async fn edges_among(
COALESCE(r.label, fact_surface_predicate(f.id)) AS label,
r.id IS NULL AS inferred, FALSE AS derived, NULL::text AS rule,
ARRAY[]::uuid[] AS premises,
- f.valid_from, f.valid_to, f.confidence,
+ f.valid_from, f.valid_to,
+ {holds_from} AS holds_from, {holds_to} AS holds_to, f.confidence,
(EXISTS (SELECT 1 FROM axiom_violations v
WHERE {violation_open}
AND (v.left_fact = f.id
@@ -480,24 +550,21 @@ async fn edges_among(
FROM facts f LEFT JOIN relation_types r ON r.id = f.predicate_id
WHERE f.kb_id = $1 AND {facts_held} AND f.object_id IS NOT NULL
AND {subject} = ANY($2) AND {object} = ANY($2)
- AND ($3::timestamptz IS NULL
- OR ((f.valid_from IS NULL OR f.valid_from <= $3)
- AND (f.valid_to IS NULL OR f.valid_to > $3)))
+ AND {facts_hold}
UNION ALL
SELECT d.id, d.subject_id AS source, d.object_id AS target,
r.key AS predicate, r.label AS label,
FALSE AS inferred, TRUE AS derived, ru.kind AS rule,
ARRAY(SELECT fd.premise_fact_id FROM fact_derivations fd
WHERE fd.derived_fact_id = d.id ORDER BY fd.seq) AS premises,
- d.valid_from, d.valid_to, d.confidence,
+ d.valid_from, d.valid_to,
+ d.valid_from AS holds_from, d.valid_to AS holds_to, d.confidence,
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 {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)
- AND (d.valid_to IS NULL OR d.valid_to > $3)))
+ AND {derived_hold}
UNION ALL
SELECT v.id,
(v.detail->>'subject_id')::uuid AS source,
@@ -507,17 +574,25 @@ async fn edges_among(
v.path AS premises,
(v.detail->>'valid_from')::timestamptz AS valid_from,
(v.detail->>'valid_to')::timestamptz AS valid_to,
+ (v.detail->>'valid_from')::timestamptz AS holds_from,
+ (v.detail->>'valid_to')::timestamptz AS holds_to,
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 {violation_open}
AND (v.detail->>'subject_id')::uuid = ANY($2)
AND (v.detail->>'object_id')::uuid = ANY($2)
- AND ($3::timestamptz IS NULL
- OR (((v.detail->>'valid_from')::timestamptz IS NULL
- OR (v.detail->>'valid_from')::timestamptz <= $3)
- AND ((v.detail->>'valid_to')::timestamptz IS NULL
- OR (v.detail->>'valid_to')::timestamptz > $3)))",
+ AND {ghost_hold}",
+ // 世界轴(0022):三段都从 world_axis 拼,读点上不再手写 NULL 的含义
+ facts_hold = crate::world_axis::facts_hold_at("f", 3),
+ derived_hold = crate::world_axis::derived_hold_at("d", 3),
+ ghost_hold = crate::world_axis::interval_holds_at(
+ "(v.detail->>'valid_from')::timestamptz",
+ "(v.detail->>'valid_to')::timestamptz",
+ 3,
+ ),
+ holds_from = crate::world_axis::facts_holds_from("f"),
+ holds_to = crate::world_axis::facts_holds_to("f"),
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),
@@ -635,6 +710,7 @@ pub async fn entity_detail(
pool: &PgPool,
kb_id: Uuid,
entity_id: Uuid,
+ at: Option<chrono::DateTime<chrono::Utc>>,
as_of: Option<chrono::DateTime<chrono::Utc>>,
) -> AppResult<(GraphNode, Vec<EntityFact>)> {
let node: GraphNode = sqlx::query_as(&format!(
@@ -656,7 +732,8 @@ pub async fn entity_detail(
r.id IS NULL AS inferred, r.temporal,
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,
+ f.valid_from, f.valid_from_precision, f.valid_to, f.valid_to_precision,
+ {holds_from} AS holds_from, {holds_to} AS holds_to, f.confidence,
(SELECT count(*) FROM fact_evidence fe WHERE fe.fact_id = f.id) AS evidence_count,
(EXISTS (SELECT 1 FROM fact_evidence fe WHERE fe.fact_id = f.id)
AND NOT EXISTS (SELECT 1 FROM fact_evidence fe
@@ -689,10 +766,13 @@ 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 {subject} = $2 THEN {object} ELSE {subject} END
- WHERE f.kb_id = $1 AND {facts_held}
+ WHERE f.kb_id = $1 AND {facts_held} AND {facts_hold}
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),
+ facts_hold = crate::world_axis::facts_hold_at("f", 4),
+ holds_from = crate::world_axis::facts_holds_from("f"),
+ holds_to = crate::world_axis::facts_holds_to("f"),
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),
@@ -702,6 +782,7 @@ pub async fn entity_detail(
.bind(kb_id)
.bind(entity_id)
.bind(as_of)
+ .bind(at)
.fetch_all(pool)
.await?;
@@ -1528,10 +1609,12 @@ async fn adopt(
let inserted: Option<(Uuid,)> = sqlx::query_as(
"INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, object_value,
valid_from, valid_from_precision,
- valid_to, valid_to_precision, confidence, supersedes)
+ valid_to, valid_to_precision, confidence, supersedes,
+ attested_at)
SELECT $1, kb_id, $6, $3, $4, $5,
valid_from, valid_from_precision,
- valid_to, valid_to_precision, confidence, id
+ valid_to, valid_to_precision, confidence, id,
+ attested_at
FROM facts WHERE id = $2 AND invalidated_at IS NULL
RETURNING id",
)
diff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rs
index 89a23e0f..e507f18e 100644
--- a/crates/utopia-store/src/lib.rs
+++ b/crates/utopia-store/src/lib.rs
@@ -34,3 +34,4 @@ pub mod temporal;
pub mod test_db;
pub mod tokens;
pub mod workspaces;
+pub mod world_axis;
diff --git a/crates/utopia-store/src/pending.rs b/crates/utopia-store/src/pending.rs
index b4115502..4a406522 100644
--- a/crates/utopia-store/src/pending.rs
+++ b/crates/utopia-store/src/pending.rs
@@ -226,11 +226,22 @@ pub struct Confirmed {
/// 只会补证据、不会落第二条,删行在最后——幂等靡有余悸。
pub async fn confirm(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<Confirmed> {
let v = get(pool, kb_id, id).await?;
+ // 锚点是那句记忆所在文档的日期(0022)——与抽取那条路同一个来源。没起点的
+ // 事实从有证据的那一刻起成立,而证据就是这句话
+ let attested_at: Option<chrono::DateTime<chrono::Utc>> = sqlx::query_scalar(
+ "SELECT d.doc_time FROM chunks c JOIN documents d ON d.id = c.document_id
+ WHERE c.id = $1",
+ )
+ .bind(v.chunk_id)
+ .fetch_optional(pool)
+ .await?
+ .flatten();
let validity = Validity {
from: v.valid_from,
from_precision: v.valid_from_precision.as_deref(),
to: v.valid_to,
to_precision: v.valid_to_precision.as_deref(),
+ attested_at,
};
let (fact_id, created) = match (v.object_id, v.object_value.as_ref()) {
(Some(object_id), _) => {
diff --git a/crates/utopia-store/src/reasoning.rs b/crates/utopia-store/src/reasoning.rs
index 1385fceb..739b723d 100644
--- a/crates/utopia-store/src/reasoning.rs
+++ b/crates/utopia-store/src/reasoning.rs
@@ -1833,21 +1833,22 @@ pub async fn derived_for_entity(
pool: &PgPool,
kb_id: Uuid,
entity_id: Uuid,
+ at: Option<chrono::DateTime<chrono::Utc>>,
) -> AppResult<Vec<DerivedFactView>> {
// **宾语与规则两侧都是 LEFT JOIN。** 表拓宽之后(0021)一条派生的宾语可能
// 是字面值而不是实体,规则可能是业务规则而不是公理——内连接会把这两种
// 结论**静默地**从面板上抹掉,而它们恰恰是最需要解释的那种。
//
// 宾语的显示文本因此有三个来源:实体名、归类结论里的类标签、属性结论的值。
- Ok(sqlx::query_as(
+ Ok(sqlx::query_as(&format!(
"SELECT d.id,
d.subject_id, s.canonical_name AS subject,
d.object_id,
COALESCE(o.canonical_name,
ct.label,
d.object_value ->> 'class',
- d.object_value #>> '{value}',
- d.object_value #>> '{}') AS object,
+ d.object_value #>> '{{value}}',
+ d.object_value #>> '{{}}') AS object,
r.label AS predicate,
COALESCE(ru.kind, 'business') AS rule,
ar.name AS rule_name,
@@ -1857,7 +1858,7 @@ pub async fn derived_for_entity(
ps.canonical_name || ' · '
|| COALESCE(pr.label, '?') || ' · '
|| COALESCE(po.canonical_name,
- pf.object_value #>> '{value}',
+ pf.object_value #>> '{{value}}',
'?')
ORDER BY fd.seq)
FROM fact_derivations fd
@@ -1877,10 +1878,13 @@ pub async fn derived_for_entity(
LEFT JOIN entity_types ct ON ct.id = ar.conclude_type_id
WHERE d.kb_id = $1 AND d.invalidated_at IS NULL
AND (d.subject_id = $2 OR d.object_id = $2)
+ AND {derived_hold}
ORDER BY d.derived_at DESC",
- )
+ derived_hold = crate::world_axis::derived_hold_at("d", 3),
+ ))
.bind(kb_id)
.bind(entity_id)
+ .bind(at)
.fetch_all(pool)
.await?)
}
diff --git a/crates/utopia-store/src/temporal.rs b/crates/utopia-store/src/temporal.rs
index 0c4b2108..773913b2 100644
--- a/crates/utopia-store/src/temporal.rs
+++ b/crates/utopia-store/src/temporal.rs
@@ -330,9 +330,9 @@ pub async fn close_superseded(
let inserted: Option<(Uuid,)> = sqlx::query_as(
"INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, object_value,
valid_from, valid_from_precision,
- valid_to, valid_to_precision, confidence, supersedes)
+ valid_to, valid_to_precision, confidence, supersedes, attested_at)
SELECT $1, kb_id, subject_id, predicate_id, object_id, object_value,
- valid_from, valid_from_precision, $3, $4, confidence, id
+ valid_from, valid_from_precision, $3, $4, confidence, id, attested_at
FROM facts WHERE id = $2 AND invalidated_at IS NULL
RETURNING id",
)
@@ -356,6 +356,47 @@ pub async fn close_superseded(
Ok(Some(corrected))
}
+/// 作废 + 改写成「结束了,不知哪天」(0022):旧行记 invalidated_at,修正行终点仍是
+/// NULL、精度 'unknown',锚点换成**说出结束的那份文档**——读出来就是「到它为止」
+/// (起点是原文给的,锚点只管结束端)。证据引用随行复制。
+/// 返回修正行 id;`None` = 这条已不是带起点的开放行,没动。
+pub async fn close_with_unknown_end(
+ pool: &PgPool,
+ fact_id: Uuid,
+ attested_at: Option<DateTime<Utc>>,
+) -> AppResult<Option<Uuid>> {
+ let mut tx = pool.begin().await?;
+ let corrected = Uuid::now_v7();
+ let inserted: Option<(Uuid,)> = sqlx::query_as(
+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, object_value,
+ valid_from, valid_from_precision,
+ valid_to, valid_to_precision, confidence, supersedes, attested_at)
+ SELECT $1, kb_id, subject_id, predicate_id, object_id, object_value,
+ valid_from, valid_from_precision, NULL, $3, confidence, id, COALESCE($4, now())
+ FROM facts
+ WHERE id = $2 AND invalidated_at IS NULL
+ AND valid_from IS NOT NULL AND valid_to IS NULL AND valid_to_precision IS NULL
+ RETURNING id",
+ )
+ .bind(corrected)
+ .bind(fact_id)
+ .bind(crate::graph::ENDED_UNKNOWN)
+ .bind(attested_at)
+ .fetch_optional(&mut *tx)
+ .await?;
+ if inserted.is_none() {
+ tx.rollback().await?;
+ return Ok(None);
+ }
+ sqlx::query("UPDATE facts SET invalidated_at = now() WHERE id = $1")
+ .bind(fact_id)
+ .execute(&mut *tx)
+ .await?;
+ copy_evidence(&mut tx, fact_id, corrected).await?;
+ tx.commit().await?;
+ Ok(Some(corrected))
+}
+
/// 证据引用随修正行复制。表层谓词一起搬:纠正的是时间区间,不是原文说了什么。
async fn copy_evidence(
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
@@ -396,9 +437,9 @@ pub async fn correct_interval(
let inserted: Option<(Uuid,)> = sqlx::query_as(
"INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, object_value,
valid_from, valid_from_precision,
- valid_to, valid_to_precision, confidence, supersedes)
+ valid_to, valid_to_precision, confidence, supersedes, attested_at)
SELECT $1, kb_id, subject_id, predicate_id, object_id, object_value,
- $3, $4, $5, $6, confidence, id
+ $3, $4, $5, $6, confidence, id, attested_at
FROM facts WHERE id = $2 AND invalidated_at IS NULL
RETURNING id",
)
diff --git a/crates/utopia-store/src/world_axis.rs b/crates/utopia-store/src/world_axis.rs
new file mode 100644
index 00000000..831fa7aa
--- /dev/null
+++ b/crates/utopia-store/src/world_axis.rs
@@ -0,0 +1,65 @@
+//! 世界轴谓词(0022):`holds_at(T)`——**T 时刻哪些事实成立**。
+//!
+//! 写入侧早就分得清「仍在持续」与「结束了,不知哪天」,也从不替原文编一个起点。
+//! 读出侧却把两者都读回「随时成立」:`valid_from IS NULL` 被读成自古如此,
+//! `valid_to IS NULL` 不看旁边的精度就读成至今仍是。问一个证据出现之前的时刻,
+//! 或一个原文说已结束、只是没给日期的时刻,图都会理直气壮地回答——引的恰恰是
+//! 那条说它不该成立的行(#345、#352)。
+//!
+//! **谓词只在这里拼**,理由与 `record_axis` 相同:散在每个读点的防御,漏一处就
+//! 无声无息。前端也不再自己算一遍——边和事实带着 `holds_from` / `holds_to`
+//! (按这里同一套表达式投影出来的「读出来的区间」),滑杆只按它们过滤。
+//!
+//! 未知的一端**读到证据为止**:`attested_at` 是这一行的各次观察里最早那份文档的
+//! 日期。没有起点 → 从它起成立;结束了不知哪天 → 到它为止。两端的不对称是故意
+//! 的:开放的结束端仍读作「直到有人说它结束」——结束会以记录的形式到来(后面的
+//! 文档、人的修正),把行关上;而缺失的起点没有这样的修正者,不会有谁来说
+//! 「2023 年它还没开始」。所以事实从有证据的那一刻起成立,之前的诚实答案是没有。
+//!
+//! `at` 为 NULL 在世界轴上是**每一刻**(画布画的是历史,滑杆负责收窄),与记录轴
+//! 的「NULL 即现在」不同:没有人持有一个晚于此刻的信念,而没有时刻的图是全部
+//! 时间的图。
+
+/// `facts`:读出来的下界——原文给了起点用起点,否则从最早的证据起。
+pub fn facts_holds_from(alias: &str) -> String {
+ format!("COALESCE({alias}.valid_from, {alias}.attested_at)")
+}
+
+/// `facts`:读出来的上界——原文给了终点用终点;说结束了但不知哪天,到最早说出它
+/// 的那份文档为止;否则开放(NULL)。
+pub fn facts_holds_to(alias: &str) -> String {
+ format!(
+ "CASE WHEN {alias}.valid_to IS NOT NULL THEN {alias}.valid_to \
+ WHEN {alias}.valid_to_precision = 'unknown' THEN {alias}.attested_at END"
+ )
+}
+
+/// `facts`:断言在 T 时刻成立。`$param` 为 NULL 即不过滤。
+pub fn facts_hold_at(alias: &str, param: usize) -> String {
+ format!(
+ "(${param}::timestamptz IS NULL \
+ OR ({from} <= ${param} AND ({to} IS NULL OR {to} > ${param})))",
+ from = facts_holds_from(alias),
+ to = facts_holds_to(alias),
+ )
+}
+
+/// 纯粹的区间包含,NULL 一端即开放。派生行与幽灵边(0017 §3,区间在 `detail` 里)
+/// 都用它——它们的两端不是原文说的,是引擎按前提算出来的。
+pub fn interval_holds_at(from: &str, to: &str, param: usize) -> String {
+ format!(
+ "(${param}::timestamptz IS NULL \
+ OR (({from} IS NULL OR {from} <= ${param}) AND ({to} IS NULL OR {to} > ${param})))"
+ )
+}
+
+/// `derived_facts`:派生在 T 时刻成立。两端由求值器按前提**读出来的**区间求交写入
+/// (0022 第 4 条,第二刀),所以这里是纯粹的包含。第一刀里派生行仍带着前提原样的
+/// NULL 起点,那一半随第二刀补上。
+pub fn derived_hold_at(alias: &str, param: usize) -> String {
+ interval_holds_at(
+ &format!("{alias}.valid_from"),
+ &format!("{alias}.valid_to"),
+ param,
+ )
+}
diff --git a/crates/utopia-store/tests/a_contradiction_points_upstream.rs b/crates/utopia-store/tests/a_contradiction_points_upstream.rs
index cb427a90..9ab4af5f 100644
--- a/crates/utopia-store/tests/a_contradiction_points_upstream.rs
+++ b/crates/utopia-store/tests/a_contradiction_points_upstream.rs
@@ -226,7 +226,8 @@ async fn a_contradiction_points_upstream() -> anyhow::Result<()> {
// 争议在它坐的地方可见(0017 §3):面板行挂 contested,图上有一条幽灵边,
// 「没落地的」一档有一行,它的证明链读得出前提
- let (_, facts) = utopia_store::graph::entity_detail(&pool, f.kb, f.mira, None).await?;
+ let (_, facts) =
+ utopia_store::graph::entity_detail(&pool, f.kb, f.mira, None, None).await?;
let hit = facts
.iter()
.find(|x| x.id == old)
diff --git a/crates/utopia-store/tests/a_fact_awaits_a_nod.rs b/crates/utopia-store/tests/a_fact_awaits_a_nod.rs
index e91ea22f..a5c27c05 100644
--- a/crates/utopia-store/tests/a_fact_awaits_a_nod.rs
+++ b/crates/utopia-store/tests/a_fact_awaits_a_nod.rs
@@ -118,6 +118,7 @@ async fn a_remembered_fact_waits_for_a_nod() -> anyhow::Result<()> {
from_precision: Some("day"),
to: None,
to_precision: None,
+ attested_at: None,
},
confidence: 0.9,
chunk_id: f.chunk,
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.rs
index edd8da5d..d923ddd2 100644
--- 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.rs
@@ -166,7 +166,8 @@ async fn facts_of(
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 (_, facts) =
+ utopia_store::graph::entity_detail(pool, kb, entity, None, as_of.map(t)).await?;
let mut ids: Vec<Uuid> = facts.iter().map(|f| f.id).collect();
ids.sort();
Ok(ids)
diff --git a/crates/utopia-store/tests/a_proof_reaches_the_sentence.rs b/crates/utopia-store/tests/a_proof_reaches_the_sentence.rs
index ddb46080..f2a780e6 100644
--- a/crates/utopia-store/tests/a_proof_reaches_the_sentence.rs
+++ b/crates/utopia-store/tests/a_proof_reaches_the_sentence.rs
@@ -186,7 +186,7 @@ async fn a_proof_reaches_the_sentence() -> anyhow::Result<()> {
reasoning::materialize(&pool, f.kb).await?;
let derived: Vec<utopia_core::models::DerivedFactView> =
- reasoning::derived_for_entity(&pool, f.kb, f.a).await?;
+ reasoning::derived_for_entity(&pool, f.kb, f.a, None).await?;
let ac = derived
.iter()
.find(|d| d.subject_id == f.a && d.object_id == Some(f.c))
diff --git a/crates/utopia-store/tests/a_wrong_time_can_be_corrected.rs b/crates/utopia-store/tests/a_wrong_time_can_be_corrected.rs
index d6785c38..d2abb215 100644
--- a/crates/utopia-store/tests/a_wrong_time_can_be_corrected.rs
+++ b/crates/utopia-store/tests/a_wrong_time_can_be_corrected.rs
@@ -255,6 +255,7 @@ async fn an_end_that_was_never_there_can_be_taken_back() -> anyhow::Result<()> {
from_precision: Some("day"),
to: Some(t("2024-01-01T00:00:00Z")),
to_precision: Some("year"),
+ attested_at: None,
},
)
.await?
diff --git a/crates/utopia-store/tests/an_unknown_date_is_not_an_open_one.rs b/crates/utopia-store/tests/an_unknown_date_is_not_an_open_one.rs
new file mode 100644
index 00000000..7c457beb
--- /dev/null
+++ b/crates/utopia-store/tests/an_unknown_date_is_not_an_open_one.rs
@@ -0,0 +1,525 @@
+//! 未知的日期不是开放的日期(0022 / #345 / #352),打在真库上。
+//!
+//! 为什么非要连库:这道防御整个活在 SQL 字符串里(`world_axis`),与 0019 的记录轴
+//! 同一种危险——`cargo check` 看不见一个写反的 CASE,漏掉一处读点也没有人报错。
+//!
+//! 表里的四种行,两个方向都断言:
+//! - 没有起点的事实,在它的文档日期**之前不出现**、**当天出现**(读成「自古如此」
+//! 会让 2023 年 1 月看见一张 2024 年的调薪单)
+//! - 结束了不知哪天的事实,在它的文档日期**之前出现**、**当天起不出现**(读成
+//! 「至今仍是」会让 2026 年还挂着一个原文说已经不担任的头衔)
+//! - 原文给了两端的事实,两端照旧——这条改动不碰有日期的行
+//! - 两端都不知道的行,**任何时刻都不成立**,但实体的时间线上仍列着它
+//!
+//! 再钉两条写入侧的约定:同一断言被更早的文档再观察到一次,锚点往早挪;
+//! 修正行从被替代的行继承锚点,而不是重新锚在修正的那一刻。
+//!
+//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。
+
+use std::collections::HashSet;
+
+use sqlx::PgPool;
+use utopia_store::graph::Validity;
+use uuid::Uuid;
+
+/// 关上之后那一行:起点、终点、终点精度、supersedes、锚点
+type ClosedRow = (
+ Option<chrono::DateTime<chrono::Utc>>,
+ Option<chrono::DateTime<chrono::Utc>>,
+ Option<String>,
+ Option<Uuid>,
+ chrono::DateTime<chrono::Utc>,
+);
+
+fn t(s: &str) -> chrono::DateTime<chrono::Utc> {
+ s.parse().unwrap()
+}
+
+struct Fixture {
+ org: Uuid,
+ kb: Uuid,
+ lin: Uuid,
+ meridian: Uuid,
+ platform: Uuid,
+ staff_engineer: Uuid,
+ lead: Uuid,
+ works_for: Uuid,
+ approved: Uuid,
+ holds_title: Uuid,
+}
+
+async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {
+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let (person, organization, title) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let (lin, meridian, platform) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ let (staff_engineer, lead) = (Uuid::now_v7(), Uuid::now_v7());
+ let (works_for, approved, holds_title) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'unknown-date-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'unknown-date-test')")
+ .bind(ws)
+ .bind(org)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'unknown-date-test')",
+ )
+ .bind(kb)
+ .bind(ws)
+ .execute(pool)
+ .await?;
+ for (id, key, label) in [
+ (person, "person", "Person"),
+ (organization, "organization", "Organization"),
+ (title, "title", "Title"),
+ ] {
+ 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 [
+ (works_for, "works_for", "works for"),
+ (approved, "approved", "approved"),
+ (holds_title, "holds_title", "holds title"),
+ ] {
+ 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, ty, name) in [
+ (lin, person, "Lin Zhao"),
+ (meridian, organization, "Meridian Systems"),
+ (platform, organization, "Platform Group"),
+ (staff_engineer, title, "Staff Engineer"),
+ (lead, title, "Tech Lead"),
+ ] {
+ sqlx::query(
+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",
+ )
+ .bind(id)
+ .bind(kb)
+ .bind(ty)
+ .bind(name)
+ .execute(pool)
+ .await?;
+ }
+ Ok(Fixture {
+ org,
+ kb,
+ lin,
+ meridian,
+ platform,
+ staff_engineer,
+ lead,
+ works_for,
+ approved,
+ holds_title,
+ })
+}
+
+async fn fact(
+ pool: &PgPool,
+ f: &Fixture,
+ subject: Uuid,
+ predicate: Uuid,
+ object: Uuid,
+ validity: Validity<'_>,
+) -> anyhow::Result<(Uuid, bool)> {
+ Ok(utopia_store::graph::insert_fact(
+ pool,
+ f.kb,
+ subject,
+ Some(predicate),
+ object,
+ validity,
+ 0.9,
+ )
+ .await?)
+}
+
+/// T 时刻林昭一跳邻域里的边(按事实 id)。`None` = 每一刻。
+async fn edges_at(pool: &PgPool, f: &Fixture, at: Option<&str>) -> anyhow::Result<HashSet<Uuid>> {
+ let (_, edges) =
+ utopia_store::graph::neighborhood(pool, f.kb, f.lin, 1, at.map(t), None).await?;
+ Ok(edges.into_iter().map(|e| e.id).collect())
+}
+
+async fn attested_at(pool: &PgPool, id: Uuid) -> anyhow::Result<chrono::DateTime<chrono::Utc>> {
+ Ok(
+ sqlx::query_scalar("SELECT attested_at FROM facts WHERE id = $1")
+ .bind(id)
+ .fetch_one(pool)
+ .await?,
+ )
+}
+
+#[tokio::test]
+async fn an_unknown_bound_reaches_as_far_as_the_evidence() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let run = async {
+ // A:offer letter,2023-06-01 起,仍在继续——两端原文都给了(起点)
+ let (a, _) = fact(
+ &pool,
+ &f,
+ f.lin,
+ f.works_for,
+ f.meridian,
+ Validity::starting(Some(t("2023-06-01T00:00:00Z")), Some("day"))
+ .attested(Some(t("2023-06-01T00:00:00Z"))),
+ )
+ .await?;
+ // B:2024-02-20 的调薪单说「加薪由平台组批准」——没有起点
+ let (b, _) = fact(
+ &pool,
+ &f,
+ f.platform,
+ f.approved,
+ f.lin,
+ Validity::default().attested(Some(t("2024-02-20T00:00:00Z"))),
+ )
+ .await?;
+ // C:2025-10-15 的角色说明说「不再担任 Staff Engineer,日期未记录」——两端都不知道
+ let (c, _) = fact(
+ &pool,
+ &f,
+ f.lin,
+ f.holds_title,
+ f.staff_engineer,
+ Validity::default()
+ .ended_when_unknown()
+ .attested(Some(t("2025-10-15T00:00:00Z"))),
+ )
+ .await?;
+ // D:2023-06-01 起任 Tech Lead,同一份 2025-10-15 的说明说已不再担任——起点有,终点不知哪天
+ let (d, _) = fact(
+ &pool,
+ &f,
+ f.lin,
+ f.holds_title,
+ f.lead,
+ Validity::starting(Some(t("2023-06-01T00:00:00Z")), Some("day"))
+ .ended_when_unknown()
+ .attested(Some(t("2025-10-15T00:00:00Z"))),
+ )
+ .await?;
+
+ // 2023 年 1 月:什么都还没有。B 的证据在 2024 年——「自古如此」读法会让它出现
+ let jan_2023 = edges_at(&pool, &f, Some("2023-01-01T00:00:00Z")).await?;
+ assert!(
+ jan_2023.is_empty(),
+ "证据出现之前的时刻,一条也不该成立:{jan_2023:?}"
+ );
+
+ // 2023-06-01:有起点的两条当天起成立;B 还没有证据;C 从不成立
+ let jun_2023 = edges_at(&pool, &f, Some("2023-06-01T00:00:00Z")).await?;
+ assert_eq!(jun_2023, HashSet::from([a, d]));
+
+ // 2024-02-20:B 从它的文档日期起成立
+ let feb_2024 = edges_at(&pool, &f, Some("2024-02-20T00:00:00Z")).await?;
+ assert_eq!(feb_2024, HashSet::from([a, b, d]));
+ let day_before = edges_at(&pool, &f, Some("2024-02-19T00:00:00Z")).await?;
+ assert!(
+ !day_before.contains(&b),
+ "文档日期前一天,没起点的事实还不成立"
+ );
+
+ // 2025-10-15:D 到说出它结束的那份文档为止;前一天还在
+ let oct_2025 = edges_at(&pool, &f, Some("2025-10-15T00:00:00Z")).await?;
+ assert_eq!(
+ oct_2025,
+ HashSet::from([a, b]),
+ "结束了不知哪天的,到它的文档日期为止"
+ );
+ let eve = edges_at(&pool, &f, Some("2025-10-14T00:00:00Z")).await?;
+ assert!(
+ eve.contains(&d),
+ "文档日期前一天它还成立——保守包含到证据为止"
+ );
+
+ // 2026-01-01:#345 那道题——头衔不该还挂着
+ let jan_2026 = edges_at(&pool, &f, Some("2026-01-01T00:00:00Z")).await?;
+ assert!(
+ !jan_2026.contains(&c) && !jan_2026.contains(&d),
+ "原文说结束了,就不该在之后成立"
+ );
+ assert_eq!(jan_2026, HashSet::from([a, b]));
+
+ // 两端都不知道的 C:任何时刻都不成立;但不给时刻时它在(画布画的是历史)
+ let every = edges_at(&pool, &f, None).await?;
+ assert_eq!(
+ every,
+ HashSet::from([a, b, c, d]),
+ "at = None 是每一刻,四条都在"
+ );
+
+ // 边上带着读出来的区间,前端按它过滤,不自己解释 NULL
+ let (_, edges) =
+ utopia_store::graph::neighborhood(&pool, f.kb, f.lin, 1, None, None).await?;
+ let by_id = |id: Uuid| edges.iter().find(|e| e.id == id).unwrap();
+ assert_eq!(by_id(b).holds_from, Some(t("2024-02-20T00:00:00Z")));
+ assert_eq!(by_id(b).holds_to, None);
+ assert_eq!(by_id(d).holds_from, Some(t("2023-06-01T00:00:00Z")));
+ assert_eq!(
+ by_id(d).holds_to,
+ Some(t("2025-10-15T00:00:00Z")),
+ "结束端读到文档日期"
+ );
+ assert_eq!(by_id(a).holds_to, None, "仍在继续的还是开放的");
+ assert_eq!(by_id(c).holds_from, Some(t("2025-10-15T00:00:00Z")));
+ assert_eq!(
+ by_id(c).holds_to,
+ Some(t("2025-10-15T00:00:00Z")),
+ "两端都不知道:区间为空"
+ );
+
+ // 实体面板:不给时刻时整条时间线都在(C 也列着,标着结束);给时刻时按规则筛
+ let (_, all) = utopia_store::graph::entity_detail(&pool, f.kb, f.lin, None, None).await?;
+ assert_eq!(all.len(), 4);
+ let (_, now_ish) = utopia_store::graph::entity_detail(
+ &pool,
+ f.kb,
+ f.lin,
+ Some(t("2026-01-01T00:00:00Z")),
+ None,
+ )
+ .await?;
+ let ids: HashSet<Uuid> = now_ish.iter().map(|x| x.id).collect();
+ assert_eq!(ids, HashSet::from([a, b]));
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
+ .bind(f.kb)
+ .execute(&pool)
+ .await?;
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await?;
+ run
+}
+
+/// 锚点只往早挪:更早的文档是更早的证据。修正行继承锚点:改区间是重述同一份证据。
+#[tokio::test]
+async fn the_anchor_moves_earlier_and_is_inherited() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let run = async {
+ let (b, created) = fact(
+ &pool,
+ &f,
+ f.platform,
+ f.approved,
+ f.lin,
+ Validity::default().attested(Some(t("2024-02-20T00:00:00Z"))),
+ )
+ .await?;
+ assert!(created);
+ assert!(!edges_at(&pool, &f, Some("2023-12-01T00:00:00Z"))
+ .await?
+ .contains(&b));
+
+ // 同一断言,出自一份更早的文档(回填语料乱序进来是常态):同一行,锚点前移
+ let (again, created) = fact(
+ &pool,
+ &f,
+ f.platform,
+ f.approved,
+ f.lin,
+ Validity::default().attested(Some(t("2023-12-01T00:00:00Z"))),
+ )
+ .await?;
+ assert_eq!(again, b, "同一断言复用同一行");
+ assert!(!created);
+ assert_eq!(attested_at(&pool, b).await?, t("2023-12-01T00:00:00Z"));
+ assert!(edges_at(&pool, &f, Some("2023-12-01T00:00:00Z"))
+ .await?
+ .contains(&b));
+
+ // 更晚的文档再提一次:什么也不动
+ fact(
+ &pool,
+ &f,
+ f.platform,
+ f.approved,
+ f.lin,
+ Validity::default().attested(Some(t("2025-01-01T00:00:00Z"))),
+ )
+ .await?;
+ assert_eq!(
+ attested_at(&pool, b).await?,
+ t("2023-12-01T00:00:00Z"),
+ "只往早挪"
+ );
+
+ // 人给它一个结束:修正行继承锚点,而不是锚在修正的此刻
+ let corrected = utopia_store::temporal::correct_interval(
+ &pool,
+ b,
+ Validity {
+ from: None,
+ from_precision: None,
+ to: Some(t("2025-06-01T00:00:00Z")),
+ to_precision: Some("day"),
+ attested_at: None,
+ },
+ )
+ .await?
+ .expect("改得动");
+ assert_eq!(
+ attested_at(&pool, corrected).await?,
+ t("2023-12-01T00:00:00Z")
+ );
+ let (_, edges) =
+ utopia_store::graph::neighborhood(&pool, f.kb, f.lin, 1, None, None).await?;
+ let row = edges.iter().find(|e| e.id == corrected).unwrap();
+ assert_eq!(row.holds_from, Some(t("2023-12-01T00:00:00Z")));
+ assert_eq!(
+ row.holds_to,
+ Some(t("2025-06-01T00:00:00Z")),
+ "原文给了终点就用终点"
+ );
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
+ .bind(f.kb)
+ .execute(&pool)
+ .await?;
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await?;
+ run
+}
+
+/// 「不再担任,日期未记录」撞上「2023-06-01 起担任」的开放行:关上它,而不是另立
+/// 一行让两条各说各话。#345 那道题挂的正是这个——结束的那行读对了,开放的那行
+/// 照旧说「至今仍是」。
+#[tokio::test]
+async fn an_ending_without_a_date_closes_the_dated_row_it_ends() -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let f = seed(&pool).await?;
+
+ let run = async {
+ // 2023-06-01 的 offer:Staff Engineer,仍在继续
+ let (open, _) = fact(
+ &pool,
+ &f,
+ f.lin,
+ f.holds_title,
+ f.staff_engineer,
+ Validity::starting(Some(t("2023-06-01T00:00:00Z")), Some("day"))
+ .attested(Some(t("2023-06-01T00:00:00Z"))),
+ )
+ .await?;
+ assert!(edges_at(&pool, &f, Some("2026-01-01T00:00:00Z"))
+ .await?
+ .contains(&open));
+
+ // 2025-10-15 的角色说明:不再担任,日期未记录——同一断言,没起点
+ let (closed, created) = fact(
+ &pool,
+ &f,
+ f.lin,
+ f.holds_title,
+ f.staff_engineer,
+ Validity::default()
+ .ended_when_unknown()
+ .attested(Some(t("2025-10-15T00:00:00Z"))),
+ )
+ .await?;
+ assert!(created, "关上是一条修正行,不是并进去");
+ assert_ne!(closed, open);
+
+ // 旧行作废、修正行链上:起点是原文给的,终点空、精度 unknown,锚在结束的那份文档
+ let (invalidated, supersedes): (Option<chrono::DateTime<chrono::Utc>>, Option<Uuid>) =
+ sqlx::query_as("SELECT invalidated_at, supersedes FROM facts WHERE id = $1")
+ .bind(open)
+ .fetch_one(&pool)
+ .await?;
+ assert!(invalidated.is_some(), "旧行作废,不删");
+ assert!(supersedes.is_none());
+ let row: ClosedRow = sqlx::query_as(
+ "SELECT valid_from, valid_to, valid_to_precision, supersedes, attested_at
+ FROM facts WHERE id = $1",
+ )
+ .bind(closed)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(row.0, Some(t("2023-06-01T00:00:00Z")), "起点照旧");
+ assert_eq!(row.1, None);
+ assert_eq!(row.2.as_deref(), Some("unknown"));
+ assert_eq!(row.3, Some(open), "supersedes 链上");
+ assert_eq!(row.4, t("2025-10-15T00:00:00Z"), "锚在说出结束的那份文档");
+
+ // #345 那道题:2026 年 1 月不该再有 Staff Engineer;2024 年 6 月还有
+ assert!(!edges_at(&pool, &f, Some("2026-01-01T00:00:00Z"))
+ .await?
+ .contains(&closed));
+ assert!(edges_at(&pool, &f, Some("2024-06-01T00:00:00Z"))
+ .await?
+ .contains(&closed));
+ let (_, panel) = utopia_store::graph::entity_detail(
+ &pool,
+ f.kb,
+ f.lin,
+ Some(t("2026-01-01T00:00:00Z")),
+ None,
+ )
+ .await?;
+ assert!(panel.is_empty(), "面板在 2026 年也不再列它:{panel:?}");
+
+ // 同一断言再说一次「结束了」:已经关上的行不再被关,也不另立
+ let (again, created) = fact(
+ &pool,
+ &f,
+ f.lin,
+ f.holds_title,
+ f.staff_engineer,
+ Validity::default()
+ .ended_when_unknown()
+ .attested(Some(t("2025-12-01T00:00:00Z"))),
+ )
+ .await?;
+ assert!(!created, "没有开放行可关,也不是新信息");
+ assert_eq!(again, closed);
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
+ .bind(f.kb)
+ .execute(&pool)
+ .await?;
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(f.org)
+ .execute(&pool)
+ .await?;
+ run
+}
diff --git a/crates/utopia-store/tests/no_predicate_still_shows.rs b/crates/utopia-store/tests/no_predicate_still_shows.rs
index dc7c17e3..4ae2357c 100644
--- a/crates/utopia-store/tests/no_predicate_still_shows.rs
+++ b/crates/utopia-store/tests/no_predicate_still_shows.rs
@@ -193,7 +193,8 @@ 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, None).await?;
+ let (_, facts) =
+ utopia_store::graph::entity_detail(&pool, f.kb, f.subject, None, 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
index 9918e162..3a400e23 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
@@ -245,7 +245,7 @@ async fn the_recording_axis_rewinds_on_every_graph_read() -> anyhow::Result<()>
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))
+ utopia_store::graph::entity_detail(&pool, f.kb, f.zhang, None, as_of.map(t))
.await
.map(|(_, facts)| facts)
}
diff --git a/docs/decisions/0022-an-unknown-date-is-not-an-open-one.md b/docs/decisions/0022-an-unknown-date-is-not-an-open-one.md
index 677ec5a2..88e2153f 100644
--- a/docs/decisions/0022-an-unknown-date-is-not-an-open-one.md
+++ b/docs/decisions/0022-an-unknown-date-is-not-an-open-one.md
@@ -1,6 +1,6 @@
# 0022 · An unknown date is not an open one
-- **Status**: proposed · to be built in two cuts — the predicate, the anchor and every read of asserted facts first (#345, #352), derived rows second
+- **Status**: first cut implemented · `world_axis` beside `record_axis`, `facts.attested_at` set by every writer and backfilled, every server read and both client filters on the read interval, `holds_from` / `holds_to` on edges and entity facts · an undated ending now also **closes** the dated open row it ends (`close_with_unknown_end`), which the first open question below had left to the write side · derived rows still read their stated bounds — the second cut · a bare open row plus an undated ending is #393
- **Written**: 2026-09-06 (conventions in the [README](README.md))
- **Related**: [0003](0003-ontology-growth-loop.md)'s graph migration gave the end of a fact three states and refused to store a document's date as an indeterminate instant; this record keeps that refusal and puts the date in a column that says what it is. [0019](0019-the-second-clock-can-be-rewound.md) put the record-axis predicate in one place (`record_axis`) and kept `at` and `as_of` apart; this record does the same for the world axis. [0017](0017-a-contradiction-points-upstream.md) gave derived rows their own precisions, and [0021](0021-a-rule-reads-attributes-and-concludes-a-type.md)'s evaluator intersects premise intervals — both inherit the rule below. From #345 and #352, both found by the temporal benchmark (#306).
@@ -86,8 +86,8 @@ The slider and a timed question stop returning a fact before its evidence or aft
## Phasing
-1. Schema (`attested_at`, its backfill, the derived CHECK), every writer, `world_axis`, every server read, `holds_from` / `holds_to` on edges and entity facts, the two client filters, the benchmark's two questions un-gapped. One database-backed test carries the table of cases in both directions: a no-start fact absent the day before its document and present on it; an ended-unknown fact present the day before its document and absent from it; a stated interval untouched; the both-unknown row absent at every moment yet listed on the entity.
-2. Derived rows: the evaluator on read intervals, precision-less anchored bounds, and a test that a chain through an ended-unknown premise ends at that premise's document.
+1. Schema (`attested_at` and its backfill), every writer, `world_axis`, every server read, `holds_from` / `holds_to` on edges and entity facts, the two client filters, the benchmark's two questions un-gapped. One database-backed test carries the table of cases in both directions: a no-start fact absent the day before its document and present on it; an ended-unknown fact present the day before its document and absent from it; a stated interval untouched; the both-unknown row absent at every moment yet listed on the entity.
+2. Derived rows: the evaluator on read intervals, precision-less anchored bounds (which is where the derived CHECK loosens — it ships with its first writer, not ahead of it), and a test that a chain through an ended-unknown premise ends at that premise's document.
## Dead ends
@@ -99,7 +99,7 @@ The slider and a timed question stop returning a fact before its evidence or aft
## Open questions
-- **One write path drops an ending.** `insert_fact_inner` reuses a live row with the same stated start as an exact duplicate before it looks at the end; a bare open row (no start, no end) and a new "ended, date unknown" observation with no start are such a pair, so the ending is lost. The `ended_when_unknown` test covers the weak-statement path, not this one. Separate issue.
-- **An ending does not close the dated row it ends.** `reconcile_new_fact` returns early for any fact that has ended, so the "no longer holds" row from #352 sits beside the 2023-06-01 row that still says "holds", and that row still reads as holding today. Whether an ended-unknown observation should close the open row of the same assertion — its precision to `'unknown'`, its anchor to the ending's document — is a write-side decision that would make the both-unknown row rare. Separate issue.
+- **An ending does not close the dated row it ends.** ~~`reconcile_new_fact` returns early for any fact that has ended, so the "no longer holds" row from #352 sits beside the 2023-06-01 row that still says "holds".~~ Settled in the first cut, because the benchmark showed the read rule alone leaves #345's question failing: the ended-unknown row read correctly, and the dated open row beside it went on holding. An undated ending that meets an open row **with a stated start** of the same assertion now closes it — a superseding row with `'unknown'` at the end, anchored on the ending's document, the old row invalidated (`temporal::close_with_unknown_end`). A repeated ending reuses the closed row and only moves its anchor earlier.
+- **A bare open row cannot be closed the same way** (#393). With no stated start the one anchor would have to serve both ends — held from the first note, ended by the second. Today the exact-duplicate path in `insert_fact_inner` merges the ending into the bare row and drops it. Two anchors is the likely answer; it is a schema decision and waits for its own line.
- **Retrieval is untimed.** Vector and full-text recall take `as_of` (0019) but no `at`; a chunk about 2025 answers a question about 2023 and the model is left to notice. Out of scope; noted so the benchmark's chat probe is read with that in mind.
- **Showing the anchor.** Whether the panel should say "attested 2024-02-20" beside a blank start, so a person sees why the slider hides the edge before then. Deferred until the first cut has been looked at.
diff --git a/docs/decisions/README.md b/docs/decisions/README.md
index 55e49b8e..c9ed1e47 100644
--- a/docs/decisions/README.md
+++ b/docs/decisions/README.md
@@ -45,7 +45,7 @@ The test for writing one: if someone (including us) looks at a piece of code in
| 0019 | [The second clock can be rewound](0019-the-second-clock-can-be-rewound.md) | Implemented in three cuts · `held_at` and `as_of` on every graph read (#317), entities' own clock by unwinding `entity_merges` (#337), retrieval as of a moment · the control on the graph page is still open (#307), full-text recall is still "now" only |
| 0020 | [An auditor reads it without us](0020-an-auditor-reads-it-without-us.md) | Implemented · `GET /kbs/{id}/export?format=turtle\|jsonld` streams the base as RDF, `rdf.rs` holds the mapping · SPARQL waits, and the record says why (#308) |
| 0021 | [A rule reads attributes and concludes a type](0021-a-rule-reads-attributes-and-concludes-a-type.md) | Implemented (#359) · `derived_facts` widened to match `facts`, rules authored in `attribute_rules` from the ontology page, evaluated in the materialisation job, explained in the entity panel with their premises · read-only over MCP, writing a rule stays out · no canvas marker, and a conclusion is rewritten rather than edited |
-| 0022 | [An unknown date is not an open one](0022-an-unknown-date-is-not-an-open-one.md) | Proposed · a missing start is read as since-always and a stated-but-undated ending as still-holding, by hand at every read site · one `world_axis` predicate, an `attested_at` anchor from the document's date, derived rows on read intervals · two cuts (#345, #352) |
+| 0022 | [An unknown date is not an open one](0022-an-unknown-date-is-not-an-open-one.md) | First cut implemented · `world_axis` predicate beside `record_axis`, `facts.attested_at` anchors a missing start or an undated end at the document that attests it, every server read and both client filters on the read interval, an undated ending closes the dated row it ends · derived rows on read intervals are the second cut · a bare open row plus an undated ending is #393 |
## Not a decision record
diff --git a/migrations/0030_an_unknown_date_is_not_an_open_one.sql b/migrations/0030_an_unknown_date_is_not_an_open_one.sql
new file mode 100644
index 00000000..9144550d
--- /dev/null
+++ b/migrations/0030_an_unknown_date_is_not_an_open_one.sql
@@ -0,0 +1,29 @@
+-- 0022:未知的日期不是开放的日期。
+--
+-- 写入侧分得清「仍在持续」(valid_to NULL,精度 NULL)与「结束了,不知哪天」
+-- (valid_to NULL,精度 'unknown'),也从不替原文编一个起点。读出侧把两者都读回
+-- 「随时成立」。修法不改这张表上任何一列的含义,而是补一列说清自己是什么:
+--
+-- attested_at:这一行的各次观察里,**最早那份文档的日期**。没有起点的事实从它起
+-- 成立;结束了不知哪天的事实到它为止。它是世界轴上的时刻(文档的日期),不是
+-- recorded_at(我们何时写下——另一根轴,0019):回填的语料一个晚上灌进 2023–2025
+-- 年的文档,按 recorded_at 锚,每条没起点的事实都会出现在 2026 年、而在任何一个
+-- 历史时刻都不出现。
+--
+-- 不把文档日期填进 valid_from / valid_to(0003 的拒绝仍然成立):那两列写的是原文
+-- 说了什么,读它们的人不该先查精度才敢信。
+ALTER TABLE facts ADD COLUMN attested_at TIMESTAMPTZ;
+
+-- 回填:证据里最早的文档日期;没有证据的行(人手录的)按记下的时刻。
+UPDATE facts f
+ SET attested_at = COALESCE(
+ (SELECT min(COALESCE(d.doc_time, d.created_at))
+ FROM fact_evidence fe JOIN documents d ON d.id = fe.document_id
+ WHERE fe.fact_id = f.id),
+ f.recorded_at);
+
+-- 默认 now():人此刻写下的事实,人就是证据。写入路径都显式给值(抽取给文档日期,
+-- 修正行从被替代的行继承),默认值兜住的是测试里直接 INSERT 的行。
+ALTER TABLE facts
+ ALTER COLUMN attested_at SET NOT NULL,
+ ALTER COLUMN attested_at SET DEFAULT now();
diff --git a/scripts/bench/temporal/questions.json b/scripts/bench/temporal/questions.json
index a42c6ae9..2fb584e2 100644
--- a/scripts/bench/temporal/questions.json
+++ b/scripts/bench/temporal/questions.json
@@ -181,7 +181,6 @@
"subject": "Lin Zhao",
"expect": null,
"not": ["Meridian Systems", "Platform Group"],
- "known_gap": true,
"ask": "Who did Lin Zhao work for in January 2023?",
"why": "入职是六月的事。一月的答案应当是空,而不是把开区间当成「一直如此」——`valid_from` 之前不成立,正是双时态存在的理由。第一版只禁 Meridian,账本满分;对话却答出「Platform Group 的 Staff Engineer」——那两条都没有起点(2024 年的调薪单说「加薪由平台组批准」,2025 年的角色说明说「不再担任,日期未记录」),而世界轴把没有起点读成自古就有。见 #352。"
},
@@ -248,7 +247,6 @@
"subject": "Lin Zhao",
"expect": null,
"not": ["Staff Engineer"],
- "known_gap": true,
"ask": "What is Lin Zhao's job title in January 2026?",
"why": "「不再担任,日期不详」是账本专门留的一个状态(valid_to 为空、精度为 unknown)。世界轴按 `valid_to IS NULL` 判活时会把它当成仍然成立——这一题钉住那个口径,修好的那天它自己会翻绿。"
},
diff --git a/web/src/api.ts b/web/src/api.ts
index 958907df..228d46c0 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -754,6 +754,11 @@ export interface GraphEdge {
premises: string[];
valid_from: string | null;
valid_to: string | null;
+ /** **读出来的**区间(0022):没起点的事实从最早的证据起,结束了不知哪天的到说出
+ * 它的那份文档为止。滑杆按这两个过滤;上面那两个是原文说了什么,只用来显示。
+ * 前端不自己解释 NULL——规则只在服务端的 world_axis 里有一份 */
+ holds_from: string | null;
+ holds_to: string | null;
confidence: number;
/** 有争议(0017 §3):有一条 open 的公理违规或时态冲突指着它。整条边画成警戒色 */
contested: boolean;
@@ -778,6 +783,9 @@ export interface EntityFact {
object_value: Record<string, unknown> | null;
valid_from: string | null;
valid_to: string | null;
+ /** 读出来的区间(0022),与 GraphEdge 同义:「此刻成立」按它判 */
+ holds_from: string | null;
+ holds_to: string | null;
valid_from_precision: string | null;
/** year | month | day,外加 unknown = 原文说它结束了但没说哪天 */
valid_to_precision: string | null;
diff --git a/web/src/pages/Graph.tsx b/web/src/pages/Graph.tsx
index 99c6bc41..2437d3d6 100644
--- a/web/src/pages/Graph.tsx
+++ b/web/src/pages/Graph.tsx
@@ -529,12 +529,14 @@ export function Graph() {
const nodes = new Set<string>();
const touched = new Set<string>();
for (const e of d.edges) {
- const vf = e.valid_from ? Date.parse(e.valid_from) : null;
- const vt = e.valid_to ? Date.parse(e.valid_to) : null;
+ // 按**读出来的**区间过滤(0022):没起点的边从最早的证据起才亮,结束了
+ // 不知哪天的到说出它的那份文档就灭。NULL 一端才是开放——这里不再把
+ // 「没有起点」读成「一直都在」
+ const hf = e.holds_from ? Date.parse(e.holds_from) : null;
+ const ht = e.holds_to ? Date.parse(e.holds_to) : null;
touched.add(e.source);
touched.add(e.target);
- const active =
- vf === null ? true : vf <= t && (vt === null || vt > t);
+ const active = (hf === null || hf <= t) && (ht === null || ht > t);
if (active) {
edges.add(e.id);
nodes.add(e.source);
@@ -1810,8 +1812,10 @@ function TimeScrubber({
const { minTs, maxTs, bars, merged, trackW } = useMemo(() => {
const now = Date.now();
+ // 柱子按边**开始成立**的时刻分格(0022):没起点的边从最早证据起算,这样
+ // 滑杆的量程盖得住它亮起来的那一刻,而不是把它排除在直方图之外
const froms = edges
- .map((e) => (e.valid_from ? Date.parse(e.valid_from) : NaN))
+ .map((e) => (e.holds_from ? Date.parse(e.holds_from) : NaN))
.filter((t) => !Number.isNaN(t));
const min = froms.length
? Math.min(...froms)
@@ -2760,10 +2764,11 @@ function EntityPanel({
const { groups, historicalCount } = useMemo(() => {
const all = detail.data?.facts ?? [];
const nowIso = new Date().toISOString();
+ // 「此刻成立」按读出来的区间判(0022):结束了不知哪天的那条不再混进现行里
const current = all.filter(
(f) =>
- (!f.valid_from || f.valid_from <= nowIso) &&
- (!f.valid_to || f.valid_to > nowIso),
+ (!f.holds_from || f.holds_from <= nowIso) &&
+ (!f.holds_to || f.holds_to > nowIso),
);
const map = new Map<
string,