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: 1 addition & 1 deletion crates/utopia-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 = 125;
const CURRENT_SCHEMA_VERSION: u32 = 126;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
Expand Down
23 changes: 18 additions & 5 deletions crates/utopia-extract/src/open.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ pub struct OpenEntity {
pub kind: String,
/// 原文点了名(true)还是只描述了(false)
pub named: bool,
/// where it stood in the reply's `e` array; a malformed or repeated neighbour is dropped
pub raw_index: usize,
}

#[derive(Debug, Clone)]
Expand All @@ -78,6 +80,9 @@ pub struct OpenStatement {
pub ended: Option<String>,
/// the sentence of the passage that states it, verbatim
pub quote: Option<String>,
/// where it stood in the reply's `s` array; a malformed neighbour is dropped, so this is not
/// its position in `OpenExtraction::statements`
pub raw_index: usize,
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -546,7 +551,12 @@ fn parse_entity(arr: &[Value]) -> Option<OpenEntity> {
Some(Value::Number(n)) => n.as_f64() != Some(0.0),
_ => true,
};
Some(OpenEntity { name, kind, named })
Some(OpenEntity {
name,
kind,
named,
raw_index: 0,
})
}

/// `[quote, subject, phrase, object, value, qualifiers, when, ended]`。八格都得在:短了的
Expand All @@ -567,6 +577,7 @@ fn parse_statement(arr: &[Value]) -> Option<OpenStatement> {
when: opt_text(&arr[6]),
ended: opt_text(&arr[7]),
quote: opt_text(&arr[0]),
raw_index: 0,
})
}

Expand Down Expand Up @@ -611,15 +622,17 @@ pub fn parse_open_response(raw: &str) -> anyhow::Result<OpenExtraction> {
..Default::default()
};
let mut seen = HashSet::new();
for item in items(&value, "e") {
for (raw_index, item) in items(&value, "e").iter().enumerate() {
match item.as_array().and_then(|a| parse_entity(a)) {
Some(e) if seen.insert(name_key(&e.name)) => out.entities.push(e),
Some(e) if seen.insert(name_key(&e.name)) => {
out.entities.push(OpenEntity { raw_index, ..e })
}
_ => out.skipped += 1,
}
}
for item in items(&value, "s") {
for (raw_index, item) in items(&value, "s").iter().enumerate() {
match item.as_array().and_then(|a| parse_statement(a)) {
Some(s) => out.statements.push(s),
Some(s) => out.statements.push(OpenStatement { raw_index, ..s }),
None => out.skipped += 1,
}
}
Expand Down
76 changes: 76 additions & 0 deletions crates/utopia-server/src/api/sources_repush_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,79 @@ async fn a_repush_keeps_a_statement_another_item_still_states() -> anyhow::Resul
);
f.cleanup().await
}

#[tokio::test]
async fn an_extracted_item_remembers_the_fact_of_each_statement() -> anyhow::Result<()> {
let Some(f) = Fixture::new().await? else {
return Ok(());
};
let body = item(
"obs-1",
&[("is based in", "Port Ellen"), ("visited", "Oslo")],
);
let doc = push_and_extract(&f, &body, "created").await?;

let rows: Vec<(i32, String, String)> = sqlx::query_as(
"SELECT w.ord, w.key, f.phrase
FROM pushed_statement_writes w
JOIN chunks c ON c.id = w.chunk_id
JOIN facts f ON f.id = w.fact_id
WHERE c.document_id = $1 AND c.superseded_at IS NULL AND f.invalidated_at IS NULL
ORDER BY w.ord",
)
.bind(doc)
.fetch_all(&f.pool)
.await?;

let expected: Vec<(i32, String, String)> = body["s"]
.as_array()
.unwrap()
.iter()
.enumerate()
.map(|(ord, statement)| {
(
ord as i32,
serde_json::to_string(statement).unwrap(),
statement[2].as_str().unwrap().to_string(),
)
})
.collect();
assert_eq!(rows, expected);
f.cleanup().await
}

#[tokio::test]
async fn an_extracted_item_remembers_the_entity_of_each_name() -> anyhow::Result<()> {
let Some(f) = Fixture::new().await? else {
return Ok(());
};
let body = item("obs-1", &[("is based in", "Port Ellen")]);
let doc = push_and_extract(&f, &body, "created").await?;

let mut rows: Vec<(String, String)> = sqlx::query_as(
"SELECT h.key, e.canonical_name
FROM pushed_entity_handles h
JOIN chunks c ON c.id = h.chunk_id
JOIN entities e ON e.id = h.entity_id
WHERE c.document_id = $1 AND c.superseded_at IS NULL",
)
.bind(doc)
.fetch_all(&f.pool)
.await?;
rows.sort();

let mut expected: Vec<(String, String)> = body["e"]
.as_array()
.unwrap()
.iter()
.map(|entity| {
(
serde_json::to_string(entity).unwrap(),
entity[0].as_str().unwrap().to_string(),
)
})
.collect();
expected.sort();
assert_eq!(rows, expected);
f.cleanup().await
}
37 changes: 37 additions & 0 deletions crates/utopia-server/src/extraction_open.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,28 @@ async fn call_and_parse_one_chunk(
}))
}

/// 推送块里 `e` / `s` 两个数组的规范键,按原始位置排列(9012 的记忆键)
struct PushedRaw {
entities: Vec<String>,
statements: Vec<String>,
}

