Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/utopia-core/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -676,6 +676,8 @@ pub struct StatementQualifier {
pub value: Option<serde_json::Value>,
pub entity_id: Option<Uuid>,
pub entity_name: Option<String>,
/// 说这个值的那几块(0070):两块活着的块说法不同,各自一条
pub chunk_ids: Vec<Uuid>,
}

/// 一次 OWL 导入的记录。原文按内容寻址存在 blob 里,这行只是账。
Expand Down
3 changes: 2 additions & 1 deletion crates/utopia-server/src/api/mcp_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1028,7 +1028,8 @@ async fn entity_facts_reads_back_a_statements_role_words() -> anyhow::Result<()>
.unwrap();
assert_eq!(
fact["statement_qualifiers"],
json!([{"role":"lines","value":{"value":"10-42"},"entity_id":null,"entity_name":null}])
json!([{"role":"lines","value":{"value":"10-42"},"entity_id":null,"entity_name":null,
"chunk_ids":[f.chunk]}])
);
f.clean().await
}
Expand Down
36 changes: 36 additions & 0 deletions crates/utopia-server/src/api/sources_statements_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,42 @@ async fn a_second_push_under_the_same_identity_updates_in_place() -> anyhow::Res
f.cleanup().await
}

/// 0070 的例子:再推一次把 `lines` 从 40-52 改成 58-70,读回来只有新的范围
#[tokio::test]
async fn a_re_push_that_moves_lines_to_58_70_reads_back_only_58_70() -> anyhow::Result<()> {
let Some(f) = Fixture::new().await? else {
return Ok(());
};
for lines in ["40-52", "58-70"] {
let mut body = observation("08:14:03", "kitchen table");
body["s"][0][5] = json!({ "lines": lines });
let (status, body) = f.push(f.source, &f.token, &body).await?;
assert_eq!(status, StatusCode::OK, "{body}");
let doc = documents::find_by_external_key(&f.pool, f.source, "statements:obs-000412")
.await?
.expect("the push has a document");
crate::pipeline::process_document(&f.state, doc.id).await?;
let proposer = Proposer {
user_id: None,
token_id: None,
};
crate::extraction::extract_document(&f.state, doc.id, proposer).await?;
}
let (cup,): (Uuid,) =
sqlx::query_as("SELECT id FROM entities WHERE kb_id = $1 AND canonical_name = 'cup-7'")
.bind(f.kb)
.fetch_one(&f.pool)
.await?;
let (_, facts) = utopia_store::graph::entity_detail(&f.pool, f.kb, cup, None, None).await?;
let said: Vec<_> = facts
.iter()
.flat_map(|x| &x.statement_qualifiers)
.map(|q| (q.role.as_str(), q.value.clone()))
.collect();
assert_eq!(said, vec![("lines", Some(json!("58-70")))]);
f.cleanup().await
}

/// 门口的拒绝走到 HTTP 是 422(`AppError::Validation`,与 `api` 推送被拒时同一个码),
/// 并且这次推送留在 run 历史里;`api` 来源不认这条路由(404),钥匙不对是 401
#[tokio::test]
Expand Down
39 changes: 27 additions & 12 deletions crates/utopia-store/src/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,10 +237,11 @@ pub async fn add_statement_qualifier(
}

