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
78 changes: 77 additions & 1 deletion crates/utopia-server/src/namesake_decision_measurements.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ impl Fx {
governance: bool,
gold_same: bool,
reverse: bool,
extra_quote: Option<&str>,
) -> anyhow::Result<Value> {
let order = if reverse { [1, 0] } else { [0, 1] };
let mut holders = [Uuid::nil(); 2];
Expand Down Expand Up @@ -80,6 +81,33 @@ impl Fx {
.bind(self.chunks[i])
.execute(&self.pool)
.await?;
if let (0, Some(quote)) = (i, extra_quote) {
// 多条事实可以来自同一块,调查请求需要看到各自的原文。
let fact = Uuid::now_v7();
sqlx::query("UPDATE chunks SET text = text || ' ' || $1 WHERE id = $2")
.bind(quote)
.bind(self.chunks[i])
.execute(&self.pool)
.await?;
sqlx::query(
"INSERT INTO facts(id,kb_id,subject_id,layer,phrase,object_value,confidence)
VALUES ($1,$2,$3,'open','joined',$4,0.1)",
)
.bind(fact)
.bind(self.kb)
.bind(holders[i])
.bind(json!({"value":"the engineering lab"}))
.execute(&self.pool)
.await?;
utopia_store::graph::add_evidence(
&self.pool,
fact,
self.chunks[i],
Some(quote),
None,
)
.await?;
}
}
sqlx::query("UPDATE knowledge_bases SET governance=$1 WHERE id=$2")
.bind(governance)
Expand Down Expand Up @@ -320,7 +348,7 @@ async fn namesake_decision_measurements_have_only_the_named_gold_errors() -> any
};
let run = tokio::time::timeout(
Duration::from_secs(15),
f.measure_decision(path, governance, gold_same, reverse),
f.measure_decision(path, governance, gold_same, reverse, None),
)
.await;
f.cleanup().await?;
Expand Down Expand Up @@ -374,3 +402,51 @@ async fn namesake_decision_measurements_have_only_the_named_gold_errors() -> any
);
Ok(())
}

#[tokio::test]
async fn two_quotes_from_one_chunk_reach_the_adjudication_request() -> anyhow::Result<()> {
let Some(url) = utopia_store::test_db::url() else {
return Ok(());
};
let pool = sqlx::PgPool::connect(&url).await?;
let case = Case {
id: "quotes_from_one_chunk",
check: Check::Adjudicator { literal: true },
};
let quote = "Alex Lee joined the engineering lab.";
for governance in [false, true] {
let org = Uuid::now_v7();
let f = match Fx::new(&pool, &case, org).await {
Ok(f) => f,
Err(error) => {
sqlx::query("DELETE FROM organizations WHERE id=$1")
.bind(org)
.execute(&pool)
.await?;
return Err(error);
}
};
let result = tokio::time::timeout(
Duration::from_secs(15),
f.measure_decision(Path::Quotes, governance, false, false, Some(quote)),
)
.await;
f.cleanup().await?;
let row = result??;
let tool_results = row["tool_results"].as_array().unwrap();
let passages = tool_results
.iter()
.find(|result| result["side"] == "A")
.and_then(|result| result["content"].as_str())
.ok_or_else(|| {
anyhow::anyhow!(
"missing Record A quotes in the actual model request (governance={governance})"
)
})?;
anyhow::ensure!(
passages.contains(&format!("[directory-0.txt] {quote}")),
"missing second passage from the same chunk (governance={governance}): {passages}"
);
}
Ok(())
}
25 changes: 19 additions & 6 deletions crates/utopia-store/src/governance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -768,17 +768,24 @@ pub async fn loop_calls_today(pool: &PgPool, kb_id: Uuid) -> AppResult<i64> {
/// **名字事实排在后面,引文就是名字本身的不要**(0041)。名字事实置信度 1.0,
/// 按置信度排它每块都赢,而「这一块写了它的名字」的引文往往只是那个名字——
/// 给裁决的 agent 一串光秃秃的名字,等于没给原文。带整句引文的别名(「简称海探1」)
/// 照样留着,那正是判断是不是一个东西要看的
/// 照样留着,那正是判断是不是一个东西要看的。
///
/// 同块的不同引文不能去重成一条:获奖段落中两条陈述共用一个名字时,按块去重
/// 只给裁决器管理奖那句,技术奖那句永远读不到。按块和引文去重重复事实,先给各块
/// 一段再补后续段落,仍守调用方的条数上限,避免长块独占全部来源。
pub async fn quotes_of(
pool: &PgPool,
kb_id: Uuid,
entity_id: Uuid,
limit: i64,
) -> AppResult<Vec<(String, String)>> {
let rows: Vec<(String, String)> = sqlx::query_as(
"SELECT filename, quote FROM (
SELECT DISTINCT ON (fe.chunk_id) d.filename,
COALESCE(NULLIF(fe.quote, ''), left(c.text, 240)) AS quote
"WITH passages AS (
SELECT DISTINCT ON (fe.chunk_id, COALESCE(NULLIF(fe.quote, ''), left(c.text, 240)))
fe.chunk_id, d.filename,
COALESCE(NULLIF(fe.quote, ''), left(c.text, 240)) AS quote,
coalesce(r.builtin AND r.key = 'known_as', false) AS is_name,
f.confidence
FROM facts f
-- 谓词可以为空(0010),LEFT JOIN 才不丢那些事实
LEFT JOIN relation_types r ON r.id = f.predicate_id
Expand All @@ -789,8 +796,14 @@ pub async fn quotes_of(
AND (f.subject_id = $2 OR f.object_id = $2)
AND NOT (coalesce(r.builtin AND r.key = 'known_as', false)
AND lower(trim(coalesce(fe.quote, ''))) = lower(f.object_value->>'value'))
ORDER BY fe.chunk_id, coalesce(r.builtin AND r.key = 'known_as', false), f.confidence DESC
) q
ORDER BY fe.chunk_id, quote, is_name, f.confidence DESC, f.id
), ranked AS (
SELECT *, row_number() OVER (
PARTITION BY chunk_id ORDER BY is_name, confidence DESC, quote
) AS within_chunk FROM passages
)
SELECT filename, quote FROM ranked
ORDER BY is_name, within_chunk, chunk_id, quote
LIMIT $3",
)
.bind(kb_id)
Expand Down
62 changes: 61 additions & 1 deletion crates/utopia-store/tests/store/a_name_is_a_fact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,8 @@ async fn a_bare_name_is_not_a_quote_and_a_deleted_document_keeps_the_name() -> a
.map(|(_, q)| q)
.collect();
assert!(quotes.iter().all(|q| q != "海洋探测器1号"), "{quotes:?}");
assert_eq!(quotes.len(), 1, "一块一段:{quotes:?}");
assert_eq!(quotes.len(), 2, "同一块的不同句子都保留:{quotes:?}");
assert_eq!(quotes[1], "简称海探1", "名字证据仍排在普通事实之后");
assert_eq!(quotes[0], "于2026年下水", "同一块里真正的句子优先");

utopia_store::documents::delete(&pool, f.kb, doc, None).await?;
Expand All @@ -435,3 +436,62 @@ async fn a_bare_name_is_not_a_quote_and_a_deleted_document_keeps_the_name() -> a
teardown(&pool, &f).await?;
run
}

