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
4 changes: 4 additions & 0 deletions crates/utopia-server/src/extraction_open.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1246,6 +1246,10 @@ pub(crate) async fn run_open(
state.emit_review(kb_id);
}

// 身份来源(0071 决定 5):散文先写下的名字向量,这篇给了它身份证据,删掉
if identity {
utopia_store::name_vectors::drop_for_document(pool, document_id).await?;
}
// 名字向量:这篇新写的名字事实,向量补上(0041 决定 3 通道 2)。算不出来只记日志——
// 文档已经抽完了,不能因为召回的辅助数据没算而把它标成 failed
if let (Some(settings), Some(client)) = (settings, &embed) {
Expand Down
35 changes: 26 additions & 9 deletions crates/utopia-server/src/extraction_open_identity_names_tests.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
//! A statements source with `{"names": "identity"}` (0071) gets no embedding call and no
//! `name_vector|` pair. The fake endpoint returns one vector for every name.
//! `name_vector|` pair, and the name it pushes loses the vector prose gave it first. The fake
//! endpoint returns one vector for every name.
use super::*;
use axum::{routing::post, Json, Router};
use serde_json::{json, Value};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

/// Push `PUSHED` into a base holding `KNOWN` (with a name vector); answers (embedding calls, review reasons).
async fn push(config: Value) -> anyhow::Result<Option<(usize, Vec<String>)>> {
/// Push `PUSHED` and `KNOWN` into a base holding `KNOWN` (with a name vector); answers
/// (embedding calls, review reasons, whether `KNOWN` kept its vector).
async fn push(config: Value) -> anyhow::Result<Option<(usize, Vec<String>, bool)>> {
let Some(url) = utopia_store::test_db::url() else {
return Ok(None);
};
Expand All @@ -17,7 +19,7 @@ async fn push(config: Value) -> anyhow::Result<Option<(usize, Vec<String>)>> {
std::array::from_fn(|_| Uuid::now_v7());
let text = serde_json::to_string(&json!({
"external_id": "commit:identity",
"e": [[PUSHED, "SourceFile", true]],
"e": [[PUSHED, "SourceFile", true], [KNOWN, "SourceFile", true]],
"s": [[null, PUSHED, "path", null, "src/x.ts", null, null, null]],
"n": []
}))?;
Expand Down Expand Up @@ -90,6 +92,11 @@ async fn push(config: Value) -> anyhow::Result<Option<(usize, Vec<String>)>> {
.bind(kb)
.fetch_all(&pool)
.await?;
let known_kept: bool =
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM name_vectors WHERE fact_id = $1)")
.bind(fact)
.fetch_one(&pool)
.await?;

server.abort();
sqlx::query("DELETE FROM jobs WHERE payload->>'kb_id' = $1")
Expand All @@ -100,27 +107,37 @@ async fn push(config: Value) -> anyhow::Result<Option<(usize, Vec<String>)>> {
.bind(org)
.execute(&pool)
.await?;
Ok(Some((calls.load(Ordering::SeqCst), reasons)))
Ok(Some((calls.load(Ordering::SeqCst), reasons, known_kept)))
}

const KNOWN: &str = "re-cinq/lore:src/a.ts";
const PUSHED: &str = "re-cinq/lore:src/b.ts";

#[tokio::test]
async fn an_identity_source_adds_no_name_vectors_and_asks_no_neighbours() -> anyhow::Result<()> {
let Some(outcome) = push(json!({"names": "identity"})).await? else {
let Some((calls, reasons, _)) = push(json!({"names": "identity"})).await? else {
return Ok(());
};
assert_eq!(outcome, (0, Vec::<String>::new()));
assert_eq!((calls, reasons), (0, Vec::<String>::new()));
Ok(())
}

#[tokio::test]
async fn a_name_prose_gave_a_vector_loses_it_when_an_identity_source_pushes_it(
) -> anyhow::Result<()> {
let Some((_, _, known_kept)) = push(json!({"names": "identity"})).await? else {
return Ok(());
};
assert!(!known_kept);
Ok(())
}

#[tokio::test]
async fn a_statements_source_without_the_flag_still_proposes_by_name_vector() -> anyhow::Result<()>
{
let Some((calls, reasons)) = push(json!({})).await? else {
let Some((calls, reasons, known_kept)) = push(json!({})).await? else {
return Ok(());
};
assert!(calls > 0 && reasons.iter().any(|r| r.starts_with("name_vector|")));
assert!(calls > 0 && reasons.iter().any(|r| r.starts_with("name_vector|")) && known_kept);
Ok(())
}
69 changes: 61 additions & 8 deletions crates/utopia-store/src/name_vectors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,22 +25,44 @@ pub const TOP_K: usize = 8;
/// 0.4 上下的余弦——所以这条线比画像的 `SIM_ATTACH` 高。同样是待测量的临时值
pub const SIM_FLOOR: f32 = 0.60;

/// 名字事实 `$fact` 有身份来源的证据(0071 决定 4、5):这样的名字不留向量
macro_rules! has_identity_evidence {
($fact:literal) => {
concat!(
"EXISTS (SELECT 1 FROM fact_evidence fe
JOIN documents d ON d.id = fe.document_id
JOIN sources s ON s.id = d.source_id
WHERE fe.fact_id = ",
$fact,
" AND s.kind = 'statements' AND s.config->>'names' = 'identity')"
)
};
}

/// `known_as` 的 id 用子查询取,不要改回 JOIN:子查询先算出一个值,`predicate_id = 它` 才成了
/// `facts_live_predicate_idx`(0115)的索引条件,扫描只碰这个库的名字事实,且仍按 id 走,
/// `ORDER BY ... LIMIT` 不用排序。写成 JOIN,规划器沿 `facts_kb_id_key` 把整个库按 id 读一遍,
/// 谓词只能逐行筛(#1296:20 万条事实的库上读 20 万行,这样读 2 万行)
const PENDING_SQL: &str = "SELECT f.id, f.subject_id, f.object_value->>'value'
///
/// 有身份来源证据的名字不补向量,哪怕散文也提到它(0071 决定 4、5)
const PENDING_SQL: &str = concat!(
"SELECT f.id, f.subject_id, f.object_value->>'value'
FROM facts f
LEFT JOIN name_vectors v ON v.fact_id = f.id
WHERE f.kb_id = $1
AND f.predicate_id = (SELECT nr.id FROM relation_types nr
WHERE nr.kb_id = $1 AND nr.builtin AND nr.key = $2)
AND f.invalidated_at IS NULL AND f.object_value IS NOT NULL
AND v.fact_id IS NULL
AND NOT ",
has_identity_evidence!("f.id"),
"
ORDER BY f.id
LIMIT $3";
LIMIT $3"
);

/// 还没有向量的名字事实:现行的、`known_as` 上的、`name_vectors` 里没有它的。
/// 还没有向量的名字事实:现行的、`known_as` 上的、`name_vectors` 里没有它的、
/// 没有身份来源证据的。
/// 按写入先后取(`facts.id` 是 uuid v7,按它排即按写入排;这张表没有 created_at——
/// 端到端跑出来的:按一个不存在的列排,补向量每篇都静默失败),一次取一批
pub async fn pending(
Expand All @@ -57,19 +79,50 @@ pub async fn pending(
Ok(rows)
}

/// 来源刚开了身份名(0071 决定 6):删掉有它文档证据的名字向量,与改配置同一个事务
pub async fn drop_for_source(
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
source_id: Uuid,
) -> AppResult<()> {
sqlx::query(
"DELETE FROM name_vectors v
USING fact_evidence fe JOIN documents d ON d.id = fe.document_id
WHERE fe.fact_id = v.fact_id AND d.source_id = $1",
)
.bind(source_id)
.execute(&mut **tx)
.await?;
Ok(())
}

/// 身份来源的文档抽完(0071 决定 5):散文先写下的名字向量,这篇给了它身份证据就删
pub async fn drop_for_document(pool: &PgPool, document_id: Uuid) -> AppResult<()> {
sqlx::query(
"DELETE FROM name_vectors v USING fact_evidence fe
WHERE fe.fact_id = v.fact_id AND fe.document_id = $1",
)
.bind(document_id)
.execute(pool)
.await?;
Ok(())
}

/// 写一批名字向量:`(fact_id, entity_id, embedding)`。同一条事实重写就覆盖(换了模型
/// 重算)。第一次写下这个维度的向量,索引就该排上了(0035)
/// 重算)。第一次写下这个维度的向量,索引就该排上了(0035)。
/// 写的时候再查一次身份证据:补向量算到一半,来源开了身份名或身份文档抽完删过一轮,
/// 这里不能把它写回去
pub async fn set(pool: &PgPool, kb_id: Uuid, items: &[(Uuid, Uuid, Vec<f32>)]) -> AppResult<()> {
if items.is_empty() {
return Ok(());
}
let mut tx = pool.begin().await?;
for (fact_id, entity_id, emb) in items {
sqlx::query(
sqlx::query(concat!(
"INSERT INTO name_vectors (fact_id, kb_id, entity_id, embedding)
VALUES ($1, $2, $3, $4)
ON CONFLICT (fact_id) DO UPDATE SET embedding = EXCLUDED.embedding",
)
SELECT $1::uuid, $2::uuid, $3::uuid, $4::vector WHERE NOT ",
has_identity_evidence!("$1"),
" ON CONFLICT (fact_id) DO UPDATE SET embedding = EXCLUDED.embedding"
))
.bind(fact_id)
.bind(kb_id)
.bind(entity_id)
Expand Down
59 changes: 38 additions & 21 deletions crates/utopia-store/src/resolution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,9 @@ pub async fn resolve_identity_name(
Some(ctx) => update_profile(pool, holder.id, holder.profile_n, ctx).await?,
None => touch_entity(pool, holder.id).await?,
}
if holder.type_id.is_none() {
adopt_type(pool, kb_id, holder.id, &holder.canonical_name, type_id).await?;
}
Ok(Resolution {
entity_id: holder.id,
created: false,
Expand Down Expand Up @@ -1011,8 +1014,6 @@ struct CrossCandidate {
type_key: Option<String>,
// 同上;`types_are_kin` 要按 id 走类层级
type_id: Option<Uuid>,
// 抽取升格要看它:人说过「就是没有类型」时,那也是一个决定
type_source: String,
profile_embedding: Option<Vector>,
profile_n: i32,
}
Expand Down Expand Up @@ -1125,6 +1126,38 @@ fn confusable_reviews(
.collect()
}

/// 持有者还没判出类型而这次判出来了 → 升格。
/// 不是合并(没有第二个实体),不入 entity_merges;本体页可手工改回
///
/// **人说过的「没有类型」不算「还没判出来」。** 0009 之后两者都是
/// NULL,只看 type_id 分不出——于是一个人看过、认为
/// 本体里没有合适类的实体,会在下一次抽取时被安上一个类型
async fn adopt_type(
pool: &PgPool,
kb_id: Uuid,
entity_id: Uuid,
canonical_name: &str,
type_id: Option<Uuid>,
) -> AppResult<()> {
let Some(type_id) = type_id else {
return Ok(());
};
let adopted = sqlx::query(
"UPDATE entities
SET type_id = $2, type_source = 'extracted', updated_at = now()
WHERE id = $1 AND type_id IS NULL AND type_source <> 'human'",
)
.bind(entity_id)
.bind(type_id)
.execute(pool)
.await?;
if adopted.rows_affected() > 0 {
// 类型标签兜底的消歧后缀可能已过时
refresh_disambiguators(pool, kb_id, canonical_name).await?;
}
Ok(())
}

/// 同类型召回为空时的跨类型处置(类型漂移)。
/// concept 兜底型候选跑既有画像分层:高相似直接 ATTACH(漂移的召回修复,concept
/// 侧类型升格为具体类型),灰区/无从判别 → 宁分勿合新建 + 审核对;易混具体类型
Expand Down Expand Up @@ -1152,7 +1185,7 @@ async fn resolve_type_drift(
None => None,
};
let cross: Vec<CrossCandidate> = sqlx::query_as(&format!(
"SELECT e.id, e.canonical_name, t.key AS type_key, e.type_id, e.type_source,
"SELECT e.id, e.canonical_name, t.key AS type_key, e.type_id,
e.profile_embedding, e.profile_n
FROM entities e LEFT JOIN entity_types t ON t.id = e.type_id
-- IS DISTINCT FROM 而不是 <>:后者遇 NULL 返回 NULL,被 WHERE 当假,
Expand Down Expand Up @@ -1210,24 +1243,8 @@ async fn resolve_type_drift(
if let Some((best, sim)) = best {
if sim >= SIM_ATTACH {
update_profile(pool, best.id, best.profile_n, ctx).await?;
// 候选还没判出类型而这次抽取判出来了 → 升格。
// 不是合并(没有第二个实体),不入 entity_merges;本体页可手工改回
//
// **人说过的「没有类型」不算「还没判出来」。** 0009 之后两者都是
// NULL,只看 type_key.is_none() 分不出——于是一个人看过、认为
// 本体里没有合适类的实体,会在下一次抽取时被安上一个类型
if best.type_key.is_none() && best.type_source != "human" && type_id.is_some() {
sqlx::query(
"UPDATE entities
SET type_id = $2, type_source = 'extracted', updated_at = now()
WHERE id = $1",
)
.bind(best.id)
.bind(type_id)
.execute(pool)
.await?;
// 类型标签兜底的消歧后缀可能已过时
refresh_disambiguators(pool, kb_id, &best.canonical_name).await?;
if best.type_key.is_none() {
adopt_type(pool, kb_id, best.id, &best.canonical_name, type_id).await?;
}
// mention 已定居到召回实体;同名易混类型实体的疑点仍在 → 照常入队
let mut reviews =
Expand Down
5 changes: 4 additions & 1 deletion crates/utopia-store/src/sources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ pub async fn update(
&& old_full
&& new_full
&& rss_feed_url(&previous.config) != rss_feed_url(&next_config);
let source = sqlx::query_as(
let source: Source = sqlx::query_as(
"UPDATE sources SET
name = COALESCE($2, name),
config = COALESCE($3, config),
Expand All @@ -303,6 +303,9 @@ pub async fn update(
if (!old_full && new_full) || feed_url_changed {
crate::rss_full_content::enable_source(&mut tx, id).await?;
}
if !previous.names_are_identities() && source.names_are_identities() {
crate::name_vectors::drop_for_source(&mut tx, id).await?;
}
tx.commit().await?;
opened(source)
}
Expand Down
Loading
Loading