World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
fix: preserve record clock precision in changes (#373)
Daniel331b8b60d7f5
diff --git a/crates/utopia-server/src/api/chat.rs b/crates/utopia-server/src/api/chat.rsindex 827a730d..5d824d49 100644--- a/crates/utopia-server/src/api/chat.rs+++ b/crates/utopia-server/src/api/chat.rs@@ -352,7 +352,7 @@ pub(super) fn base_tools() -> serde_json::Value {"type": "function","function": {"name": "changes",- "description": "What the graph LEARNED or REVISED in a window of record time — the belief axis. Answers \"what changed since X\", \"what did we get wrong\", \"what is new this quarter\", and needs no entity, so use it when the question names a period rather than a subject. Events: asserted (new claim), corrected (a claim replaced by a revised one), rejected (a claim withdrawn), merged (folded into another claim) — each with the document it came from. NOT the same axis as entity_facts(at): that asks \"what was true on date D\"; this asks \"what did we change our mind about between D1 and D2\". A fact about 2019 can be recorded in 2026 — this windows on when we recorded it.",+ "description": "What the graph LEARNED or REVISED in a window of record time — the belief axis. Answers \"what changed since X\", \"what did we get wrong\", \"what is new this quarter\", and needs no entity, so use it when the question names a period rather than a subject. Events: asserted (new claim), corrected (a claim replaced by a revised one), rejected (a claim withdrawn), merged (folded into another claim) — each with the document it came from. NOT the same axis as entity_facts(at): that asks \"what was true on date D\"; this asks \"what did we change our mind about between D1 and D2\". A fact about 2019 can be recorded in 2026 — this windows on when we recorded it. Each event starts with its exact UTC RFC3339 record timestamp, including fractional seconds. For 'before a correction arrived', find that event here, then call entity_facts with as_of one microsecond before its timestamp. At the timestamp itself the change already applies; subtracting a whole day or second can skip earlier records. Keep at for the world date asked about.","parameters": {"type": "object","properties": {@@ -417,6 +417,11 @@ const SYSTEM_PROMPT: &str = "You are the assistant of Utopia, a temporal knowled2. Facts carry validity ranges (from → to). For \"as of <date>\" questions pass `at` to \entity_facts and the server filters to that moment; for history questions omit `at` \to see the full timeline. For 'what did we know / have on record / believe as of <date>' or 'before <memo> arrived' pass `as_of` — that is the record axis and the ONLY way to answer such a question; do not narrate a plan, call the tool. The two combine: `at` for the date asked about, `as_of` for when. State dates in the answer.\n\+ 2a. For 'before a correction or memo arrived', call changes to find its exact record timestamp, \+ then call entity_facts with `as_of` one microsecond before that timestamp. At the timestamp \+ itself the change already applies. Preserve fractional seconds: for example, before \+ 2026-09-05T02:43:53.382Z use 2026-09-05T02:43:53.381999Z. Subtracting a whole day or \+ second can skip earlier records. Keep `at` for the world date asked about.\n\2b. For \"what changed / what is new / what did we get wrong since <date>\", call changes — \it needs no entity. Name the document a correction came from in plain prose. Graph tools \return no [n] numbers and no URLs, so never write a bracketed citation or a placeholder \diff --git a/crates/utopia-server/src/api/tools.rs b/crates/utopia-server/src/api/tools.rsindex de1d84e2..cad491f6 100644--- a/crates/utopia-server/src/api/tools.rs+++ b/crates/utopia-server/src/api/tools.rs@@ -356,23 +356,7 @@ pub async fn entity_facts(ctx: &ToolCtx<'_>, args: &serde_json::Value) -> ToolRelines.append(&mut derived);lines.join("\n")};- let detail = match (at, as_of) {- (Some(t), Some(r)) => format!(- "{} facts at {}, as recorded by {}",- facts.len(),- t.format("%Y-%m-%d"),- r.format("%Y-%m-%d")- ),- (Some(t), None) => format!("{} facts as of {}", facts.len(), t.format("%Y-%m-%d")),- (None, Some(r)) => {- format!(- "{} facts as recorded by {}",- facts.len(),- r.format("%Y-%m-%d")- )- }- (None, None) => format!("{} facts", facts.len()),- };+ let detail = entity_facts_detail(facts.len(), at, as_of);(text,json!({ "kind": "facts", "label": node.name, "detail": detail }),@@ -739,6 +723,28 @@ fn fact_line(f: &EntityFact) -> String {format!("{core}{range} [{}%]", (f.confidence * 100.0).round() as i32)}+// 记录轴上的两次更正可以发生在同一秒;输出必须能原样交回 as_of,不能截到天或秒。+fn record_stamp(time: chrono::DateTime<chrono::Utc>) -> String {+ time.to_rfc3339_opts(chrono::SecondsFormat::AutoSi, true)+}++fn entity_facts_detail(+ count: usize,+ at: Option<chrono::DateTime<chrono::Utc>>,+ as_of: Option<chrono::DateTime<chrono::Utc>>,+) -> String {+ match (at, as_of) {+ (Some(t), Some(r)) => format!(+ "{count} facts at {}, as recorded by {}",+ t.format("%Y-%m-%d"),+ record_stamp(r)+ ),+ (Some(t), None) => format!("{count} facts as of {}", t.format("%Y-%m-%d")),+ (None, Some(r)) => format!("{count} facts as recorded by {}", record_stamp(r)),+ (None, None) => format!("{count} facts"),+ }+}+/// 时刻参数:`YYYY-MM-DD` 或 RFC3339。`at` 与 `as_of` 共用一个解析——记录轴上的/// 时刻常常是一个带时间的戳("第一波灌完那一刻"),日期粒度装不下它fn parse_when(raw: &str) -> Option<chrono::DateTime<chrono::Utc>> {@@ -856,7 +862,7 @@ fn change_line(c: &GraphChange) -> String {};format!("{} {}: {} {} {}{}{}",- c.at.format("%Y-%m-%d"),+ record_stamp(c.at),c.kind,c.subject_name,c.predicate_label.as_deref().unwrap_or("?"),@@ -961,6 +967,40 @@ mod tests {}}+ // 同一秒内也能先录入再更正;截到整秒会把这两次认知重新叠在一起。+ #[test]+ fn change_stamps_round_trip_without_losing_the_record_clock() {+ let mut c = change("corrected");+ for stamp in [+ "2026-09-05T02:43:53Z",+ "2026-09-05T02:43:53.382Z",+ "2026-09-05T02:43:53.382001Z",+ "2026-09-05T02:43:53.382002Z",+ ] {+ c.at = t(stamp);+ let line = change_line(&c);+ let printed = line.split_whitespace().next().unwrap();+ assert_eq!(printed, stamp);+ assert_eq!(parse_when(printed), Some(c.at));+ }+ }++ #[test]+ fn fact_details_keep_the_record_instant_beside_the_world_date() {+ let at = Some(t("2024-08-01T00:00:00Z"));+ let as_of = Some(t("2026-09-05T02:43:53.382001Z"));+ assert_eq!(+ entity_facts_detail(2, at, as_of),+ "2 facts at 2024-08-01, as recorded by 2026-09-05T02:43:53.382001Z"+ );+ assert_eq!(+ entity_facts_detail(2, None, as_of),+ "2 facts as recorded by 2026-09-05T02:43:53.382001Z"+ );+ assert_eq!(entity_facts_detail(2, at, None), "2 facts as of 2024-08-01");+ assert_eq!(entity_facts_detail(0, None, None), "0 facts");+ }+fn attribute_fact(value: serde_json::Value) -> EntityFact {EntityFact {id: Uuid::nil(),@@ -1037,7 +1077,10 @@ mod tests {c.predicate_label = Some("headquartered in".to_string());c.valid_from = Some(t("2019-01-01T00:00:00Z"));let line = change_line(&c);- assert!(line.starts_with("2026-08-28 corrected: "), "{line}");+ assert!(+ line.starts_with("2026-08-28T10:00:00Z corrected: "),+ "{line}"+ );assert!(line.contains("[valid 2019-01-01 → now]"), "{line}");}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 3a400e23..72514860 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@@ -262,6 +262,57 @@ async fn the_recording_axis_rewinds_on_every_graph_read() -> anyhow::Result<()>let before = facts(Some("2026-02-01T00:00:00Z")).await?;assert!(before.is_empty(), "记下之前不该有事实");+ // #351:同一秒内先录入再更正。拿更正时刻退一整秒会跳过旧记录,+ // 拿更正时刻本身则已经是新记录;工具提示的「前一微秒」必须能读回旧事实。+ let first = t("2026-03-20T02:43:53.382000Z");+ let changed = t("2026-03-20T02:43:53.382002Z");+ sqlx::query("UPDATE facts SET recorded_at = $2, invalidated_at = $3 WHERE id = $1")+ .bind(f.retracted)+ .bind(first)+ .bind(changed)+ .execute(&pool)+ .await?;+ sqlx::query("UPDATE facts SET recorded_at = $2 WHERE id = $1")+ .bind(f.correction)+ .bind(changed)+ .execute(&pool)+ .await?;++ let events = utopia_store::graph::graph_changes(+ &pool,+ f.kb,+ t("2026-03-20T00:00:00Z"),+ t("2026-03-21T00:00:00Z"),+ Some(f.zhang),+ None,+ 10,+ )+ .await?;+ assert_eq!(events.len(), 2);+ assert_eq!(+ (events[0].at, events[0].kind.as_str()),+ (changed, "corrected")+ );+ assert_eq!((events[1].at, events[1].kind.as_str()), (first, "asserted"));++ for (moment, expected) in [+ (changed - chrono::Duration::seconds(1), None),+ (+ changed - chrono::Duration::microseconds(1),+ Some(f.retracted),+ ),+ (changed, Some(f.correction)),+ ] {+ let (_, rows) =+ utopia_store::graph::entity_detail(&pool, f.kb, f.zhang, None, Some(moment)).await?;+ let ids: Vec<_> = rows.iter().map(|row| row.id).collect();+ assert_eq!(+ ids,+ expected.into_iter().collect::<Vec<_>>(),+ "as_of={moment}"+ );+ }+// 拆台:facts/entities/… 全是 ON DELETE CASCADElet gone = sqlx::query("DELETE FROM organizations WHERE id = (