/// 一块里的第二句话不能被第一句话挤掉;重复事实不能挤掉别的来源。
#[tokio::test]
async fn distinct_quotes_in_one_chunk_survive_without_duplicate_facts_using_the_budget(
) -> anyhow::Result<()> {
let Some(url) = utopia_store::test_db::url() else {
return Ok(());
};
let pool = PgPool::connect(&url).await?;
for reverse in [false, true] {
let f = seed(&pool).await?;
let run = async {
let person = mention(&pool, &f, "Alex Lee").await?.entity_id;
let other = mention(&pool, &f, "Another Person").await?.entity_id;
let quotes = ["Alex Lee received the management award.",
"Alex Lee received the engineering award."];
let mut first_chunk = Uuid::nil();
for index in 0..7 {
let (doc, chunk) = (Uuid::now_v7(), Uuid::now_v7());
sqlx::query("INSERT INTO documents(id,kb_id,filename,sha256) VALUES ($1,$2,$3,$4)")
.bind(doc).bind(f.kb).bind(format!("source-{index}.txt"))
.bind(doc.to_string()).execute(&pool).await?;
let text = if index == 0 { quotes.join(" ") } else { format!("Source {index} mentions Alex Lee.") };
sqlx::query("INSERT INTO chunks(id,kb_id,document_id,seq,text) VALUES ($1,$2,$3,0,$4)")
.bind(chunk).bind(f.kb).bind(doc).bind(&text).execute(&pool).await?;
if index == 0 { first_chunk = chunk; }
let count = if index == 0 { 4 } else { 1 };
for n in if reverse { (0..count).rev().collect::<Vec<_>>() } else { (0..count).collect() } {
let fact = Uuid::now_v7();
// 两句各由两条事实引用,第二句还覆盖实体作为宾语的读取。
let object_side = index == 0 && n % 2 == 1;
sqlx::query("INSERT INTO facts(id,kb_id,subject_id,object_id,layer,phrase,confidence) VALUES ($1,$2,$3,$4,'open','mentions',0.9)")
.bind(fact).bind(f.kb).bind(if object_side { other } else { person })
.bind(if object_side { person } else { other })
.execute(&pool).await?;
graph::add_evidence(&pool, fact, chunk,
Some(if index == 0 { quotes[n % 2] } else { &text }), None).await?;
}
}
let stale = Uuid::now_v7();
sqlx::query("INSERT INTO facts(id,kb_id,subject_id,layer,phrase,object_value,invalidated_at) VALUES ($1,$2,$3,'open','stale','{\"value\":\"old\"}'::jsonb,now())")
.bind(stale).bind(f.kb).bind(person).execute(&pool).await?;
graph::add_evidence(&pool, stale, first_chunk, Some("obsolete evidence"), None).await?;
let all = utopia_store::governance::quotes_of(&pool, f.kb, person, 20).await?;
assert_eq!(all.len(), 8, "不同引文保留,重复和作废事实不增加条目:{all:?}");
for q in quotes { assert_eq!(all.iter().filter(|(_, quote)| quote == q).count(), 1); }
let limited = utopia_store::governance::quotes_of(&pool, f.kb, person, 6).await?;
assert_eq!(limited.len(), 6);
let sources: std::collections::HashSet<_> = limited.iter().map(|(doc, _)| doc).collect();
assert_eq!(sources.len(), 6, "先分配各块第一段,不能让一个长块耗尽预算");
assert_eq!(limited, utopia_store::governance::quotes_of(&pool, f.kb, person, 6).await?, "同分时顺序也稳定");
assert!(utopia_store::governance::quotes_of(&pool, Uuid::now_v7(), person, 6).await?.is_empty());
anyhow::Ok(())
}.await;
teardown(&pool, &f).await?;
run?;
}
Ok(())
}
Loading