From 50522d454d23c07d2a0d6e03faddfee86a3dcee4 Mon Sep 17 00:00:00 2001 From: Rudy Mizrahi Celekli <47457359+rudycelekli@users.noreply.github.com> Date: Sat, 7 Nov 2026 12:23:10 -0500 Subject: [PATCH 01/13] A period written from one quarter to another ends in the last month, so Q1 to Q3 runs through September instead of stopping in July (#1405) * A period written from one quarter to another ends in the last month, so Q1 to Q3 runs through September instead of stopping in July Signed-off-by: Rudy Celekli * A period's end goes through parts_to_end, so the quarter-end rule lives in one place Signed-off-by: Rudy Celekli --------- Signed-off-by: Rudy Celekli --- crates/utopia-server/src/time_resolution.rs | 34 +++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/utopia-server/src/time_resolution.rs b/crates/utopia-server/src/time_resolution.rs index 69c00e1cb..a2d4bde44 100644 --- a/crates/utopia-server/src/time_resolution.rs +++ b/crates/utopia-server/src/time_resolution.rs @@ -160,9 +160,10 @@ fn quarter_around(t: DateTime, fiscal_year_end: Option<(u32, u32)>) -> Opti Some(((start, "month"), (end, "month"))) } -/// 一个期间的起止(写明的数字部分)。 +/// 一个期间的起止(写明的数字部分)。写在终点的季度是那一季的最后一个月: +/// 「第一季度到第三季度」止于 9 月,同 [`parts_to_end`]。 fn period_bounds(from: &DateParts, to: &DateParts) -> Option<(Bound, Bound)> { - Some((parts_to_time(from)?, parts_to_time(to)?)) + Some((parts_to_time(from)?, parts_to_end(to)?)) } /// 形状决定字在世界轴上占哪一段(决定 7:形状另存,这里只算区间)。 @@ -1568,6 +1569,35 @@ mod tests { ); } + #[test] + fn a_period_from_one_quarter_to_another_ends_in_the_last_month() { + let quarter = |q| DateParts { + quarter: Some(q), + ..parts(2025, None, None) + }; + let i = Interpretation { + id: 0, + shape: Shape::Interval, + reference: Reference::Period { + name: "Q1 to Q3 2025".into(), + from: Some(quarter(1)), + to: Some(quarter(3)), + }, + granularity: Granularity::Month, + }; + let r = resolve_one(&i, &DocumentDating::default(), &HashMap::new()); + assert_eq!( + (r.from, r.to, r.from_p, r.to_p, r.grade), + ( + Some(at("2025-01-01T00:00:00Z")), + Some(at("2025-09-01T00:00:00Z")), + Some("month"), + Some("month"), + "A" + ) + ); + } + #[test] fn month_arithmetic_clamps_to_the_month_end() { let t = at("2024-03-31T00:00:00Z"); From a1b0feb345d9ccc713c22dd121d73abff33d7deb Mon Sep 17 00:00:00 2001 From: Rudy Mizrahi Celekli <47457359+rudycelekli@users.noreply.github.com> Date: Sat, 7 Nov 2026 12:29:02 -0500 Subject: [PATCH 02/13] A month or a year stored at its own precision can be truncated, so "2024-03" truncated to a month is 2024-03-01 instead of no value (#1407) * A month or a year stored at its own precision can be truncated, so "2024-03" truncated to a month is 2024-03-01 instead of no value Signed-off-by: Rudy Celekli * A bare year must be four digits before date_trunc reads it, and ADR 0036 lists the month and year forms it accepts Signed-off-by: Rudy Celekli --------- Signed-off-by: Rudy Celekli Co-authored-by: WaylandYang <145302500+WaylandYang@users.noreply.github.com> --- crates/utopia-reason/src/expressions.rs | 54 ++++++++++++++++--- ...oration-aligns-a-schema-to-the-ontology.md | 8 ++- 2 files changed, 54 insertions(+), 8 deletions(-) diff --git a/crates/utopia-reason/src/expressions.rs b/crates/utopia-reason/src/expressions.rs index 3f08d4c26..ae9f29e03 100644 --- a/crates/utopia-reason/src/expressions.rs +++ b/crates/utopia-reason/src/expressions.rs @@ -77,15 +77,43 @@ impl DatePart { let Scalar::Text(text) = value else { return None; }; - let date = if text.len() == 10 { - NaiveDate::parse_from_str(&text, "%Y-%m-%d").ok()? + // 年精度存的是 "2024",月精度是 "2024-03"(规则 3)。截到比字更细的一档 + // 是在补一个原文没有的日或月,所以没有。 + let (date, finest) = if text.len() == 10 { + ( + NaiveDate::parse_from_str(&text, "%Y-%m-%d").ok()?, + Self::Day, + ) + } else if text.len() == 7 { + ( + NaiveDate::parse_from_str(&format!("{text}-01"), "%Y-%m-%d").ok()?, + Self::Month, + ) + } else if text.len() == 4 { + // 四位数字才是年:`parse` 也收 "+202"、"-123",它们不是存下来的年精度 + if !text.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let year: i32 = text.parse().ok()?; + (NaiveDate::from_ymd_opt(year, 1, 1)?, Self::Year) } else { // An offset is required: the host timezone must not change a fact. - chrono::DateTime::parse_from_rfc3339(&text) - .ok()? - .with_timezone(&chrono::Utc) - .date_naive() + ( + chrono::DateTime::parse_from_rfc3339(&text) + .ok()? + .with_timezone(&chrono::Utc) + .date_naive(), + Self::Day, + ) + }; + let rank = |part: Self| match part { + Self::Year => 0, + Self::Month => 1, + Self::Day => 2, }; + if rank(self) > rank(finest) { + return None; + } let date = match self { Self::Year => NaiveDate::from_ymd_opt(date.year(), 1, 1)?, Self::Month => NaiveDate::from_ymd_opt(date.year(), date.month(), 1)?, @@ -424,6 +452,9 @@ mod tests { ("year", "2024-01-01T00:30:00+01:00", "2023-01-01"), ("day", "2024-02-29", "2024-02-29"), ("month", "2024-02-29", "2024-02-01"), + ("month", "2024-03", "2024-03-01"), + ("year", "2024-03", "2024-01-01"), + ("year", "2024", "2024-01-01"), ] { let expr = Expr::from_json(&json!({"date_trunc":part,"expr":{"attr":id(1)}})).unwrap(); assert_eq!( @@ -432,6 +463,17 @@ mod tests { ); } let expr = Expr::from_json(&json!({"date_trunc":"month","expr":{"attr":id(1)}})).unwrap(); + let day = Expr::from_json(&json!({"date_trunc":"day","expr":{"attr":id(1)}})).unwrap(); + // 月精度没有日,年精度没有月:截得更细就没有值 + assert_eq!( + day.evaluate(&|_| Some(Scalar::Text("2024-03".into()))), + None + ); + assert_eq!(expr.evaluate(&|_| Some(Scalar::Text("2024".into()))), None); + let year = Expr::from_json(&json!({"date_trunc":"year","expr":{"attr":id(1)}})).unwrap(); + for input in ["+202", "-123"] { + assert_eq!(year.evaluate(&|_| Some(Scalar::Text(input.into()))), None); + } for input in [ "2023-02-29", "2024-02-30", diff --git a/docs/decisions/0036-exploration-aligns-a-schema-to-the-ontology.md b/docs/decisions/0036-exploration-aligns-a-schema-to-the-ontology.md index d5cb6a63d..90946611c 100644 --- a/docs/decisions/0036-exploration-aligns-a-schema-to-the-ontology.md +++ b/docs/decisions/0036-exploration-aligns-a-schema-to-the-ontology.md @@ -172,8 +172,12 @@ numeric constant into a valid number. The additional shapes are: Case results have one scalar type, and at most 32 arms. The existing four-edge `MAX_EXPR_DEPTH` bound applies to every expression. Dates accept an ISO calendar -date or an RFC 3339 timestamp with an offset; timestamp offsets are converted to -UTC before truncation. The result is an ISO calendar date, such as `2024-02-01`. +date, an RFC 3339 timestamp with an offset, or a coarser stored value: a month +(`2024-03`) or a four-digit year (`2024`), the forms a month- or year-precision +attribute is stored in. Timestamp offsets are converted to UTC before truncation. +A month or a year cannot be truncated to a finer part than it states, so +`date_trunc('day', '2024-03')` has no value. The result is an ISO calendar date, +such as `2024-02-01`. Naive timestamps, arbitrary cast types, decimal precision/scale, searched cases, aggregates and other SQL functions are outside this cut. From c7f6ae4dac7db8ea7bca6f53140609cf6166ff28 Mon Sep 17 00:00:00 2001 From: Rudy Mizrahi Celekli <47457359+rudycelekli@users.noreply.github.com> Date: Sat, 7 Nov 2026 12:34:06 -0500 Subject: [PATCH 03/13] A MySQL TIME past a day or below zero reads as itself, so TIMEDIFF of 30 hours is 30:15:00, not null (#1411) * A MySQL TIME past a day or below zero reads as itself, so TIMEDIFF of 30 hours is 30:15:00, not null Signed-off-by: Rudy Celekli * Import time_text in the MySQL time test so the test target compiles Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Rudy Celekli --------- Signed-off-by: Rudy Celekli Co-authored-by: Claude Sonnet 5.5 Co-authored-by: WaylandYang <145302500+WaylandYang@users.noreply.github.com> --- .../utopia-server/src/query_engine/mysql.rs | 56 ++++++++++++++++++- 1 file changed, 53 insertions(+), 3 deletions(-) diff --git a/crates/utopia-server/src/query_engine/mysql.rs b/crates/utopia-server/src/query_engine/mysql.rs index 38ffc3928..9611f5205 100644 --- a/crates/utopia-server/src/query_engine/mysql.rs +++ b/crates/utopia-server/src/query_engine/mysql.rs @@ -145,9 +145,10 @@ fn cell_to_json(row: &sqlx::mysql::MySqlRow, i: usize, type_name: &str) -> serde r.try_get::, _>(i) .map(|v| v.map(|d| d.to_string())) }), + // TIME 是一段时长(-838:59:59 到 838:59:59),NaiveTime 装不下 24 小时以上,还丢负号 Cell::Time => try_text(row, i, |r| { - r.try_get::, _>(i) - .map(|v| v.map(|t| t.to_string())) + r.try_get::, _>(i) + .map(|v| v.map(time_text)) }), Cell::DateTime => try_text(row, i, |r| { r.try_get::, _>(i) @@ -178,6 +179,26 @@ fn cell_to_json(row: &sqlx::mysql::MySqlRow, i: usize, type_name: &str) -> serde } } +/// 照 MySQL 自己的写法:`-01:30:00`、`30:15:00`,有小数才写小数 +fn time_text(t: sqlx::mysql::types::MySqlTime) -> String { + // sqlx 0.8 的 `MySqlTime::is_negative` 返回的是 is_positive,要看 sign 本身 + let sign = if t.sign().is_negative() { "-" } else { "" }; + let mut s = format!( + "{sign}{:02}:{:02}:{:02}", + t.hours(), + t.minutes(), + t.seconds() + ); + // 小数照 chrono 的 NaiveTime 写:整毫秒三位(`.500`),否则六位(`.000500`), + // 一天以内的 TIME 输出和从前一样 + match t.microseconds() { + 0 => {} + us if us % 1000 == 0 => s.push_str(&format!(".{:03}", us / 1000)), + us => s.push_str(&format!(".{us:06}")), + } + s +} + /// 按类型读文本,读不出来退回通用字符串(时间列被服务器配置成字符串时会走到)。 fn try_text(row: &sqlx::mysql::MySqlRow, i: usize, f: F) -> serde_json::Value where @@ -394,7 +415,7 @@ async fn keys(pool: &sqlx::MySqlPool) -> anyhow::Result { #[cfg(test)] mod tests { - use super::{cell_kind, Cell, MysqlEngine, QueryEngine, SchemaColumn}; + use super::{cell_kind, time_text, Cell, MysqlEngine, QueryEngine, SchemaColumn}; use sqlx::mysql::MySqlPoolOptions; use uuid::Uuid; @@ -510,6 +531,24 @@ mod tests { fx.cleanup().await; } + /// TIME 是一段时长:TIMEDIFF 过了 24 小时或是负的,都还是它自己 + #[tokio::test] + async fn a_time_past_a_day_or_below_zero_reads_as_itself_mysql() { + let Some(url) = live_url() else { return }; + let r = MysqlEngine::new(&url) + .execute( + "SELECT TIMEDIFF('2024-01-02 06:15:00', '2024-01-01 00:00:00') AS late, \ + TIMEDIFF('2024-01-01 00:00:00', '2024-01-01 01:30:00') AS early, \ + CAST('08:05:00' AS TIME) AS start", + ) + .await + .expect("execute"); + assert_eq!( + r.rows, + vec![r#"{"late":"30:15:00","early":"-01:30:00","start":"08:05:00"}"#] + ); + } + /// 每个测试自己的库,名字带随机后缀:并行跑不撞,也不碰服务器上已有的库。 /// 测完逐个 `DROP DATABASE`。**这是 MySQL 的「schema」,跟 PG 的命名空间 /// 不同——MySQL 的 schema 就是 database**(见 fetch_schema 顶上的注释) @@ -734,6 +773,17 @@ mod tests { fx.cleanup().await; } + /// CI 没有 MySQL,时长的写法在这里直接验:过 24 小时、负的、带小数 + #[test] + fn a_time_is_written_as_the_duration_it_holds() { + use sqlx::mysql::types::{MySqlTime, MySqlTimeSign}; + let t = |sign, h, m, s, us| time_text(MySqlTime::new(sign, h, m, s, us).unwrap()); + assert_eq!(t(MySqlTimeSign::Positive, 30, 15, 0, 0), "30:15:00"); + assert_eq!(t(MySqlTimeSign::Negative, 1, 30, 0, 0), "-01:30:00"); + assert_eq!(t(MySqlTimeSign::Positive, 8, 5, 0, 500_000), "08:05:00.500"); + assert_eq!(t(MySqlTimeSign::Positive, 8, 5, 0, 500), "08:05:00.000500"); + } + #[test] fn mariadb_is_the_same_protocol_under_another_name() { // sqlx 只认 mysql://,而界面允许写 mariadb://——不改写的话驱动会以 From 2448418065abe75b18d80f3621de648166505adc Mon Sep 17 00:00:00 2001 From: Rudy Mizrahi Celekli <47457359+rudycelekli@users.noreply.github.com> Date: Sat, 7 Nov 2026 12:40:19 -0500 Subject: [PATCH 04/13] An object storage prefix is listed as written, so a folder named "Case #12" syncs its files (#1421) * An object storage prefix is listed as written, so a folder named "Case #12" syncs its files Signed-off-by: Rudy Celekli * The object storage prefix test covers a Chinese folder, since Path::from also escaped non-ASCII prefixes Signed-off-by: Rudy Celekli --------- Signed-off-by: Rudy Celekli Co-authored-by: WaylandYang <145302500+WaylandYang@users.noreply.github.com> --- crates/utopia-server/src/object_storage.rs | 32 +++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/utopia-server/src/object_storage.rs b/crates/utopia-server/src/object_storage.rs index 7b6dffefe..c5b48091c 100644 --- a/crates/utopia-server/src/object_storage.rs +++ b/crates/utopia-server/src/object_storage.rs @@ -179,7 +179,9 @@ pub async fn fetch( // **三家各用各的 scheme。** 身份要唯一:同名的桶在 S3 与 GCS 上是两个 // 不同的东西,共用一个前缀会让两个来源的文档互相认领 let scheme = uri_scheme(kind); - let p = prefix.map(StorePath::from); + // 前缀是桶里 key 的原样写法。`Path::from` 会把 `#`、`[`、`%` 这些字符转义掉, + // `Case #12` 列的就成了 `Case %2312`,一个对象也找不到 + let p = prefix.map(|p| StorePath::parse(p).unwrap_or_else(|_| StorePath::from(p))); let mut listing = store.list(p.as_ref()); let mut out = Vec::new(); let mut truncated = false; @@ -269,6 +271,34 @@ mod tests { assert!(client("s3", &cfg).is_ok()); } + /// 文件夹名里带 `#`、`[]` 或中文的前缀照原样列:桶里的 key 就是这么写的。 + /// `Path::from` 把非 ASCII 的字节也转义,`合同/2024` 从前一个对象也列不出来 + #[tokio::test] + async fn a_prefix_with_symbols_lists_its_objects() { + use object_store::memory::InMemory; + let store = InMemory::new(); + for key in [ + "Case #12/brief.txt", + "Q1 [final]/plan.md", + "合同/2024/租约.pdf", + "other/x.txt", + ] { + store + .put(&StorePath::parse(key).unwrap(), "hello".into()) + .await + .unwrap(); + } + for (prefix, want) in [ + ("Case #12", "s3://b/Case #12/brief.txt"), + ("Q1 [final]/", "s3://b/Q1 [final]/plan.md"), + ("合同/2024", "s3://b/合同/2024/租约.pdf"), + ] { + let (objs, _) = fetch("s3", &store, "b", Some(prefix)).await.unwrap(); + let keys: Vec<&str> = objs.iter().map(|o| o.external_key.as_str()).collect(); + assert_eq!(keys, [want], "{prefix}"); + } + } + /// 真连一个 S3 兼容端点,只测**读**这一侧:列出来、取回内容、身份对不对。 /// /// **没有 `UTOPIA_S3_TEST_ENDPOINT` 时跳过而不是失败**——跟连库的测试 From 304b0a9e76b669d9c22fc28bfdec4f3fd817d1e3 Mon Sep 17 00:00:00 2001 From: Rudy Mizrahi Celekli <47457359+rudycelekli@users.noreply.github.com> Date: Sat, 7 Nov 2026 13:20:27 -0500 Subject: [PATCH 05/13] =?UTF-8?q?A=20counted=20figure=20is=20read=20into?= =?UTF-8?q?=20a=20larger=20declared=20unit,=20so=20"12,000=E4=BA=BA"=20und?= =?UTF-8?q?er=20"=E4=B8=87=E4=BA=BA"=20is=201.2=20(#1418)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Rudy Celekli Co-authored-by: WaylandYang <145302500+WaylandYang@users.noreply.github.com> --- crates/utopia-extract/src/lib.rs | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/crates/utopia-extract/src/lib.rs b/crates/utopia-extract/src/lib.rs index 4653f8301..6e0d976c9 100644 --- a/crates/utopia-extract/src/lib.rs +++ b/crates/utopia-extract/src/lib.rs @@ -776,10 +776,15 @@ pub fn attribute_value( if written.is_some() && wanted.is_some() && written != wanted { return None; } - // 原文写了量级词,或写了和声明一样的单位(「50000000元」对「万元」),n 才是绝对量, - // 要除下来;光秃秃的数就是声明单位下的数。除法走一次十进制解析,同 `scan_quantity` - // 乘量级词的道理:先算成 f64 再除会留下 23000.000000000004 - let n = if q.scaled || (written.is_some() && written == wanted) { + // 原文写了量级词,或写了和声明一样的单位(「50000000元」对「万元」、「12,000人」对 + // 「万人」),或写了计数量词,n 才是绝对量,要除下来;光秃秃的数就是声明单位下的数。 + // 除法走一次十进制解析,同 `scan_quantity` 乘量级词的道理:先算成 f64 再除会留下 + // 23000.000000000004 + let counted = q + .unit + .as_deref() + .is_some_and(|u| u == base || COUNTERS.iter().any(|c| c.trim() == u)); + let n = if q.scaled || counted || (written.is_some() && written == wanted) { format!("{}e-{exponent}", q.n).parse().ok()? } else { q.n @@ -1553,6 +1558,22 @@ mod an_attribute_value_is_read_in_its_declared_unit { ); } + /// 数后面写了人数的词,那就是一个个数出来的人,落到「万人」上要除下来 + #[test] + fn a_counted_figure_is_read_into_a_larger_unit() { + assert_eq!(value("number", Some("万人"), "12,000人"), Some(json!(1.2))); + assert_eq!(value("number", Some("万人"), "约3500名"), Some(json!(0.35))); + assert_eq!( + value("number", Some("thousand people"), "1,250 employees"), + Some(json!(1.25)) + ); + assert_eq!( + value("number", Some("万人"), "1400万人"), + Some(json!(1400.0)) + ); + assert_eq!(value("number", Some("万人"), "1.2"), Some(json!(1.2))); + } + /// 换不了的不换:货币对不上、读不出数的,宁缺勿脏 #[test] fn what_cannot_be_read_is_not_written() { From 95837f3dd1eae31491900f6a36001a8602ca0c76 Mon Sep 17 00:00:00 2001 From: Rudy Mizrahi Celekli <47457359+rudycelekli@users.noreply.github.com> Date: Sat, 7 Nov 2026 13:42:33 -0500 Subject: [PATCH 06/13] A number in accounting parentheses is read as negative, so "(1,234)" is -1234 instead of no value (#1422) * A number in accounting parentheses is read as negative, so "(1,234)" is -1234 instead of no value Signed-off-by: Rudy Celekli * An accounting parenthesis is a minus only when nothing but a magnitude, currency or percent follows it, so "(2024) 500" stays no value Signed-off-by: Rudy Celekli --------- Signed-off-by: Rudy Celekli Co-authored-by: WaylandYang <145302500+WaylandYang@users.noreply.github.com> --- crates/utopia-extract/src/lib.rs | 53 ++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/crates/utopia-extract/src/lib.rs b/crates/utopia-extract/src/lib.rs index 6e0d976c9..b9618b63a 100644 --- a/crates/utopia-extract/src/lib.rs +++ b/crates/utopia-extract/src/lib.rs @@ -471,6 +471,8 @@ fn scan_quantity(s: &str, strict: bool) -> Option { if s.is_empty() { return None; } + let negated = if strict { None } else { accounting_negative(s) }; + let s = negated.as_deref().unwrap_or(s); let (body, percent) = match s.strip_suffix('%') { Some(b) => (b.trim_end(), true), None => (s, false), @@ -559,6 +561,35 @@ fn scan_quantity(s: &str, strict: bool) -> Option { }) } +/// 财报的写法:括号里的数是负数。`(1,234)` → `-1,234`,`$(1.2) billion` → `$-1.2 billion`, +/// `(12.5%)` → `-12.5%`。括号前只许有一个货币,括号里只许是数,括号后只许是量级词、 +/// 货币或 `%`:「(1) 1,200 employees」「(2024) 500」里的括号是编号和年份,不是负号 +fn accounting_negative(s: &str) -> Option { + let (head, rest) = s.split_once('(')?; + let (inner, after) = rest.split_once(')')?; + if !head.trim().is_empty() && currency_unit(head.trim()).is_none() { + return None; + } + let mut tail = after.trim(); + tail = tail.strip_suffix('%').unwrap_or(tail).trim_end(); + while !tail.is_empty() { + let (tok, next) = next_token(tail); + if magnitude(&tok.to_ascii_lowercase()).is_none() && currency_unit(tok).is_none() { + return None; + } + tail = next.trim_start(); + } + let digits = inner.trim().strip_suffix('%').unwrap_or(inner.trim()); + if !digits.starts_with(|c: char| c.is_ascii_digit()) + || !digits + .chars() + .all(|c| c.is_ascii_digit() || matches!(c, ',' | '.')) + { + return None; + } + Some(format!("{head}-{}{after}", inner.trim())) +} + /// 读出来的一个量。`n` 已经乘上了量级词;`scaled` 记下原文写没写量级词——换算到属性 /// 声明的单位时要知道 `5000` 是原文就这么写的数,还是 `5000万` 展开出来的 struct Quantity { @@ -1481,6 +1512,28 @@ mod tests { ); assert_eq!(normalize_attr_value("text", &json!([1])), None); } + + /// 财报表里括号里的数是负数:从前整格读不出来,这个值就丢了 + #[test] + fn an_accounting_negative_is_read_as_negative() { + use serde_json::json; + let n = |s: &str| normalize_attr_value("number", &json!(s)); + assert_eq!(n("(1,234)"), Some(json!(-1234.0))); + assert_eq!(n("$(1.2) billion"), Some(json!(-1200000000.0))); + assert_eq!(n("(12.5%)"), Some(json!(-12.5))); + assert_eq!( + attribute_value("number", Some("万元"), &json!("(350)万元")), + Some(json!(-350.0)) + ); + // 括号里不是数、括号前不是货币的,照旧读不出 + assert_eq!(n("(see note 4)"), None); + assert_eq!(n("Q3 (12)"), None); + // 括号后面跟着别的数:括号是编号或年份,不是负号 + assert_eq!(n("(1) 1,200 employees"), None); + assert_eq!(n("(2024) 500"), None); + // 宾语判定不跟着变:点了名的「(1984)」仍是一个东西 + assert!(!literal_object("(1984)", true)); + } } #[cfg(test)] From 6a76564b44ebce7deaae5662eb61821b2a524ba1 Mon Sep 17 00:00:00 2001 From: Rudy Mizrahi Celekli <47457359+rudycelekli@users.noreply.github.com> Date: Sat, 7 Nov 2026 17:08:46 -0500 Subject: [PATCH 07/13] An ODS time cell reads as the time it shows, so PT09H30M00S becomes 09:30 (#1429) Signed-off-by: Rudy Celekli Co-authored-by: WaylandYang <145302500+WaylandYang@users.noreply.github.com> --- crates/utopia-ingest/src/parsers.rs | 36 ++++++++++++ .../tests/spreadsheet_ods_times.rs | 56 +++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 crates/utopia-ingest/tests/spreadsheet_ods_times.rs diff --git a/crates/utopia-ingest/src/parsers.rs b/crates/utopia-ingest/src/parsers.rs index a80d11ce5..8e98c8980 100644 --- a/crates/utopia-ingest/src/parsers.rs +++ b/crates/utopia-ingest/src/parsers.rs @@ -1098,10 +1098,46 @@ fn spreadsheet_cell_text(cell: Option<&calamine::Data>) -> String { None | Some(calamine::Data::Empty) => String::new(), Some(calamine::Data::DateTime(d)) => excel_date(d), Some(calamine::Data::Float(f)) => excel_number(*f), + Some(calamine::Data::DurationIso(d)) => ods_time(d).unwrap_or_else(|| d.clone()), Some(other) => other.to_string(), } } +/// ODS 的时刻格存的是 ISO 时长(`office:time-value="PT09H30M00S"`),不分一天里的钟点和 +/// 累计时长。照 xlsx 那两种格子的写法:不到一天的写钟点(`09:30`),满一天的写累计的 +/// 时分秒(`36:15:00`)。LibreOffice 常把秒写成 `59.999999998S`,按最近的整秒算 +fn ods_time(iso: &str) -> Option { + let iso = iso.trim(); + let (sign, body) = match iso.strip_prefix('-') { + Some(rest) => ("-", rest.strip_prefix('P')?), + None => ("", iso.strip_prefix('P')?), + }; + let (days, mut clock) = body.split_once('T').unwrap_or((body, "")); + let mut seconds = match days.strip_suffix('D') { + Some(n) => n.parse::().ok()? * 86_400.0, + None if days.is_empty() => 0.0, + None => return None, + }; + for (unit, scale) in [('H', 3_600.0), ('M', 60.0), ('S', 1.0)] { + if let Some((n, tail)) = clock.split_once(unit) { + seconds += n.parse::().ok()? * scale; + clock = tail; + } + } + if !clock.is_empty() || !seconds.is_finite() { + return None; + } + let seconds = seconds.round() as u64; + let (h, m, s) = (seconds / 3600, seconds / 60 % 60, seconds % 60); + Some(if h >= 24 || !sign.is_empty() { + format!("{sign}{h}:{m:02}:{s:02}") + } else if s == 0 { + format!("{h:02}:{m:02}") + } else { + format!("{h:02}:{m:02}:{s:02}") + }) +} + /// 表头从第一排至少两格有字的行开始;这一块里纵向 merge 伸到的行也是表头。 fn spreadsheet_headers(regions: &[GridMerge], rows: &[GridRow]) -> Option> { let start = rows diff --git a/crates/utopia-ingest/tests/spreadsheet_ods_times.rs b/crates/utopia-ingest/tests/spreadsheet_ods_times.rs new file mode 100644 index 000000000..143817095 --- /dev/null +++ b/crates/utopia-ingest/tests/spreadsheet_ods_times.rs @@ -0,0 +1,56 @@ +//! ODS 的时刻格读成它显示的钟点,和 xlsx 里同一格写法一样。 +//! +//! LibreOffice 把时刻存成 ISO 时长:`office:value-type="time" +//! office:time-value="PT09H30M00S"`,格子里显示的是 `09:30:00`。 + +use std::io::{Cursor, Write}; + +fn ods(rows: &[(&str, &str)]) -> Vec { + let cells: String = rows + .iter() + .map(|(label, time)| { + format!( + r#"{label}{time}"# + ) + }) + .collect(); + let content = format!( + r#"ItemWhen{cells}"# + ); + let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); + let stored = + zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + zip.start_file("mimetype", stored).unwrap(); + zip.write_all(b"application/vnd.oasis.opendocument.spreadsheet") + .unwrap(); + zip.start_file( + "META-INF/manifest.xml", + zip::write::SimpleFileOptions::default(), + ) + .unwrap(); + zip.write_all(br#""#) + .unwrap(); + zip.start_file("content.xml", zip::write::SimpleFileOptions::default()) + .unwrap(); + zip.write_all(content.as_bytes()).unwrap(); + zip.finish().unwrap().into_inner() +} + +#[test] +fn an_ods_time_cell_reads_as_clock_time() { + let text = utopia_ingest::parse( + "shifts.ods", + &ods(&[ + ("Daily call", "PT09H30M00S"), + ("Cutoff", "PT17H45M30S"), + ("Close", "PT14H29M59.999999998S"), + ("Downtime", "PT36H15M00S"), + ]), + ) + .unwrap() + .text; + assert!(text.contains("| Daily call | 09:30 |"), "{text}"); + assert!(text.contains("| Cutoff | 17:45:30 |"), "{text}"); + assert!(text.contains("| Close | 14:30 |"), "{text}"); + assert!(text.contains("| Downtime | 36:15:00 |"), "{text}"); +} From 4a1594432c914e0bc024af2f44ba0e90b02ffdfa Mon Sep 17 00:00:00 2001 From: Rudy Mizrahi Celekli <47457359+rudycelekli@users.noreply.github.com> Date: Sat, 7 Nov 2026 18:51:08 -0500 Subject: [PATCH 08/13] Docs search ignores letter case, so search_docs("Mcp") finds the "Agents over MCP" sections instead of nothing (#1432) Signed-off-by: Rudy Celekli Co-authored-by: WaylandYang <145302500+WaylandYang@users.noreply.github.com> --- crates/utopia-search/src/docs.rs | 43 +++++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/crates/utopia-search/src/docs.rs b/crates/utopia-search/src/docs.rs index bab165596..1e376d2b9 100644 --- a/crates/utopia-search/src/docs.rs +++ b/crates/utopia-search/src/docs.rs @@ -7,7 +7,7 @@ use tantivy::query::{BooleanQuery, Occur, Query, TermQuery}; use tantivy::schema::{ Field, IndexRecordOption, Schema, TextFieldIndexing, TextOptions, Value, STORED, }; -use tantivy::tokenizer::TextAnalyzer; +use tantivy::tokenizer::{LowerCaser, TextAnalyzer}; use tantivy::{Index, IndexReader, TantivyDocument, Term}; const JIEBA: &str = "jieba"; @@ -52,9 +52,13 @@ impl DocsIndex { let schema = schema_builder.build(); let index = Index::create_in_ram(schema); - index - .tokenizers() - .register(JIEBA, tantivy_jieba::JiebaTokenizer::new()); + // 语料是英文为主的 markdown;内存索引每次启动重建,折小写不涉及重建索引 + index.tokenizers().register( + JIEBA, + TextAnalyzer::builder(tantivy_jieba::JiebaTokenizer::new()) + .filter(LowerCaser) + .build(), + ); let mut writer = index.writer(16 * 1024 * 1024)?; for s in sections { @@ -133,3 +137,34 @@ impl DocsIndex { Ok(hits) } } + +#[cfg(test)] +mod tests { + use super::{DocsIndex, DocsSection}; + + fn section(anchor: &str, body: &str) -> DocsSection { + DocsSection { + slug: "mcp".into(), + title: "Agents over MCP".into(), + heading: anchor.into(), + anchor: anchor.into(), + body: body.into(), + } + } + + /// chat 的 search_docs 由模型随手写查询,大小写不由文档定 + #[test] + fn a_query_finds_the_section_whatever_its_letter_case() { + let index = DocsIndex::build(&[ + section("connect", "Point your MCP client at the Utopia server."), + section("tokens", "Create an access token in Settings."), + ]) + .unwrap(); + for query in ["MCP client", "mcp client", "Mcp", "settings", "SETTINGS"] { + let hits = index.search(query, 5).unwrap(); + assert!(!hits.is_empty(), "{query:?} found nothing"); + } + assert_eq!(index.search("mcp", 5).unwrap()[0].anchor, "connect"); + assert_eq!(index.search("access TOKEN", 5).unwrap()[0].anchor, "tokens"); + } +} From bdabe92591740e3895ef2159d27c95d2c2e11aed Mon Sep 17 00:00:00 2001 From: Rudy Mizrahi Celekli <47457359+rudycelekli@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:12:54 -0500 Subject: [PATCH 09/13] =?UTF-8?q?A=20sub-property=20ring=20is=20reported?= =?UTF-8?q?=20from=20its=20own=20members,=20so=20p=20=E2=8A=91=20q=20?= =?UTF-8?q?=E2=8A=91=20r=20=E2=8A=91=20q=20names=20the=20ring=20q,=20r=20i?= =?UTF-8?q?nstead=20of=20p,=20q,=20r=20(#1443)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Rudy Celekli Co-authored-by: WaylandYang <145302500+WaylandYang@users.noreply.github.com> --- crates/utopia-reason/src/ontology.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/utopia-reason/src/ontology.rs b/crates/utopia-reason/src/ontology.rs index dc6e68537..af3f7117c 100644 --- a/crates/utopia-reason/src/ontology.rs +++ b/crates/utopia-reason/src/ontology.rs @@ -170,6 +170,10 @@ pub fn check_ontology( let mut cur = start; for _ in 0..MAX_ANCESTRY { if seen.contains(&cur) { + // 走进的是别处的环,start 不在环上:等环上的成员自己那一轮报 + if cur != start { + break; + } // 环上每个成员都标记过,整条环只报一次 for m in &seen { reported.insert(*m); @@ -591,6 +595,23 @@ mod inverse_and_sub_property_tests { assert_eq!(ring[0].path.len(), 3); } + /// 1 ⊑ 2 ⊑ 3 ⊑ 2:环只有 2 和 3,1 只是挂在环上。 + #[test] + fn a_predicate_that_leads_into_a_ring_is_not_on_it() { + let mk = |parent: u8| Axioms { + sub_property_of: Some(c(parent)), + ..Default::default() + }; + let ax = HashMap::from([(c(1), mk(2)), (c(2), mk(3)), (c(3), mk(2))]); + let ring: Vec = check_ontology(&ax, &[], &[]) + .into_iter() + .filter(|x| x.kind == Defect::SubPropertyCycle) + .collect(); + assert_eq!(ring.len(), 1); + assert_eq!(ring[0].subject, c(2)); + assert_eq!(ring[0].path, vec![c(2), c(3)]); + } + /// 一条不成环的链不该被误报。 #[test] fn a_chain_that_ends_is_not_a_ring() { From 5e32087b77b868dc8f62a9d5a12232bff3d21ad5 Mon Sep 17 00:00:00 2001 From: Rudy Mizrahi Celekli <47457359+rudycelekli@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:31:37 -0500 Subject: [PATCH 10/13] A company name with a comma before "Inc." recalls its entity, so "Acme, Inc." finds Acme instead of creating a second one (#1433) Signed-off-by: Rudy Celekli Co-authored-by: WaylandYang <145302500+WaylandYang@users.noreply.github.com> --- crates/utopia-store/src/resolution.rs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rs index 926472916..4cefc3b83 100644 --- a/crates/utopia-store/src/resolution.rs +++ b/crates/utopia-store/src/resolution.rs @@ -123,8 +123,10 @@ pub fn name_stem(name: &str) -> Option { if words.len() >= 2 { if generic(words[words.len() - 1]) { let stem = words[..words.len() - 1].join(" "); - if !generic(&stem) { - return Some(stem); + // 「Acme, Inc.」:后缀前那个逗号是写法,不是名字 + let stem = stem.trim_end_matches(','); + if !stem.is_empty() && !generic(stem) { + return Some(stem.to_string()); } } if generic(words[0]) { @@ -2821,6 +2823,17 @@ mod tests { assert!(recall_keys("张三").len() <= 10); } + /// 英文公司名常在后缀前加逗号:「Acme, Inc.」与「Acme」「Acme Inc」是同一个召回 + #[test] + fn a_comma_before_the_generic_suffix_is_not_part_of_the_stem() { + assert_eq!(name_stem("Acme, Inc.").as_deref(), Some("acme")); + assert_eq!(name_stem("Orion Labs, Inc").as_deref(), Some("orion labs")); + let k = recall_keys("Acme, Inc."); + assert!(k.contains(&"acme".to_string()), "{k:?}"); + assert!(k.contains(&"acme inc".to_string()), "{k:?}"); + assert_eq!(name_stem(", Inc."), None); + } + #[test] fn type_drift_classes() { // 还没判出类型的那一侧 → 召回候选。0009 之前这一档比的是 `concept` From e3d20b83c5741857947a7052b9a03cde077f561b Mon Sep 17 00:00:00 2001 From: Rudy Mizrahi Celekli <47457359+rudycelekli@users.noreply.github.com> Date: Sat, 7 Nov 2026 21:11:35 -0500 Subject: [PATCH 11/13] =?UTF-8?q?A=20full-width=20yen=20sign=20is=20read?= =?UTF-8?q?=20as=20the=20currency,=20so=20"=EF=BF=A55,000=E4=B8=87"=20is?= =?UTF-8?q?=2050000000=20instead=20of=20no=20value=20(#1442)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Rudy Celekli Co-authored-by: WaylandYang <145302500+WaylandYang@users.noreply.github.com> --- crates/utopia-extract/src/lib.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/utopia-extract/src/lib.rs b/crates/utopia-extract/src/lib.rs index b9618b63a..3039a9f34 100644 --- a/crates/utopia-extract/src/lib.rs +++ b/crates/utopia-extract/src/lib.rs @@ -437,7 +437,8 @@ pub(crate) fn currency_unit(tok: &str) -> Option<&'static str> { "$" | "USD" | "usd" | "US$" | "dollar" | "dollars" | "美元" => "$", "€" | "EUR" | "eur" | "euro" | "euros" | "欧元" => "€", "£" | "GBP" | "gbp" | "pound" | "pounds" | "英镑" => "£", - "¥" | "JPY" | "jpy" | "yen" | "日元" => "¥", + // 中文排版的「¥」是全角的同一个符号 + "¥" | "¥" | "JPY" | "jpy" | "yen" | "日元" => "¥", "CNY" | "cny" | "RMB" | "rmb" | "yuan" | "人民币" | "元" | "元人民币" | "人民币元" => { "¥" } @@ -1636,6 +1637,19 @@ mod an_attribute_value_is_read_in_its_declared_unit { assert_eq!(value("bool", None, "尚未上市"), None); } + /// 中文财务文本的金额多用全角的「¥」,与「¥」是同一个符号 + #[test] + fn a_full_width_yen_sign_is_read_as_the_currency() { + assert_eq!(value("number", None, "¥5,000万"), Some(json!(5e7))); + assert_eq!( + value("number", Some("万元"), "¥5,000万"), + Some(json!(5000.0)) + ); + assert_eq!(value("number", Some("元"), "¥1,280"), Some(json!(1280.0))); + assert_eq!(value("number", Some("万美元"), "¥5,000万"), None); + assert!(literal_object("¥5000万", true)); + } + #[test] fn a_figure_or_a_date_is_not_a_thing() { for v in [ From 739452ce14d04139c9dce9189f5c5e0f38d136cf Mon Sep 17 00:00:00 2001 From: Szabo Bogdan Date: Sun, 8 Nov 2026 03:39:44 +0100 Subject: [PATCH 12/13] A role word is recorded against the chunk that says it, so a re-push can say something new (#1428) Signed-off-by: Bogdan Szabo Co-authored-by: WaylandYang <145302500+WaylandYang@users.noreply.github.com> --- crates/utopia-cli/src/main.rs | 2 +- crates/utopia-server/src/api/mcp_tests.rs | 5 +- crates/utopia-server/src/extraction_open.rs | 1 + .../src/export_provenance_integrity.sql | 8 + crates/utopia-store/src/graph.rs | 16 +- crates/utopia-store/src/materialize.rs | 12 +- crates/utopia-store/src/pending.rs | 3 +- .../a_bound_statement_becomes_a_typed_fact.rs | 55 +++- ...ole_word_moves_onto_its_evidence_chunks.rs | 289 ++++++++++++++++++ ...pen_statement_keeps_the_documents_words.rs | 37 ++- .../exported_references_never_cross_a_kb.rs | 31 +- crates/utopia-store/tests/store/main.rs | 1 + ...gration_0070_runs_under_any_search_path.rs | 16 +- ...ferences-stay-inside-the-knowledge-base.md | 8 +- ...ole-word-speaks-while-its-chunk-is-live.md | 4 +- docs/decisions/README.md | 2 +- docs/design/ledger.md | 4 +- ...ole_word_is_recorded_against_its_chunk.sql | 125 ++++++++ 18 files changed, 561 insertions(+), 58 deletions(-) create mode 100644 crates/utopia-store/tests/store/a_role_word_moves_onto_its_evidence_chunks.rs create mode 100644 migrations/0121_a_role_word_is_recorded_against_its_chunk.sql diff --git a/crates/utopia-cli/src/main.rs b/crates/utopia-cli/src/main.rs index 617df6e55..817a0e137 100644 --- a/crates/utopia-cli/src/main.rs +++ b/crates/utopia-cli/src/main.rs @@ -82,7 +82,7 @@ struct ManifestDataDir { /// not a side effect of a code change. // 是迁移文件的**个数**,不是最大的编号(守卫 `schema_version_policy_compares_against_current` // 按个数比):编号有空缺时两者不同——0071 由一个开放 PR 占着,0072 先落,个数是 71 -const CURRENT_SCHEMA_VERSION: u32 = 111; +const CURRENT_SCHEMA_VERSION: u32 = 112; #[tokio::main] async fn main() -> anyhow::Result<()> { diff --git a/crates/utopia-server/src/api/mcp_tests.rs b/crates/utopia-server/src/api/mcp_tests.rs index ca6f3e280..d92916da3 100644 --- a/crates/utopia-server/src/api/mcp_tests.rs +++ b/crates/utopia-server/src/api/mcp_tests.rs @@ -1008,10 +1008,11 @@ async fn entity_facts_reads_back_a_statements_role_words() -> anyhow::Result<()> return Ok(()); }; sqlx::query( - "INSERT INTO statement_qualifiers(fact_id,role,value) - VALUES ($1,'lines','{\"value\":\"10-42\"}'::jsonb)", + "INSERT INTO statement_qualifiers(fact_id,role,value,chunk_id) + VALUES ($1,'lines','{\"value\":\"10-42\"}'::jsonb,$2)", ) .bind(f.corrected) + .bind(f.chunk) .execute(&f.state.pool) .await?; let result = f diff --git a/crates/utopia-server/src/extraction_open.rs b/crates/utopia-server/src/extraction_open.rs index b328583b6..e9cf5cb84 100644 --- a/crates/utopia-server/src/extraction_open.rs +++ b/crates/utopia-server/src/extraction_open.rs @@ -665,6 +665,7 @@ async fn apply_open_extraction( utopia_store::graph::add_statement_qualifier( pool, fact_id, + chunk.id, role, value.as_ref(), *entity, diff --git a/crates/utopia-store/src/export_provenance_integrity.sql b/crates/utopia-store/src/export_provenance_integrity.sql index c4c894832..3132ece48 100644 --- a/crates/utopia-store/src/export_provenance_integrity.sql +++ b/crates/utopia-store/src/export_provenance_integrity.sql @@ -266,6 +266,14 @@ SELECT edge, kind, COUNT(*) AS rows FROM ( LEFT JOIN entities e ON e.id = q.entity_id WHERE f.kb_id = $1 AND q.entity_id IS NOT NULL UNION ALL + -- @edge statement_qualifiers.chunk_id -> chunks.id + -- 角色词记在哪一块上:归属同样按所属 fact 的库判 + SELECT 'squalifier.chunk', 'cross_kb', c.kb_id IS DISTINCT FROM f.kb_id + FROM statement_qualifiers q + JOIN facts f ON f.id = q.fact_id + LEFT JOIN chunks c ON c.id = q.chunk_id + WHERE f.kb_id = $1 + UNION ALL -- @edge time_mentions.fact_id -> facts.id -- 时间提及以行自己的 kb 归属:指的事实与段落都必须同库 SELECT 'timemention.fact', 'cross_kb', f.kb_id IS DISTINCT FROM t.kb_id diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs index a68aef9fd..02632074f 100644 --- a/crates/utopia-store/src/graph.rs +++ b/crates/utopia-store/src/graph.rs @@ -199,12 +199,12 @@ pub async fn fact_qualifiers_for( Ok(out) } -/// 往一条开放陈述上写一个按角色词记的属性。**先写者留着**:同一条陈述同一个角色词 -/// 再听到一次不覆盖(与 [`upsert_fact_qualifier`] 的 Conflict 一条规矩——两次观察 -/// 不一致该另立一行加一条冲突,这一刀还没走到那一步)。值与实体必须恰好给一个 +/// 往一条开放陈述上写一个按角色词记的属性,记在说它的那一块上(0070 决定 1)。 +/// 同一块再说一次不写新行;另一块说的另记一行,旧行不动。值与实体必须恰好给一个 pub async fn add_statement_qualifier( pool: &PgPool, fact_id: Uuid, + chunk_id: Uuid, role: &str, value: Option<&serde_json::Value>, entity_id: Option, @@ -223,19 +223,21 @@ pub async fn add_statement_qualifier( )); } sqlx::query( - "INSERT INTO statement_qualifiers (fact_id, role, value, entity_id) - VALUES ($1, $2, $3, $4) ON CONFLICT (fact_id, role) DO NOTHING", + "INSERT INTO statement_qualifiers (fact_id, role, value, entity_id, chunk_id) + VALUES ($1, $2, $3, $4, $5) ON CONFLICT (fact_id, role, chunk_id) DO NOTHING", ) .bind(fact_id) .bind(role) .bind(value) .bind(entity_id) + .bind(chunk_id) .execute(pool) .await?; Ok(()) } -/// 一批开放陈述各自的角色词属性,按事实 id 取回;实体那一格连上显示名 +/// 一批开放陈述各自的角色词属性,按事实 id 取回;实体那一格连上显示名。 +/// 同一个值记在几块上只返回一次 pub async fn statement_qualifiers_for( pool: &PgPool, fact_ids: &[Uuid], @@ -253,7 +255,7 @@ pub async fn statement_qualifiers_for( entity_name: Option, } let rows: Vec = sqlx::query_as( - "SELECT q.fact_id, q.role, q.value, q.entity_id, e.canonical_name AS entity_name + "SELECT DISTINCT q.fact_id, q.role, q.value, q.entity_id, e.canonical_name AS entity_name FROM statement_qualifiers q LEFT JOIN entities e ON e.id = q.entity_id WHERE q.fact_id = ANY($1) diff --git a/crates/utopia-store/src/materialize.rs b/crates/utopia-store/src/materialize.rs index c2d263cee..855f1da6a 100644 --- a/crates/utopia-store/src/materialize.rs +++ b/crates/utopia-store/src/materialize.rs @@ -410,7 +410,7 @@ async fn materialize_in_tx( .bind(d.statement) .execute(&mut **tx) .await?; - // 证据与限定各抄一份:证据是同一段原文的同一处引文;限定照角色词原样带过去 + // 证据每次都抄:证据是同一段原文的同一处引文 sqlx::query( "INSERT INTO fact_evidence (fact_id, chunk_id, quote, document_id, doc_version, proposed_predicate, quote_start, quote_end) @@ -423,9 +423,15 @@ async fn materialize_in_tx( .bind(d.statement) .execute(&mut **tx) .await?; + // 角色词只抄行还没有的角色(0070 决定 1 的修订):并进已有行的陈述若对同一角色 + // 说了别的值,抄过来这一行就同时读到两个值;别的值由决定 4 带过来 sqlx::query( - "INSERT INTO statement_qualifiers (fact_id, role, value, entity_id) - SELECT $1, role, value, entity_id FROM statement_qualifiers WHERE fact_id = $2 + "INSERT INTO statement_qualifiers (fact_id, role, value, entity_id, chunk_id) + SELECT $1, q.role, q.value, q.entity_id, q.chunk_id + FROM statement_qualifiers q + WHERE q.fact_id = $2 + AND NOT EXISTS (SELECT 1 FROM statement_qualifiers n + WHERE n.fact_id = $1 AND n.role = q.role) ON CONFLICT DO NOTHING", ) .bind(fact) diff --git a/crates/utopia-store/src/pending.rs b/crates/utopia-store/src/pending.rs index 8d581902d..03f402c41 100644 --- a/crates/utopia-store/src/pending.rs +++ b/crates/utopia-store/src/pending.rs @@ -499,7 +499,8 @@ async fn confirm_open( } else { q.get("value") }; - crate::graph::add_statement_qualifier(pool, fact_id, role, value, entity_id).await?; + crate::graph::add_statement_qualifier(pool, fact_id, v.chunk_id, role, value, entity_id) + .await?; } for t in json_items(v.time_words.as_ref()) { let (Some(text), Some(char_start)) = ( diff --git a/crates/utopia-store/tests/store/a_bound_statement_becomes_a_typed_fact.rs b/crates/utopia-store/tests/store/a_bound_statement_becomes_a_typed_fact.rs index c53a3dd55..401688e46 100644 --- a/crates/utopia-store/tests/store/a_bound_statement_becomes_a_typed_fact.rs +++ b/crates/utopia-store/tests/store/a_bound_statement_becomes_a_typed_fact.rs @@ -4,7 +4,7 @@ //! 一条陈述「Harbor Bakery —is based in→ Port Ellen」,签名 (is based in, organization, //! place) 绑到 headquartered_in:算出一条类型化行,谓词是它,证据与限定抄过来, //! `from_statement_id` 指回陈述;再跑一遍什么都不动;带 mood 的陈述不算;另一份文档 -//! 的同一句并进同一行(两条来源、两条证据);作废其中一条陈述,行还在、来源少一条; +//! 的同一句并进同一行(两条来源、两条证据),它说的另一个 since 不跟进来,行只读建行那条的,它说的 until 行还没有、跟进来;作废其中一条陈述,行还在、来源少一条; //! 绑定翻成 reverse,旧行作废、新行主宾对调;绑定改成 none,行作废、不再补。 //! //! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。 @@ -133,21 +133,35 @@ async fn a_bound_statement_becomes_a_typed_fact() -> anyhow::Result<()> { .bind(doc) .execute(&pool) .await?; - anyhow::Ok(()) + anyhow::Ok(chunk) } }; - evidence_of(stated, "bakery.txt").await?; - evidence_of(again, "bakery-2.txt").await?; - sqlx::query( - "INSERT INTO statement_qualifiers (fact_id, role, value) VALUES ($1, 'since', '\"2019\"'::jsonb)", - ) - .bind(stated) - .execute(&pool) - .await?; + let stated_chunk = evidence_of(stated, "bakery.txt").await?; + let again_chunk = evidence_of(again, "bakery-2.txt").await?; + let planned_chunk = evidence_of(planned, "bakery-plan.txt").await?; + // 并进来的那条还说了 until:行没有这个角色,要跟进来 + for (statement, chunk, role, value) in [ + (stated, stated_chunk, "since", "2019"), + (again, again_chunk, "since", "2021"), + (again, again_chunk, "until", "2024"), + ] { + sqlx::query( + "INSERT INTO statement_qualifiers (fact_id, role, value, chunk_id) + VALUES ($1, $3, to_jsonb($4::text), $2)", + ) + .bind(statement) + .bind(chunk) + .bind(role) + .bind(value) + .execute(&pool) + .await?; + } sqlx::query( - "INSERT INTO statement_qualifiers (fact_id, role, value) VALUES ($1, 'mood', '\"will\"'::jsonb)", + "INSERT INTO statement_qualifiers (fact_id, role, value, chunk_id) + VALUES ($1, 'mood', '\"will\"'::jsonb, $2)", ) .bind(planned) + .bind(planned_chunk) .execute(&pool) .await?; @@ -207,13 +221,26 @@ async fn a_bound_statement_becomes_a_typed_fact() -> anyhow::Result<()> { .bind(typed_id) .fetch_one(&pool) .await?; - let qualifiers: Vec = sqlx::query_scalar( - "SELECT role FROM statement_qualifiers WHERE fact_id = $1 ORDER BY role", + // 并进来的那条说 since 2021:行已有 since,不抄,只读建行那条的 2019; + // 它说的 until 行还没有,跟进来 + let qualifiers: Vec<(String, String, Uuid)> = sqlx::query_as( + "SELECT role, value #>> '{}', chunk_id FROM statement_qualifiers + WHERE fact_id = $1 ORDER BY role", ) .bind(typed_id) .fetch_all(&pool) .await?; - assert_eq!((sources, evidence, qualifiers), (3, 2, vec!["since".to_string()])); + assert_eq!( + (sources, evidence, qualifiers), + ( + 3, + 2, + vec![ + ("since".to_string(), "2019".to_string(), stated_chunk), + ("until".to_string(), "2024".to_string(), again_chunk), + ] + ) + ); // 再跑一遍:什么都不动 assert_eq!(materialize(&pool, kb).await?, Outcome::default()); diff --git a/crates/utopia-store/tests/store/a_role_word_moves_onto_its_evidence_chunks.rs b/crates/utopia-store/tests/store/a_role_word_moves_onto_its_evidence_chunks.rs new file mode 100644 index 000000000..ce8188f40 --- /dev/null +++ b/crates/utopia-store/tests/store/a_role_word_moves_onto_its_evidence_chunks.rs @@ -0,0 +1,289 @@ +//! 0121:角色词搬到它事实的每一块证据上(0070 决定 1,#1267)。 +//! +//! 开一个隔离库迁到 0120,种下旧形状的行,再跑 0121: +//! - 每块证据(被取代的也算)都拿到陈述的角色词,读出来仍是一个值; +//! - 类型化行只在说过这个词、且值与它相同的来源陈述的块上拿到它; +//! - 已失效、没有证据的事实(purge 留下的)的角色词被删掉; +//! - 活着的事实有角色词却没有证据,迁移整份中止。 +//! +//! 建库失败(角色没权限的环境)与没有 UTOPIA_DATABASE_URL 一样处理:跳过。 + +use sqlx::{Acquire, PgPool}; +use uuid::Uuid; + +/// 维护库的地址:`…/utopia` → `…/postgres` +fn admin_url() -> Option { + let url = utopia_store::test_db::url()?; + let (head, _) = url.rsplit_once('/')?; + Some(format!("{head}/postgres")) +} + +/// 按文件顺序跑 `from..=through` 的迁移,各自一个事务(与 sqlx::migrate 同一形状) +async fn migrate(pool: &PgPool, from: i64, through: i64) -> Result<(), sqlx::Error> { + let migrator = sqlx::migrate!("../../migrations"); + let mut conn = pool.acquire().await?; + for m in migrator + .iter() + .filter(|m| (from..=through).contains(&m.version)) + { + let mut tx = conn.begin().await?; + sqlx::raw_sql(&m.sql).execute(&mut *tx).await?; + tx.commit().await?; + } + Ok(()) +} + +/// 隔离库:建 → 迁到 0120 → 返回(库名, 连接池)。失败就地跳过 +async fn scratch(suffix: &str) -> Option<(String, PgPool)> { + let admin_pool = PgPool::connect(&admin_url()?).await.ok()?; + let name = format!("sq121_{}_{}", suffix, Uuid::now_v7().simple()); + let created = sqlx::query(&format!("CREATE DATABASE {name}")) + .execute(&admin_pool) + .await; + admin_pool.close().await; + if created.is_err() { + eprintln!("跳过:建不了隔离库(角色没有 CREATEDB)"); + return None; + } + let url = utopia_store::test_db::url()?; + let (head, _) = url.rsplit_once('/')?; + let pool = PgPool::connect(&format!("{head}/{name}")).await.ok()?; + if let Err(e) = migrate(&pool, 0, 120).await { + eprintln!("跳过:迁到 0120 失败(迁移链自身的问题): {e}"); + drop_scratch(&name).await; + return None; + } + Some((name, pool)) +} + +async fn drop_scratch(name: &str) { + let Some(admin) = admin_url() else { return }; + if let Ok(pool) = PgPool::connect(&admin).await { + let _ = sqlx::query(&format!("DROP DATABASE IF EXISTS {name} WITH (FORCE)")) + .execute(&pool) + .await; + pool.close().await; + } +} + +struct Ledger { + kb: Uuid, + entity: Uuid, + superseded_chunk: Uuid, + live_chunk: Uuid, +} + +/// 一个库、一个实体、一份文档的两块:旧的那块已被取代 +async fn seed_ledger(pool: &PgPool) -> anyhow::Result { + let (org, ws, kb, entity, doc) = ( + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + ); + let (superseded_chunk, live_chunk) = (Uuid::now_v7(), Uuid::now_v7()); + sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'm121-test')") + .bind(org) + .execute(pool) + .await?; + sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'm121-test')") + .bind(ws) + .bind(org) + .execute(pool) + .await?; + sqlx::query( + "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'm121-test')", + ) + .bind(kb) + .bind(ws) + .execute(pool) + .await?; + sqlx::query("INSERT INTO entities (id, kb_id, canonical_name) VALUES ($1, $2, 'parse.rs')") + .bind(entity) + .bind(kb) + .execute(pool) + .await?; + sqlx::query( + "INSERT INTO documents (id, kb_id, filename, sha256, status) + VALUES ($1, $2, 'ci.json', 'm121', 'ready')", + ) + .bind(doc) + .bind(kb) + .execute(pool) + .await?; + sqlx::query( + "INSERT INTO chunks (id, kb_id, document_id, seq, text, superseded_at) + VALUES ($1, $3, $4, 0, 'lines 40-52', now()), ($2, $3, $4, 1, 'lines 58-70', NULL)", + ) + .bind(superseded_chunk) + .bind(live_chunk) + .bind(kb) + .bind(doc) + .execute(pool) + .await?; + Ok(Ledger { + kb, + entity, + superseded_chunk, + live_chunk, + }) +} + +/// 一条事实;`open` 是开放陈述,否则是类型化行 +async fn fact(pool: &PgPool, ledger: &Ledger, open: bool, live: bool) -> anyhow::Result { + let fact = Uuid::now_v7(); + sqlx::query( + "INSERT INTO facts (id, kb_id, subject_id, object_id, confidence, invalidated_at, layer, phrase) + VALUES ($1, $2, $3, $3, 0.9, CASE WHEN $4 THEN NULL ELSE now() END, + CASE WHEN $5 THEN 'open' ELSE 'typed' END, CASE WHEN $5 THEN 'covers' END)", + ) + .bind(fact) + .bind(ledger.kb) + .bind(ledger.entity) + .bind(live) + .bind(open) + .execute(pool) + .await?; + Ok(fact) +} + +/// 按 0120 的形状写一个 `lines` 角色词(没有 chunk_id) +async fn says_lines(pool: &PgPool, fact: Uuid) -> anyhow::Result<()> { + says_lines_as(pool, fact, "40-52").await +} + +async fn says_lines_as(pool: &PgPool, fact: Uuid, lines: &str) -> anyhow::Result<()> { + sqlx::query("INSERT INTO statement_qualifiers (fact_id, role, value) VALUES ($1, 'lines', $2)") + .bind(fact) + .bind(serde_json::json!(lines)) + .execute(pool) + .await?; + Ok(()) +} + +async fn evidence(pool: &PgPool, fact: Uuid, chunks: &[Uuid]) -> anyhow::Result<()> { + for chunk in chunks { + sqlx::query("INSERT INTO fact_evidence (fact_id, chunk_id) VALUES ($1, $2)") + .bind(fact) + .bind(chunk) + .execute(pool) + .await?; + } + Ok(()) +} + +async fn role_word_chunks(pool: &PgPool, facts: Vec) -> anyhow::Result> { + let rows = sqlx::query_as( + "SELECT fact_id, chunk_id FROM statement_qualifiers + WHERE fact_id = ANY($1) ORDER BY fact_id, chunk_id", + ) + .bind(facts) + .fetch_all(pool) + .await?; + Ok(rows) +} + +#[tokio::test] +async fn role_words_move_onto_every_evidence_chunk_and_leave_a_purged_fact() -> anyhow::Result<()> { + let Some((name, pool)) = scratch("chunks").await else { + return Ok(()); + }; + let ledger = seed_ledger(&pool).await?; + let stated = fact(&pool, &ledger, true, true).await?; + says_lines(&pool, stated).await?; + evidence(&pool, stated, &[ledger.superseded_chunk, ledger.live_chunk]).await?; + let purged = fact(&pool, &ledger, true, false).await?; + says_lines(&pool, purged).await?; + + migrate(&pool, 121, 121).await?; + + let mut expected = vec![ + (stated, ledger.superseded_chunk), + (stated, ledger.live_chunk), + ]; + expected.sort(); + assert_eq!( + role_word_chunks(&pool, vec![stated, purged]).await?, + expected, + "每块证据一行,没有证据的已失效事实一行不留" + ); + let read = utopia_store::graph::statement_qualifiers_for(&pool, &[stated]).await?; + assert_eq!( + serde_json::to_value(&read[&stated])?, + serde_json::json!([{ "role": "lines", "value": "40-52", "entity_id": null, "entity_name": null }]) + ); + pool.close().await; + drop_scratch(&name).await; + Ok(()) +} + +#[tokio::test] +async fn a_typed_row_takes_a_role_word_only_on_the_chunk_of_a_statement_that_said_the_same_value( +) -> anyhow::Result<()> { + let Some((name, pool)) = scratch("typed").await else { + return Ok(()); + }; + let ledger = seed_ledger(&pool).await?; + let (said, silent, disagreed) = ( + fact(&pool, &ledger, true, true).await?, + fact(&pool, &ledger, true, true).await?, + fact(&pool, &ledger, true, true).await?, + ); + says_lines(&pool, said).await?; + evidence(&pool, said, &[ledger.superseded_chunk]).await?; + evidence(&pool, silent, &[ledger.live_chunk]).await?; + // 说了另一个值的来源:它的块不替类型化行说话,类型化行仍只读出原来的值 + says_lines_as(&pool, disagreed, "58-70").await?; + evidence(&pool, disagreed, &[ledger.live_chunk]).await?; + let typed = fact(&pool, &ledger, false, true).await?; + says_lines(&pool, typed).await?; + evidence(&pool, typed, &[ledger.superseded_chunk, ledger.live_chunk]).await?; + sqlx::query("INSERT INTO typed_fact_sources (fact_id, statement_id) VALUES ($1, $2), ($1, $3), ($1, $4)", + ) + .bind(typed) + .bind(said) + .bind(silent) + .bind(disagreed) + .execute(&pool) + .await?; + // 来源已经不在的类型化行:角色词照旧抄到它的证据上,读出来不少 + let sourceless = fact(&pool, &ledger, false, true).await?; + says_lines(&pool, sourceless).await?; + evidence(&pool, sourceless, &[ledger.live_chunk]).await?; + + migrate(&pool, 121, 121).await?; + + let mut expected = vec![ + (typed, ledger.superseded_chunk), + (sourceless, ledger.live_chunk), + ]; + expected.sort(); + assert_eq!( + role_word_chunks(&pool, vec![typed, sourceless]).await?, + expected + ); + pool.close().await; + drop_scratch(&name).await; + Ok(()) +} + +#[tokio::test] +async fn a_live_fact_with_role_words_and_no_evidence_stops_the_migration() -> anyhow::Result<()> { + let Some((name, pool)) = scratch("orphan").await else { + return Ok(()); + }; + let ledger = seed_ledger(&pool).await?; + let orphan = fact(&pool, &ledger, true, true).await?; + says_lines(&pool, orphan).await?; + + let err = migrate(&pool, 121, 121).await.unwrap_err().to_string(); + + assert!( + err.contains("live facts with role words and no evidence (x1)"), + "{err}" + ); + pool.close().await; + drop_scratch(&name).await; + Ok(()) +} diff --git a/crates/utopia-store/tests/store/an_open_statement_keeps_the_documents_words.rs b/crates/utopia-store/tests/store/an_open_statement_keeps_the_documents_words.rs index ddc0b1020..46983265b 100644 --- a/crates/utopia-store/tests/store/an_open_statement_keeps_the_documents_words.rs +++ b/crates/utopia-store/tests/store/an_open_statement_keeps_the_documents_words.rs @@ -147,6 +147,7 @@ async fn an_open_statement_shows_under_its_phrase_and_reuses_its_row() -> anyhow graph::add_statement_qualifier( &pool, fact, + f.chunk_a, "amount", Some(&serde_json::json!({ "value": "$1.2 billion" })), None, @@ -318,27 +319,39 @@ async fn an_open_statement_shows_under_its_phrase_and_reuses_its_row() -> anyhow Some(serde_json::json!({ "value": "$1.2 billion" })) ); assert!(q[0].entity_id.is_none()); - // 先写者留着 - graph::add_statement_qualifier( - &pool, - fact, - "amount", - Some(&serde_json::json!({ "value": "$2 billion" })), - None, + // 角色词记在说它的那一块上:另一块的值另记一行,同一块再说一次不添行 + for (chunk, amount) in [(f.chunk_b, "$2 billion"), (f.chunk_a, "$1.2 billion")] { + graph::add_statement_qualifier( + &pool, + fact, + chunk, + "amount", + Some(&serde_json::json!({ "value": amount })), + None, + ) + .await?; + } + let amounts: Vec<(Uuid, serde_json::Value)> = sqlx::query_as( + "SELECT chunk_id, value FROM statement_qualifiers + WHERE fact_id = $1 AND role = 'amount' ORDER BY chunk_id", ) + .bind(fact) + .fetch_all(&pool) .await?; - let q = &graph::statement_qualifiers_for(&pool, &[fact]).await?[&fact]; assert_eq!( - q[0].value, - Some(serde_json::json!({ "value": "$1.2 billion" })) + amounts, + vec![ + (f.chunk_a, serde_json::json!({ "value": "$1.2 billion" })), + (f.chunk_b, serde_json::json!({ "value": "$2 billion" })), + ] ); // 值与实体必须恰好一个 assert!( - graph::add_statement_qualifier(&pool, fact, "buyer", None, None) + graph::add_statement_qualifier(&pool, fact, f.chunk_a, "buyer", None, None) .await .is_err() ); - graph::add_statement_qualifier(&pool, fact, "buyer", None, Some(f.acme)).await?; + graph::add_statement_qualifier(&pool, fact, f.chunk_a, "buyer", None, Some(f.acme)).await?; let q = &graph::statement_qualifiers_for(&pool, &[fact]).await?[&fact]; let buyer = q.iter().find(|x| x.role == "buyer").unwrap(); assert_eq!(buyer.entity_id, Some(f.acme)); diff --git a/crates/utopia-store/tests/store/exported_references_never_cross_a_kb.rs b/crates/utopia-store/tests/store/exported_references_never_cross_a_kb.rs index 281a1c1a9..481523ce5 100644 --- a/crates/utopia-store/tests/store/exported_references_never_cross_a_kb.rs +++ b/crates/utopia-store/tests/store/exported_references_never_cross_a_kb.rs @@ -379,14 +379,25 @@ async fn new_cross_kb_writes_are_rejected_on_every_exported_edge() -> anyhow::Re // —— 开放陈述的属性(statement_qualifiers,0061):行没有 kb 列,归属按 // 所属 fact 的库判;别库的实体值会被铸进本库 IRI let err = sqlx::query( - "INSERT INTO statement_qualifiers (fact_id, role, entity_id) - VALUES ($1, 'as', $2)", + "INSERT INTO statement_qualifiers (fact_id, role, entity_id, chunk_id) + VALUES ($1, 'as', $2, $3)", ) .bind(f.fact_a) .bind(f.ent_b) + .bind(f.chunk_a) .execute(&pool) .await; assert!(err.is_err(), "squalifier.entity→foreign 必须被拒"); + // 角色词记在别库的块上(0070 决定 1) + let err = sqlx::query( + "INSERT INTO statement_qualifiers (fact_id, role, value, chunk_id) + VALUES ($1, 'lines', '\"1\"'::jsonb, $2)", + ) + .bind(f.fact_a) + .bind(f.chunk_b) + .execute(&pool) + .await; + assert!(err.is_err(), "squalifier.chunk→foreign 必须被拒"); // —— 时间提及(0061/0064):提及自己的 kb 必须与它指的事实、段落同属一库 let err = sqlx::query( @@ -989,13 +1000,22 @@ async fn malformed_rows_fail_every_exported_edge_closed() -> anyhow::Result<()> .bind(f.fact_b) .execute(&mut *tx) .await?; - // 开放陈述的属性值指着别库实体 + // 开放陈述的属性值指着别库实体;另一个角色词记在别库的块上 sqlx::query( - "INSERT INTO statement_qualifiers (fact_id, role, entity_id) - VALUES ($1, 'as', $2)", + "INSERT INTO statement_qualifiers (fact_id, role, entity_id, chunk_id) + VALUES ($1, 'as', $2, $3)", ) .bind(f.fact_a) .bind(f.ent_b) + .bind(f.chunk_a) + .execute(&mut *tx) + .await?; + sqlx::query( + "INSERT INTO statement_qualifiers (fact_id, role, value, chunk_id) + VALUES ($1, 'lines', '\"1\"'::jsonb, $2)", + ) + .bind(f.fact_a) + .bind(f.chunk_b) .execute(&mut *tx) .await?; // 时间提及两种坏法:归属在 A 却指着 B 的段落(体检扫得见——行按自己的 @@ -1466,6 +1486,7 @@ async fn malformed_rows_fail_every_exported_edge_closed() -> anyhow::Result<()> "condition.predicate", "factsource.statement", "squalifier.entity", + "squalifier.chunk", "timemention.fact", "timemention.chunk", "binding.type", diff --git a/crates/utopia-store/tests/store/main.rs b/crates/utopia-store/tests/store/main.rs index 7c0276732..be6e452af 100644 --- a/crates/utopia-store/tests/store/main.rs +++ b/crates/utopia-store/tests/store/main.rs @@ -85,6 +85,7 @@ mod a_retraction_leaves_the_graph; mod a_review_has_a_summary; mod a_review_page_is_assembled_in_batches; mod a_rewritten_statement_keeps_its_section_dates; +mod a_role_word_moves_onto_its_evidence_chunks; mod a_rule_computes_what_it_concludes; mod a_rule_concludes_a_type; mod a_rule_reads_what_a_rule_concluded; diff --git a/crates/utopia-store/tests/store/migration_0070_runs_under_any_search_path.rs b/crates/utopia-store/tests/store/migration_0070_runs_under_any_search_path.rs index 7949f1145..21cfcc790 100644 --- a/crates/utopia-store/tests/store/migration_0070_runs_under_any_search_path.rs +++ b/crates/utopia-store/tests/store/migration_0070_runs_under_any_search_path.rs @@ -428,6 +428,11 @@ const TRIGGER_EDGES: &[(&str, &str, &str)] = &[ "entity_type_id", "relation_type_ranges_same_kb", ), + ( + "statement_qualifiers", + "chunk_id", + "statement_qualifiers_same_kb", + ), ( "statement_qualifiers", "entity_id", @@ -619,7 +624,7 @@ struct Coverage { impl Coverage { /// 完备 = 没有未归类的边、没有腐掉的登记、面与机制互证得上, /// 每条受保护边都进了导出体检、体检里没有腐掉的分支, - /// 且两类已覆盖边的数量与当前迁移链的 44/16 一致。 + /// 且两类已覆盖边的数量与当前迁移链的 44/17 一致。 fn assert_complete(&self) -> anyhow::Result<()> { let mut problems = String::new(); let mut dump = |name: &str, xs: &[String]| { @@ -641,9 +646,10 @@ impl Coverage { self.declarative.len() )); } - if self.trigger_covered.len() != 16 { + // 0121 adds the chunk a role word is recorded against. + if self.trigger_covered.len() != 17 { problems.push_str(&format!( - " TRIGGER_EDGES = {} (expected 16)\n", + " TRIGGER_EDGES = {} (expected 17)\n", self.trigger_covered.len() )); } @@ -1062,8 +1068,8 @@ async fn a_protected_edge_missing_from_preflight_fails_the_guard() -> anyhow::Re #[test] fn the_preflight_check_notices_a_dropped_or_stray_edge() -> anyhow::Result<()> { let surface = preflight_surface()?; - // 同一份文件两个方向各数一次:60 条结构边 + 5 条 merged 过滤检查 - assert_eq!(surface.edges.len(), 60, "preflight 必须覆盖全部保护边"); + // 同一份文件两个方向各数一次:61 条结构边 + 5 条 merged 过滤检查 + assert_eq!(surface.edges.len(), 61, "preflight 必须覆盖全部保护边"); assert_eq!( surface.filters, [ diff --git a/docs/decisions/0048-provenance-references-stay-inside-the-knowledge-base.md b/docs/decisions/0048-provenance-references-stay-inside-the-knowledge-base.md index fc1a24ff4..6496b486e 100644 --- a/docs/decisions/0048-provenance-references-stay-inside-the-knowledge-base.md +++ b/docs/decisions/0048-provenance-references-stay-inside-the-knowledge-base.md @@ -16,7 +16,7 @@ Every reference an export can resolve must join rows that live in the same knowl ## The mechanism, per edge -Thirty-nine reference edges are protected. The split is decided by a single question: **does the referencing row carry the kb authority itself?** +Forty reference edges are protected (thirty-nine at migration 0070; 0121 added `statement_qualifiers.chunk_id`). The split is decided by a single question: **does the referencing row carry the kb authority itself?** | Source | Edge → target | kb authority | Mechanism | |---|---|---|---| @@ -40,11 +40,11 @@ Thirty-nine reference edges are protected. The split is decided by a single ques | `relation_type_qualifiers` | `qualifier_type_id` → `relation_types` | relation's kb | trigger | | `attribute_rule_conditions` | `predicate_id` → `relation_types` | owning rule's kb | trigger | | `typed_fact_sources` | `statement_id` → `facts` | owning fact's kb | trigger | -| `statement_qualifiers` | `entity_id` → `entities` | owning fact's kb | trigger | +| `statement_qualifiers` | `entity_id` → `entities`; `chunk_id` → `chunks` | owning fact's kb | trigger | **26 edges** are declared as `FOREIGN KEY (kb_id, ref) REFERENCES t (kb_id, id)`, replacing the single-column FK that was already there — one kernel-level lookup now proves existence *and* same-base, where before it proved existence and a second check would have had to prove the rest. Eight `UNIQUE (kb_id, id)` constraints on the referenced tables back those keys (`documents`, `chunks`, `entities`, `entity_types`, `relation_types`, `facts`, `rules`, `attribute_rules`). -**13 edges** cannot be expressed that way: their kb authority is a *parent row's* `kb_id`, and the link row has no `kb_id` column at all. A composite key cannot name `fact.kb_id` from a `fact_evidence` row. These keep row-level `BEFORE` triggers — nine functions, ten triggers — that read the parent's base and compare. +**14 edges** cannot be expressed that way: their kb authority is a *parent row's* `kb_id`, and the link row has no `kb_id` column at all. A composite key cannot name `fact.kb_id` from a `fact_evidence` row. These keep row-level `BEFORE` triggers — nine functions, ten triggers — that read the parent's base and compare. **`kb_id` is immutable** on every owned table (one shared function, twelve `BEFORE UPDATE OF kb_id` triggers). Composite keys only guard the rows being pointed *at*; the trigger-covered edges derive their authority from a parent row, and a parent moving base would silently un-anchor every child pointing at it. Making kb reassignment impossible is what lets a point-in-time check stay correct. @@ -54,7 +54,7 @@ Thirty-nine reference edges are protected. The split is decided by a single ques `pg_restore` loads data with `COPY` and creates constraints after, so any shape that survives the migration survives a restore — and the deferred self-references are what let a same-transaction or intra-statement forward chain restore without ordering games. Two sharper edges were designed for explicitly: -- `pg_restore --disable-triggers` and any `session_replication_role = replica` load suppress *user* triggers wholesale. Declarative foreign keys are internal constraint triggers and are **not** suppressed — so the 26 declarative edges hold even in a replica-mode load, which is a second reason to prefer them wherever the schema can say them. The 13 trigger-covered edges admit the gap and are backstopped by the export-side `provenance_integrity` check and the §0 audit query, which doubles as a post-load audit. +- `pg_restore --disable-triggers` and any `session_replication_role = replica` load suppress *user* triggers wholesale. Declarative foreign keys are internal constraint triggers and are **not** suppressed — so the 26 declarative edges hold even in a replica-mode load, which is a second reason to prefer them wherever the schema can say them. The 14 trigger-covered edges admit the gap and are backstopped by the export-side `provenance_integrity` check and the §0 audit query, which doubles as a post-load audit. - The migration pins `search_path = pg_catalog` in every function body and qualifies every identifier `public.*`, because restore empties the session `search_path` and a hostile first schema must not redirect name resolution. `migration_0070_runs_under_any_search_path` installs the whole migration under a normal, an empty, and a decoy-first `search_path`. - The coverage itself is guarded by a catalog-derived regression in the same test file: it enumerates every column-level reference inside the ledger surface from `pg_catalog` and fails when an edge resolves to no declared composite-FK, owner-derived-trigger, or explicit exclusion — so a reference column added later cannot silently slip past the invariant. The same guard also reads the exact preflight scan the export runs (`export_provenance_integrity.sql`) and fails when a protected edge has no scan branch — or a scan branch no longer names a protected edge — so schema protection and export preflight cannot drift apart. diff --git a/docs/decisions/0070-a-role-word-speaks-while-its-chunk-is-live.md b/docs/decisions/0070-a-role-word-speaks-while-its-chunk-is-live.md index 7cd32a6ac..9abc926cd 100644 --- a/docs/decisions/0070-a-role-word-speaks-while-its-chunk-is-live.md +++ b/docs/decisions/0070-a-role-word-speaks-while-its-chunk-is-live.md @@ -1,6 +1,6 @@ # 0070 · A role word speaks while its chunk is live -- **Status**: Proposed · 2026-10-16 · [#1267](https://github.com/deeplethe/utopia/issues/1267) · open: all five decisions +- **Status**: In progress · 2026-10-25 · [#1267](https://github.com/deeplethe/utopia/issues/1267) · decision 1 built (migration 0121) · open: decisions 2 to 4 - **Written**: 2026-10-16 (conventions in the [README](README.md)) - **Related**: [0037](0037-a-relation-carries-its-own-attributes.md) decided that a qualifier is not part of a fact's identity and that the first value stays; [0044](0044-the-ontology-is-a-view-over-what-documents-say.md) owns the open statement and the role words on it; [0054](0054-a-source-may-push-statements-in-the-open-contract.md) decision 7 is the re-push that supersedes a chunk; migration `0061` created `statement_qualifiers`; [0048](0048-provenance-references-stay-inside-the-knowledge-base.md) gets one more edge to keep inside the base; [0019](0019-the-second-clock-can-be-rewound.md) is the record axis `as_of` reads on; [#1267](https://github.com/deeplethe/utopia/issues/1267), [#1272](https://github.com/deeplethe/utopia/issues/1272) @@ -24,6 +24,8 @@ Three facts of the code make it so: The backfill copies each existing `(fact, role)` value onto every evidence chunk of its fact, superseded ones included. Attaching it only to the earliest chunk would hide role words that show today: for a statement already re-pushed under 0054 decision 7, the earliest chunk is superseded, the live chunk carries no row because `DO NOTHING` dropped it, and under decision 2 the role would disappear. With the value on every chunk, every read after the migration returns exactly what it returned before; only the pushes that follow can change a value. +*Revised with migration 0121 (2026-10-30).* As first written this decision put each role word on every evidence chunk of its fact. That holds for open statements. A typed row can have several source statements, and their chunks are all its evidence, so copying a value onto all of them would let a statement speak for a value it never said. A typed row takes a role word only on the chunk of a source statement that said the same value; the migration falls back to every evidence chunk only when no source gave that value. At runtime `materialize` copies onto a typed row only the roles the row does not have yet: a statement that merges in brings its new roles, and a different value for a role the row already has stays on the statement, or the row would read two. Bringing the other values across is decision 4. + `chunk_id` is a new provenance edge, and 0048's invariant covers it: the owner-derived trigger `statement_qualifiers_same_kb` checks that the chunk's document is in the fact's base, and the export preflight scans the edge. **2. A superseded chunk stops speaking for the statement.** diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 564febbf8..10a3051e0 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -75,7 +75,7 @@ By domain; the domains are the files of [../design/](../design/README.md). **Sta | 0010 | [An unnamed relation stays empty](0010-no-relation-is-no-relation.md) | Implemented | partly (by 0044) | | 0037 | [A relation carries its own attributes](0037-a-relation-carries-its-own-attributes.md) | In progress | partly (by 0044) | | 0048 | [Provenance references stay inside the knowledge base](0048-provenance-references-stay-inside-the-knowledge-base.md) | Implemented | | -| 0070 | [A role word speaks while its chunk is live](0070-a-role-word-speaks-while-its-chunk-is-live.md) | Proposed | | +| 0070 | [A role word speaks while its chunk is live](0070-a-role-word-speaks-while-its-chunk-is-live.md) | In progress | | ### [governance](../design/governance.md) diff --git a/docs/design/ledger.md b/docs/design/ledger.md index 34b908222..ab78135d3 100644 --- a/docs/design/ledger.md +++ b/docs/design/ledger.md @@ -30,8 +30,8 @@ by itself: the temporal engine reads the chunk's origin and opens a `described_e instead of closing a correct fact [0040 d4, 0045 cut 3]. Its confidence is also capped below the review threshold, which is what puts it in front of a person. -**Beside the row.** `statement_qualifiers (fact, role, value | entity)` keyed by the document's role -word for open statements; `fact_qualifiers (fact, qualifier_type, value | entity)` keyed by a +**Beside the row.** `statement_qualifiers (fact, role, chunk, value | entity)` keyed by the document's +role word and the chunk that says it, for open statements [0070]; `fact_qualifiers (fact, qualifier_type, value | entity)` keyed by a declared attribute for typed rows, converted by the attribute's datatype, the unit read from the text (`$4 billion` becomes 4000000000 with unit `$`) and the declared unit only when the text carries none; a qualifier is not part of the edge's identity; every superseding writer copies diff --git a/migrations/0121_a_role_word_is_recorded_against_its_chunk.sql b/migrations/0121_a_role_word_is_recorded_against_its_chunk.sql new file mode 100644 index 000000000..8b48c822d --- /dev/null +++ b/migrations/0121_a_role_word_is_recorded_against_its_chunk.sql @@ -0,0 +1,125 @@ +-- 角色词记在说它的那一块上(0070 决定 1,#1267)。 +-- +-- `statement_qualifiers` 从前按 (fact, role) 只留一行、先写者留着:同一个 external_id 重推、 +-- 值变了,新值被 `DO NOTHING` 丢掉。现在每条角色词带上说它的 `chunk_id`,主键变成 +-- (fact, role, chunk),新推的块写新行,旧行不动。 +-- +-- 回填分三步,先陈述、后由陈述推出的行: +-- 1. 开放陈述:每个 (fact, role) 的现值抄到它的每一块证据上,被取代的块也抄。 +-- 2. 类型化行与隐含行:从来源陈述(`typed_fact_sources`、`implied_fact_sources`)第 1 步 +-- 写下的逐块行里,挑出与这一行自己的值和实体都相同的,抄下它们落在这一行证据上的块。 +-- 于是另一条来源陈述的块不会替没说过这个词的陈述说话,说了别的值的来源也不会。 +-- 3. 剩下的(来源已经不在、或没有一条来源给过同样的值)照第 1 步抄到这一行的每一块证据上, +-- 今天读得到的角色词一个不丢。 +-- 每个 (fact, role) 只留下原来那一个值,所以迁移之后读出来的和之前一样。几条来源陈述对同一个 +-- 角色词给了不同的值时,类型化行仍只读它原来的值;别的值由 0070 决定 3 带过来。 +-- +-- 没有证据的事实:`documents::purge` 删掉块和证据、留下已失效的事实和它的角色词。这些行 +-- 没有块可挂,删掉并报数。**活着的**事实有角色词却没有证据,是账本坏了,整份中止。 +-- +-- `chunk_id` 是一条新的出处边(0048):触发器同时查块与事实同库,导出体检扫它。 + +-- §0 前置检查:活着的事实有角色词却没有证据 → 中止 +DO $$ +DECLARE + orphans bigint; +BEGIN + SELECT COUNT(DISTINCT q.fact_id) INTO orphans + FROM public.statement_qualifiers q + JOIN public.facts f ON f.id = q.fact_id + WHERE f.invalidated_at IS NULL + AND NOT EXISTS (SELECT 1 FROM public.fact_evidence e WHERE e.fact_id = q.fact_id); + IF orphans > 0 THEN + RAISE EXCEPTION 'live facts with role words and no evidence (x%) — repair the ledger before role words can move onto chunks', orphans; + END IF; +END; +$$; + +DROP TRIGGER statement_qualifiers_same_kb ON public.statement_qualifiers; + +ALTER TABLE public.statement_qualifiers + ADD COLUMN chunk_id uuid, + DROP CONSTRAINT statement_qualifiers_pkey; + +INSERT INTO public.statement_qualifiers (fact_id, role, value, entity_id, chunk_id) +SELECT q.fact_id, q.role, q.value, q.entity_id, e.chunk_id + FROM public.statement_qualifiers q + JOIN public.facts f ON f.id = q.fact_id AND f.layer = 'open' + JOIN public.fact_evidence e ON e.fact_id = q.fact_id + WHERE q.chunk_id IS NULL; + +-- 两条来源陈述在同一块上说了同一个值时只留一行 +INSERT INTO public.statement_qualifiers (fact_id, role, value, entity_id, chunk_id) +SELECT DISTINCT q.fact_id, q.role, q.value, q.entity_id, s.chunk_id + FROM public.statement_qualifiers q + JOIN (SELECT fact_id, statement_id FROM public.typed_fact_sources + UNION + SELECT fact_id, statement_id FROM public.implied_fact_sources + WHERE statement_id IS NOT NULL) src ON src.fact_id = q.fact_id + JOIN public.statement_qualifiers s + ON s.fact_id = src.statement_id AND s.role = q.role AND s.chunk_id IS NOT NULL + AND s.value IS NOT DISTINCT FROM q.value AND s.entity_id IS NOT DISTINCT FROM q.entity_id + JOIN public.fact_evidence e ON e.fact_id = q.fact_id AND e.chunk_id = s.chunk_id + WHERE q.chunk_id IS NULL; + +INSERT INTO public.statement_qualifiers (fact_id, role, value, entity_id, chunk_id) +SELECT q.fact_id, q.role, q.value, q.entity_id, e.chunk_id + FROM public.statement_qualifiers q + JOIN public.fact_evidence e ON e.fact_id = q.fact_id + WHERE q.chunk_id IS NULL + AND NOT EXISTS (SELECT 1 FROM public.statement_qualifiers n + WHERE n.fact_id = q.fact_id AND n.role = q.role AND n.chunk_id IS NOT NULL); + +DO $$ +DECLARE + dropped bigint; +BEGIN + DELETE FROM public.statement_qualifiers q + WHERE q.chunk_id IS NULL + AND NOT EXISTS (SELECT 1 FROM public.fact_evidence e WHERE e.fact_id = q.fact_id); + GET DIAGNOSTICS dropped = ROW_COUNT; + RAISE NOTICE 'dropped % role words on facts with no evidence', dropped; +END; +$$; + +DELETE FROM public.statement_qualifiers WHERE chunk_id IS NULL; + +ALTER TABLE public.statement_qualifiers + ALTER COLUMN chunk_id SET NOT NULL, + ADD CONSTRAINT statement_qualifiers_chunk_id_fkey + FOREIGN KEY (chunk_id) REFERENCES public.chunks(id) ON DELETE CASCADE, + ADD PRIMARY KEY (fact_id, role, chunk_id); + +-- 删块时级联要按块找 +CREATE INDEX statement_qualifiers_chunk_fk_idx ON public.statement_qualifiers (chunk_id); + +-- 实体值与块都必须与所属事实同库 +CREATE OR REPLACE FUNCTION public.squalifier_stays_inside_its_facts_kb() RETURNS trigger +LANGUAGE plpgsql SET search_path = pg_catalog AS $$ +DECLARE + fact_kb uuid; + ref_kb uuid; +BEGIN + SELECT kb_id INTO fact_kb FROM public.facts WHERE id = NEW.fact_id; + IF fact_kb IS NULL THEN + RETURN NEW; + END IF; + SELECT kb_id INTO ref_kb FROM public.chunks WHERE id = NEW.chunk_id; + IF ref_kb IS NOT NULL AND ref_kb <> fact_kb THEN + RAISE EXCEPTION 'statement qualifier chunk % cannot live outside the fact''s knowledge base', + NEW.chunk_id; + END IF; + IF NEW.entity_id IS NOT NULL THEN + SELECT kb_id INTO ref_kb FROM public.entities WHERE id = NEW.entity_id; + IF ref_kb IS NOT NULL AND ref_kb <> fact_kb THEN + RAISE EXCEPTION 'statement qualifier entity % cannot live outside the fact''s knowledge base', + NEW.entity_id; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER statement_qualifiers_same_kb + BEFORE INSERT OR UPDATE OF fact_id, entity_id, chunk_id ON public.statement_qualifiers + FOR EACH ROW EXECUTE FUNCTION public.squalifier_stays_inside_its_facts_kb(); From e964eb4fcefd251f0a3ac21d0b283cec1f0611b0 Mon Sep 17 00:00:00 2001 From: Rudy Mizrahi Celekli <47457359+rudycelekli@users.noreply.github.com> Date: Sat, 7 Nov 2026 21:47:26 -0500 Subject: [PATCH 13/13] A date written with "Sept." is read, so "Sept. 30, 2025" becomes 2025-09-30 instead of no value (#1430) Signed-off-by: Rudy Celekli Co-authored-by: WaylandYang <145302500+WaylandYang@users.noreply.github.com> --- crates/utopia-extract/src/lib.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/crates/utopia-extract/src/lib.rs b/crates/utopia-extract/src/lib.rs index 3039a9f34..f8f62c869 100644 --- a/crates/utopia-extract/src/lib.rs +++ b/crates/utopia-extract/src/lib.rs @@ -943,6 +943,12 @@ pub fn written_date(s: &str) -> Option<(NaiveDate, &'static str)> { if year.len() != 4 || day.is_some_and(|d| d.len() > 2) { return None; } + // 美联社写法把九月缩成四个字母的「Sept.」,chrono 的 `%b` 只认三个字母 + let month = if month.eq_ignore_ascii_case("sept") { + "Sep" + } else { + month + }; let month = ["%B", "%b"].iter().find_map(|f| { NaiveDate::parse_from_str(&format!("1 {month} 2000"), &format!("%d {f} %Y")) .ok() @@ -1385,6 +1391,25 @@ mod tests { ); } + #[test] + fn september_abbreviated_as_sept_is_read() { + use serde_json::json; + let day = |s: &str| normalize_attr_value("date", &json!(s)); + for written in [ + "Sept. 17, 2020", + "Sept 17, 2020", + "17 Sept. 2020", + "SEPT. 17, 2020", + ] { + assert_eq!(day(written), Some(json!("2020-09-17")), "{written}"); + } + assert_eq!(day("Sept. 2020"), Some(json!("2020-09"))); + assert_eq!( + read_time("Sept. 30, 2025").map(|(t, p)| (t.date_naive().to_string(), p)), + Some(("2025-09-30".to_string(), "day")) + ); + } + #[test] fn a_similarity_proposed_pair_says_so_in_the_prompt() { let side = |name: &str| AdjudicationSide {