/// 一批开放陈述各自的角色词属性,按事实 id 取回;实体那一格连上显示名。
/// 同一个值记在几块上只返回一次
/// 只取 `as_of` 时刻说话的行(0070 决定 2、3);同一个值记在几块上返回一次,带上那几块
pub async fn statement_qualifiers_for(
pool: &PgPool,
fact_ids: &[Uuid],
as_of: Option<chrono::DateTime<chrono::Utc>>,
) -> AppResult<HashMap<Uuid, Vec<StatementQualifier>>> {
let mut out: HashMap<Uuid, Vec<StatementQualifier>> = HashMap::new();
if fact_ids.is_empty() {
Expand All @@ -253,23 +254,37 @@ pub async fn statement_qualifiers_for(
value: Option<serde_json::Value>,
entity_id: Option<Uuid>,
entity_name: Option<String>,
chunk_ids: Vec<Uuid>,
}
let rows: Vec<Row> = sqlx::query_as(
"SELECT DISTINCT q.fact_id, q.role, q.value, q.entity_id, e.canonical_name AS entity_name
let as_of_param = as_of.map(|_| 2);
let sql = format!(
"WITH rw_f AS (SELECT rw_ee.fact_id, {ends} FROM {evidence}
WHERE rw_ee.fact_id = ANY($1) GROUP BY rw_ee.fact_id)
SELECT q.fact_id, q.role, q.value, q.entity_id, e.canonical_name AS entity_name,
array_agg(q.chunk_id ORDER BY q.chunk_id) AS chunk_ids
FROM statement_qualifiers q
LEFT JOIN rw_f ON rw_f.fact_id = q.fact_id
JOIN chunks rw_c ON rw_c.id = q.chunk_id
JOIN documents rw_d ON rw_d.id = rw_c.document_id
LEFT JOIN entities e ON e.id = q.entity_id
WHERE q.fact_id = ANY($1)
ORDER BY q.fact_id, q.role",
)
.bind(fact_ids)
.fetch_all(pool)
.await?;
for r in rows {
WHERE q.fact_id = ANY($1) AND {speaks}
GROUP BY q.fact_id, q.role, q.value, q.entity_id, e.canonical_name
ORDER BY q.fact_id, q.role, chunk_ids",
ends = crate::record_axis::role_word_fact_ends(as_of_param),
evidence = crate::record_axis::ROLE_WORD_EVIDENCE,
speaks = crate::record_axis::role_word_speaks_given("rw_c", "rw_d", "rw_f", as_of_param),
);
let mut query = sqlx::query_as::<_, Row>(&sql).bind(fact_ids);
if let Some(at) = as_of {
query = query.bind(at);
}
for r in query.fetch_all(pool).await? {
out.entry(r.fact_id).or_default().push(StatementQualifier {
role: r.role,
value: r.value,
entity_id: r.entity_id,
entity_name: r.entity_name,
chunk_ids: r.chunk_ids,
});
}
Ok(out)
Expand Down Expand Up @@ -1519,7 +1534,7 @@ async fn edges_among(
let ids: Vec<Uuid> = edges.iter().map(|x| x.id).collect();
let (mut typed, mut worded) = tokio::try_join!(
fact_qualifiers_for(pool, &ids),
statement_qualifiers_for(pool, &ids)
statement_qualifiers_for(pool, &ids, as_of)
)?;
for x in edges.iter_mut() {
x.qualifiers = typed.remove(&x.id).unwrap_or_default();
Expand Down Expand Up @@ -1868,7 +1883,7 @@ pub async fn entity_detail(
let ids: Vec<Uuid> = facts.iter().map(|x| x.id).collect();
let (mut typed, mut worded) = tokio::try_join!(
fact_qualifiers_for(pool, &ids),
statement_qualifiers_for(pool, &ids)
statement_qualifiers_for(pool, &ids, as_of)
)?;
for x in facts.iter_mut() {
x.qualifiers = typed.remove(&x.id).unwrap_or_default();
Expand Down
21 changes: 15 additions & 6 deletions crates/utopia-store/src/materialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,8 +208,8 @@ async fn materialize_in_tx(
AND b.relation_type_id = t.predicate_id
AND ((b.direction = 'forward' AND t.subject_id = s.subject_id)
OR (b.direction = 'reverse' AND t.subject_id = s.object_id))
AND NOT EXISTS (SELECT 1 FROM statement_qualifiers q
WHERE q.fact_id = s.id AND q.role = 'mood'))"
AND {NO_MOOD})",
NO_MOOD = no_mood_spoken(),
))
.persistent(false)
.bind(kb_id)
Expand Down Expand Up @@ -274,16 +274,16 @@ async fn materialize_in_tx(
WHERE s.kb_id = $1 AND s.layer = 'open' AND s.invalidated_at IS NULL
AND b.status = 'bound'
AND (b.direction = 'forward' OR s.object_id IS NOT NULL)
AND NOT EXISTS (SELECT 1 FROM statement_qualifiers q
WHERE q.fact_id = s.id AND q.role = 'mood')
AND {NO_MOOD}
-- 勘误撤过的(陈述, 属性)不再算(0044 决定 7):撤销要站得住
AND NOT EXISTS (SELECT 1 FROM errata_actions ea
WHERE ea.statement_id = s.id AND ea.predicate_id = b.relation_type_id
AND ea.status = 'applied' AND ea.action IN ('retract', 'revise'))
AND NOT EXISTS (SELECT 1 FROM typed_fact_sources src JOIN facts t ON t.id = src.fact_id
WHERE src.statement_id = s.id AND t.invalidated_at IS NULL
AND t.predicate_id = b.relation_type_id)
ORDER BY s.id"
ORDER BY s.id",
NO_MOOD = no_mood_spoken(),
))
.persistent(false)
.bind(kb_id)
Expand Down Expand Up @@ -562,7 +562,7 @@ async fn imply_in_tx(
AND pr.reading = r.reading AND pr.phrase = {TEXT}
WHERE r.kb_id = $1 AND r.status = 'approved' AND r.trigger = 'phrase'
AND {RULE_MATCH}
AND NOT EXISTS (SELECT 1 FROM statement_qualifiers q WHERE q.fact_id = s.id AND q.role = 'mood')
AND {NO_MOOD}
AND (r.reading IS NULL OR pr.entity_id IS NOT NULL OR pr.value IS NOT NULL)
AND NOT EXISTS (SELECT 1 FROM errata_actions ea
WHERE ea.statement_id = s.id AND ea.predicate_id = r.conclude_property_id
Expand All @@ -572,6 +572,7 @@ async fn imply_in_tx(
ORDER BY s.id",
TEXT = crate::implication_rules::object_text_sql(),
RULE_MATCH = crate::implication_rules::RULE_MATCH,
NO_MOOD = no_mood_spoken(),
))
.persistent(false)
.bind(kb_id)
Expand Down Expand Up @@ -835,6 +836,14 @@ fn attribute_value(raw: &Value, datatype: Option<&str>, unit: Option<&str>) -> O
Some(out)
}

/// 陈述 `s` 没有一个说着话的 `mood`(0070 决定 2):重推丢掉了 mood,旧块上的 mood 就不再拦着
fn no_mood_spoken() -> String {
format!(
"NOT EXISTS (SELECT 1 FROM statement_qualifiers q WHERE q.fact_id = s.id AND q.role = 'mood' AND {})",
crate::record_axis::role_word_speaks_now("q")
)
}

/// 类别词的归一(同 type_bindings):这里要在 SQL 里对上实体的 specific_type
fn kind_word_sql(col: &str) -> String {
format!("lower(btrim(regexp_replace({col}, '\\s+', ' ', 'g')))")
Expand Down
55 changes: 55 additions & 0 deletions crates/utopia-store/src/record_axis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,61 @@ pub fn chunk_live_at(alias: &str, as_of: Option<usize>) -> String {
}
}

/// 一条事实的证据,选成 `rw_ee`(证据)、`rw_ec`(块)、`rw_ed`(文档),供 [`role_word_fact_ends`] 聚合
pub const ROLE_WORD_EVIDENCE: &str = "fact_evidence rw_ee
JOIN chunks rw_ec ON rw_ec.id = rw_ee.chunk_id
JOIN documents rw_ed ON rw_ed.id = rw_ec.document_id";

/// 按事实聚合 [`ROLE_WORD_EVIDENCE`]:T 时刻有没有活块(`any_live`),T 时刻已有的块里
/// 最晚的终点(`last_end`)。块的终点是 `superseded_at` 与文档 `deleted_at` 里早的那个
pub fn role_word_fact_ends(as_of: Option<usize>) -> String {
format!(
"bool_or({} AND {}) AS any_live,
max(least(rw_ec.superseded_at, rw_ed.deleted_at)) FILTER (WHERE {}) AS last_end",
chunk_live_at("rw_ec", as_of),
document_live_at("rw_ed", as_of),
chunk_existed_at("rw_ec", as_of),
)
}

fn chunk_existed_at(alias: &str, as_of: Option<usize>) -> String {
match as_of {
None => "true".into(),
Some(param) => format!("{alias}.created_at <= coalesce(${param}, now())"),
}
}

/// 角色词在 T 时刻替它的事实说话吗(0070 决定 2、3),给定它那块 `c`、那块的文档 `d`
/// 和它事实的 [`role_word_fact_ends`] 一行 `f`。
///
/// 它那块与那块的文档在 T 时刻都还活着,就说话;活着的几块值不同,都说话。
/// 事实在 T 时刻一块活证据都没有时,最后到头的那几块说话(同一时刻到头的都算),
/// 只看 T 时刻已有的块。每条事实的证据只聚合一次:重推几百次的陈述不按行重扫
pub fn role_word_speaks_given(c: &str, d: &str, f: &str, as_of: Option<usize>) -> String {
format!(
"(({c_live} AND {d_live})
OR (NOT {f}.any_live AND {existed}
AND least({c}.superseded_at, {d}.deleted_at) = {f}.last_end))",
c_live = chunk_live_at(c, as_of),
d_live = document_live_at(d, as_of),
existed = chunk_existed_at(c, as_of),
)
}

/// `statement_qualifiers`:这一行 `q` 此刻说话吗,[`role_word_speaks_given`] 的单行形状。
/// 只在写入口用,所以不带 T;别名都带 `rw_` 前缀,不和调用方的撞
pub fn role_word_speaks_now(q: &str) -> String {
format!(
"EXISTS (SELECT 1 FROM chunks rw_c JOIN documents rw_d ON rw_d.id = rw_c.document_id
CROSS JOIN LATERAL (SELECT {ends} FROM {evidence}
WHERE rw_ee.fact_id = {q}.fact_id) rw_f
WHERE rw_c.id = {q}.chunk_id AND {speaks})",
ends = role_word_fact_ends(None),
evidence = ROLE_WORD_EVIDENCE,
speaks = role_word_speaks_given("rw_c", "rw_d", "rw_f", None),
)
}

