World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
fix: reject review closes that invert a fact's interval (#1315)
Nash Aschenbath6ac96324be07
diff --git a/crates/utopia-server/src/api/graph_routes_time_tests.rs b/crates/utopia-server/src/api/graph_routes_time_tests.rsindex 3ddaa6a3..2e26e35c 100644--- a/crates/utopia-server/src/api/graph_routes_time_tests.rs+++ b/crates/utopia-server/src/api/graph_routes_time_tests.rs@@ -166,3 +166,105 @@ async fn a_correction_keeps_the_mark_unless_the_request_changes_it() -> anyhow::.await?;result}++#[tokio::test]+async fn review_closes_refuse_inverted_intervals_without_settling_the_item() -> anyhow::Result<()> {+ let Some(url) = utopia_store::test_db::url() else {+ return Ok(());+ };+ let pool = sqlx::PgPool::connect(&url).await?;+ let [org, ws, kb, editor, property, lin, meridian, orion, old, new, conflict, violation] =+ std::array::from_fn(|_| Uuid::now_v7());+ // Only locally generated UUIDs and fixed timestamps enter this fixture SQL.+ sqlx::raw_sql(&format!(+ "INSERT INTO organizations(id,name) VALUES ('{org}','review-close-time');+ INSERT INTO workspaces(id,org_id,name) VALUES ('{ws}','{org}','review-close-time');+ INSERT INTO users(id,org_id,email,display_name,password_hash)+ VALUES ('{editor}','{org}','{editor}@time.test','editor','unused');+ INSERT INTO knowledge_bases(id,workspace_id,name) VALUES ('{kb}','{ws}','times');+ INSERT INTO kb_members(kb_id,user_id,role) VALUES ('{kb}','{editor}','editor');+ INSERT INTO relation_types(id,kb_id,key,label,temporal)+ VALUES ('{property}','{kb}','works_for','works for','state');+ INSERT INTO entities(id,kb_id,canonical_name) VALUES+ ('{lin}','{kb}','Lin Zhao'), ('{meridian}','{kb}','Meridian'), ('{orion}','{kb}','Orion');+ INSERT INTO facts(id,kb_id,subject_id,predicate_id,object_id,confidence,+ valid_from,valid_from_precision) VALUES+ ('{old}','{kb}','{lin}','{property}','{meridian}',0.9,'{MARCH}','day'),+ ('{new}','{kb}','{lin}','{property}','{orion}',0.9,NULL,NULL);+ INSERT INTO fact_conflicts(id,kb_id,old_fact_id,new_fact_id,reason)+ VALUES ('{conflict}','{kb}','{old}','{new}','no_time');+ INSERT INTO axiom_violations(id,kb_id,kind,left_fact,right_fact)+ VALUES ('{violation}','{kb}','derived_contradiction','{old}','{new}');"+ ))+ .execute(&pool)+ .await?;+ let result = async {+ let dir = tempfile::tempdir()?;+ let config = utopia_core::config::AppConfig {+ data_dir: dir.path().to_string_lossy().into_owned(),+ ..Default::default()+ };+ let search = Arc::new(utopia_search::SearchIndex::open(&dir.path().join("search"))?);+ let state = crate::state::AppState::new(pool.clone(), &config, search, "test-only".into());+ let token = crate::auth::issue_token(&state, editor)?;+ let app = crate::api::router(state, &config);+ let prefix = format!("/api/v1/kbs/{kb}");+ // The first date is later as written, but earlier at year precision.+ // The existing equal-state refusal must reach all three cards as well.+ for (at, precision, code) in [+ ("2024-10-01T00:00:00Z", "year", "interval_inverted"),+ (MARCH, "month", "empty_state_span"),+ ] {+ for (path, body) in [+ (+ format!("facts/{old}/close"),+ json!({"valid_to": at, "valid_to_precision": precision}),+ ),+ (+ format!("conflicts/{conflict}"),+ json!({"action": "close", "close_at": at, "close_at_precision": precision}),+ ),+ (+ format!("review/violations/{violation}"),+ json!({"resolution": "fact_closed", "close_at": at, "close_at_precision": precision}),+ ),+ ] {+ let (status, reply) = send(&app, &token, "POST", format!("{prefix}/{path}"), &body).await?;+ assert_eq!((status, reply["code"].as_str()), (StatusCode::UNPROCESSABLE_ENTITY, Some(code)), "{path}: {reply}");+ }+ }+ // A conflict with no explicit date closes at the new row's start; it must+ // get the same store guard, even though no date came through the route.+ sqlx::query("UPDATE facts SET valid_from = '2024-01-01', valid_from_precision = 'year' WHERE id = $1")+ .bind(new).execute(&pool).await?;+ let (status, reply) = send(&app, &token, "POST", format!("{prefix}/conflicts/{conflict}"), &json!({"action": "close"})).await?;+ assert_eq!((status, reply["code"].as_str()), (StatusCode::UNPROCESSABLE_ENTITY, Some("interval_inverted")));+ let unchanged: bool = sqlx::query_scalar(+ "SELECT (SELECT count(*) = 2 FROM facts WHERE kb_id = $1)+ AND EXISTS (SELECT 1 FROM facts WHERE id = $2 AND invalidated_at IS NULL AND valid_to IS NULL)+ AND EXISTS (SELECT 1 FROM fact_conflicts WHERE id = $3 AND status = 'open' AND resolution IS NULL)+ AND EXISTS (SELECT 1 FROM axiom_violations WHERE id = $4 AND status = 'open' AND resolution IS NULL)",+ ).bind(kb).bind(old).bind(conflict).bind(violation).fetch_one(&pool).await?;+ assert!(unchanged, "refused closes write no replacement and leave both queues open");++ // A later date can still close the refused row, with the endpoint stored+ // at its supplied precision, without translating it to a period's end.+ let (status, _) = send(&app, &token, "POST", format!("{prefix}/facts/{old}/close"),+ &json!({"valid_to": "2024-09-19T00:00:00Z", "valid_to_precision": "month"})).await?;+ assert_eq!(status, StatusCode::OK);+ let closed: (DateTime<Utc>, String, bool) = sqlx::query_as(+ "SELECT valid_to, valid_to_precision, end_after_period FROM facts WHERE supersedes = $1",+ ).bind(old).fetch_one(&pool).await?;+ assert_eq!(closed, ("2024-09-01T00:00:00Z".parse()?, "month".into(), false));+ anyhow::Ok(())+ }.await;+ sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")+ .bind(kb)+ .execute(&pool)+ .await?;+ sqlx::query("DELETE FROM organizations WHERE id = $1")+ .bind(org)+ .execute(&pool)+ .await?;+ result+}diff --git a/crates/utopia-store/src/temporal.rs b/crates/utopia-store/src/temporal.rsindex 9b68dda3..85e6d985 100644--- a/crates/utopia-store/src/temporal.rs+++ b/crates/utopia-store/src/temporal.rs@@ -873,16 +873,41 @@ pub async fn retract(pool: &PgPool, kb_id: Uuid, fact_id: Uuid) -> AppResult<boo}/// 作废 + 改写成**写明的**终点:旧行记 invalidated_at(认知轴),插入闭合区间的修正行-/// (世界轴),证据引用随行复制。原文说它在哪天结束、人裁决把它关上,都走这里——-/// 这个终点此后不再由引擎重算。返回修正行 id;`None` = 这条已被作废,没动。+/// (世界轴),证据引用随行复制。人裁决把它关上走这里,拒绝早于起点的终点;原文写入+/// 走 `close_stated`。这个终点此后不再由引擎重算。返回修正行 id;`None` = 已作废,没动。pub async fn close_superseded<'a>(pool: impl sqlx::Acquire<'a, Database = Postgres>,fact_id: Uuid,valid_to: DateTime<Utc>,valid_to_precision: &str,) -> AppResult<Option<Uuid>> {+ let valid_to = crate::graph::truncate_to(valid_to, Some(valid_to_precision));+ let mut tx = pool.begin().await?;+ let row: Option<(Option<DateTime<Utc>>, Option<String>)> = sqlx::query_as(+ "SELECT valid_from, valid_from_precision FROM facts+ WHERE id = $1 AND invalidated_at IS NULL FOR UPDATE",+ )+ .bind(fact_id)+ .fetch_optional(&mut *tx)+ .await?;+ let Some((from, from_precision)) = row else {+ return Ok(None);+ };+ // 锁住起点后再比,避免并发修正穿过检查;两端都按各自精度截断(#1294)。+ // 放在审核的 store 入口,也管住冲突默认取新事实起点的闭合,不改原文写入的规则。+ if from+ .is_some_and(|from| valid_to < crate::graph::truncate_to(from, from_precision.as_deref()))+ {+ return Err(utopia_core::AppError::invalid(+ "interval_inverted",+ "The start of the interval is after its end.",+ ));+ }// 按日期关上的(审核里关、冲突的 close_at、违规的 fact_closed)给的就是终点那一刻,不标- close_stated(pool, fact_id, valid_to, valid_to_precision, false).await+ let end = End::At(valid_to, valid_to_precision.to_string());+ let corrected = rewrite_end_tx(&mut tx, fact_id, &end, false, false, false).await?;+ tx.commit().await?;+ Ok(corrected)}/// [`close_superseded`],外加这个终点是不是原文所说时段之后的那一刻(`end_after_period`,diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex 2eb3e0d8..a7109fcb 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -140,6 +140,8 @@ export const en = {inference_off:"Materialized inference is off for this knowledge base. Turn it on in Settings.",bad_resolution: "That is not a valid decision.",+ interval_inverted:+ "The end is before the start. Give an end after the start.",empty_state_span:"A state that ends where it starts holds at no moment. Give an end after the start, or leave it open.",unknown_marks: "A single date marks the start, the end, or neither.",diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.tsindex ddda99a1..9222d4ed 100644--- a/web/src/i18n/zh.ts+++ b/web/src/i18n/zh.ts@@ -127,6 +127,7 @@ export const zh: Strings = {concurrency_range: "填一个 1 到 256 之间的数。",inference_off: "这个库没有打开物化推理。到设置里开。",bad_resolution: "这不是一个有效的裁决。",+ interval_inverted: "终点早于起点。请给一个晚于起点的终点。",empty_state_span: "起止相同的状态任何时刻都不成立。给一个晚于起点的终点,或者让它开着。",unknown_marks: "单个日期标的是开始、结束,或者都不是。",marks_needs_state: "只有状态属性才说单个日期标的是什么,事件与恒常属性不说。",diff --git a/web/src/pages/Review.tsx b/web/src/pages/Review.tsxindex 88e3a1eb..ac6c213a 100644--- a/web/src/pages/Review.tsx+++ b/web/src/pages/Review.tsx@@ -1551,6 +1551,7 @@ export function Review() {resolution: ViolationResolution;opts?: DecideOpts;}) => api.decideViolation(kb!.id, id, resolution, opts),+ onError: (e) => toast.error(e instanceof Error ? e.message : String(e)),onSettled: invalidate,});// 检查是同步的纯计算,所以直接 mutate 不排队。跑完把报告留在按钮旁边——@@ -1580,6 +1581,7 @@ export function Review() {close_at: closeAt,close_at_precision: closeAtPrecision,}),+ onError: (e) => toast.error(e instanceof Error ? e.message : String(e)),onSettled: invalidate,});@@ -1593,6 +1595,7 @@ export function Review() {validTo: string;precision: string;}) => api.closeFact(kb!.id, id, validTo, precision),+ onError: (e) => toast.error(e instanceof Error ? e.message : String(e)),onSettled: invalidate,});