impl PushedRaw {
fn parse(chunk_text: &str) -> Self {
let payload: serde_json::Value = serde_json::from_str(chunk_text).unwrap_or_default();
let keys = |field: &str| -> Vec<String> {
payload[field]
.as_array()
.map(|items| items.iter().map(|item| item.to_string()).collect())
.unwrap_or_default()
};
Self {
entities: keys("e"),
statements: keys("s"),
}
}
}

/// 一个分块的后半步:把解析出来的回复写成陈述、名字和证据(#588 cut 1)。
///
/// **要按分块顺序跑**:前面的块认下的实体(`doc_entities`、`known_by_name`)、描述出来的
Expand Down Expand Up @@ -309,6 +331,7 @@ async fn apply_open_extraction(
let mut local: HashMap<String, Uuid> = HashMap::new();
// 被描述的东西:先记下名字和类别词,等陈述指到它再建(见 `place`)
let mut deferred: HashMap<String, (String, String)> = HashMap::new();
let pushed_raw = pushed.then(|| PushedRaw::parse(&chunk.text));
for e in &extraction.entities {
let name = e.name.trim();
if name.is_empty() {
Expand Down Expand Up @@ -360,6 +383,12 @@ async fn apply_open_extraction(
)
.await;
}
if let Some(key) = pushed_raw
.as_ref()
.and_then(|raw| raw.entities.get(e.raw_index))
{
utopia_store::pushed_memo::remember_entity(pool, chunk.id, key, id).await?;
}
touched_names.insert(name_key(name));
if !doc_entities.iter().any(|(x, _, _)| *x == id) {
doc_entities.push((id, kind.to_string(), name.to_string()));
Expand All @@ -374,6 +403,7 @@ async fn apply_open_extraction(
}

// ---- 陈述 ----
// 推送来的陈述按原始位置记下它写出的事实:再推时没变的陈述可以直接沿用旧事实
for s in &extraction.statements {
let phrase = s.phrase.trim();
if phrase.is_empty() {
Expand Down Expand Up @@ -651,6 +681,13 @@ async fn apply_open_extraction(
confidence,
)
.await?;
if let Some(key) = pushed_raw
.as_ref()
.and_then(|raw| raw.statements.get(s.raw_index))
{
utopia_store::pushed_memo::remember(pool, chunk.id, s.raw_index as i32, key, fact_id)
.await?;
}
// 表层谓词也写短语:今天的读路径都从 `fact_surface_predicate` 取名字
utopia_store::graph::add_evidence_located(
pool,
Expand Down
1 change: 1 addition & 0 deletions crates/utopia-store/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ pub mod palette;
pub mod paths;
pub mod pending;
pub mod phrase_bindings;
pub mod pushed_memo;
pub mod reasoning;
pub mod record_axis;
pub mod resolution;
Expand Down
46 changes: 46 additions & 0 deletions crates/utopia-store/src/pushed_memo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//! 推送来的陈述记住它写下的事实:块内位置 + 陈述的规范键 → 事实(9012)。

use sqlx::PgPool;
use uuid::Uuid;

use utopia_core::AppResult;

/// 记下块内第 `ord` 条陈述(规范键 `key`)写出的事实。
pub async fn remember(
pool: &PgPool,
chunk_id: Uuid,
ord: i32,
key: &str,
fact_id: Uuid,
) -> AppResult<()> {
sqlx::query(
"INSERT INTO pushed_statement_writes (chunk_id, ord, key, fact_id)
VALUES ($1, $2, $3, $4) ON CONFLICT (chunk_id, ord) DO NOTHING",
)
.bind(chunk_id)
.bind(ord)
.bind(key)
.bind(fact_id)
.execute(pool)
.await?;
Ok(())
}

/// 记下规范键 `key` 的具名实体对应的 entity_id。
pub async fn remember_entity(
pool: &PgPool,
chunk_id: Uuid,
key: &str,
entity_id: Uuid,
) -> AppResult<()> {
sqlx::query(
"INSERT INTO pushed_entity_handles (chunk_id, key, entity_id)
VALUES ($1, $2, $3) ON CONFLICT (chunk_id, key) DO NOTHING",
)
.bind(chunk_id)
.bind(key)
.bind(entity_id)
.execute(pool)
.await?;
Ok(())
}
20 changes: 20 additions & 0 deletions migrations/9012_a_pushed_statement_remembers_its_fact.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
-- A pushed statement remembers the fact it wrote: one row per (chunk, statement position), holding
-- the statement's canonical key and the fact it became, so a re-push can reuse the facts of the
-- statements it did not change, and, per named entity, the entity its entry resolved to. Running this again changes nothing.

CREATE TABLE IF NOT EXISTS pushed_statement_writes (
chunk_id UUID NOT NULL REFERENCES chunks(id) ON DELETE CASCADE,
ord INT NOT NULL,
key TEXT NOT NULL,
fact_id UUID NOT NULL REFERENCES facts(id) ON DELETE CASCADE,
PRIMARY KEY (chunk_id, ord)
);

CREATE INDEX IF NOT EXISTS pushed_statement_writes_fact ON pushed_statement_writes (fact_id);

CREATE TABLE IF NOT EXISTS pushed_entity_handles (
chunk_id UUID NOT NULL REFERENCES chunks(id) ON DELETE CASCADE,
key TEXT NOT NULL,
entity_id UUID NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
PRIMARY KEY (chunk_id, key)
);
Loading