/// `entity_merges`:这次合并在 T 时刻**生效着**吗(0019 第二刀 / #336)。
///
/// 实体身上没有记录轴——`merged_into` 只说合并发生过,不说何时。时刻在这张表上,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
//! place) 绑到 headquartered_in:算出一条类型化行,谓词是它,证据与限定抄过来,
//! `from_statement_id` 指回陈述;再跑一遍什么都不动;带 mood 的陈述不算;另一份文档
//! 的同一句并进同一行(两条来源、两条证据),它说的另一个 since 不跟进来,行只读建行那条的,它说的 until 行还没有、跟进来;作废其中一条陈述,行还在、来源少一条;
//! 绑定翻成 reverse,旧行作废、新行主宾对调;绑定改成 none,行作废、不再补。
//! 绑定翻成 reverse,旧行作废、新行主宾对调;绑定改成 none,行作废、不再补;
//! 带 mood 的陈述重推、新块不再说 mood,就成一行。
//!
//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。

Expand Down Expand Up @@ -287,6 +288,15 @@ async fn a_bound_statement_becomes_a_typed_fact() -> anyhow::Result<()> {
.await?;
assert_eq!(materialize(&pool, kb).await?, Outcome { retired: 1, added: 0, merged: 0, implied: 0, corrected: 0, conflicts: 0 });
assert_eq!(utopia_store::materialize::count(&pool, kb).await?, 0);

// 带 mood 的那条重推、新块不再说 mood:旧块上的 mood 不再拦着,它成一行(0070 决定 2)
sqlx::query("UPDATE chunks SET superseded_at = now() WHERE id = $1")
.bind(planned_chunk)
.execute(&pool)
.await?;
evidence_of(planned, "bakery-plan-2.txt").await?;
assert_eq!(materialize(&pool, kb).await?.added, 1);
assert_eq!(utopia_store::materialize::count(&pool, kb).await?, 1);
anyhow::Ok(())
}
.await;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,10 +208,11 @@ async fn role_words_move_onto_every_evidence_chunk_and_leave_a_purged_fact() ->
expected,
"每块证据一行,没有证据的已失效事实一行不留"
);
let read = utopia_store::graph::statement_qualifiers_for(&pool, &[stated]).await?;
let read = utopia_store::graph::statement_qualifiers_for(&pool, &[stated], None).await?;
assert_eq!(
serde_json::to_value(&read[&stated])?,
serde_json::json!([{ "role": "lines", "value": "40-52", "entity_id": null, "entity_name": null }])
serde_json::json!([{ "role": "lines", "value": "40-52", "entity_id": null,
"entity_name": null, "chunk_ids": [ledger.live_chunk] }])
);
pool.close().await;
drop_scratch(&name).await;
Expand Down
Loading
Loading