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
26 changes: 26 additions & 0 deletions crates/utopia-core/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,13 @@ impl Source {
.and_then(serde_json::Value::as_bool)
.unwrap_or(true)
}

/// statements 来源的 config 写了 `{"names": "identity"}`:它推来的每个名字各指一个
/// 确定的东西(0071),按字面归并、不算名字向量。其余来源照旧。
pub fn names_are_identities(&self) -> bool {
self.kind == "statements"
&& self.config.get("names").and_then(serde_json::Value::as_str) == Some("identity")
}
}

#[cfg(test)]
Expand Down Expand Up @@ -217,6 +224,25 @@ mod source_extracts_tests {
assert!(with(serde_json::json!({ "extract": 0 })).extracts());
assert!(!with(serde_json::json!({ "extract": false })).extracts());
}

fn of_kind(kind: &str, config: serde_json::Value) -> Source {
Source {
kind: kind.into(),
..with(config)
}
}

#[test]
fn only_a_statements_source_with_the_string_identity_has_identity_names() {
let identity = serde_json::json!({ "names": "identity" });
assert!(of_kind("statements", identity.clone()).names_are_identities());
assert!(!of_kind("api", identity).names_are_identities());
assert!(!of_kind("statements", serde_json::json!({})).names_are_identities());
assert!(!of_kind("statements", serde_json::json!({ "names": true })).names_are_identities());
assert!(
!of_kind("statements", serde_json::json!({ "names": "prose" })).names_are_identities()
);
}
}

/// 来源配置里**用来鉴权**的那几个键。凭据只进不出:列表与创建 / 更新的响应都剔掉,
Expand Down
39 changes: 31 additions & 8 deletions crates/utopia-server/src/extraction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,12 +209,23 @@ async fn resolve_uncached(
name_vec: Option<&[f32]>,
text: Option<&str>,
exclude: &[Uuid],
identity: bool,
needs_adjudication: &mut bool,
) -> anyhow::Result<Uuid> {
let r = utopia_store::resolution::resolve_mention(
pool, kb_id, type_id, name, ctx, name_vec, text, exclude,
)
.await?;
let r = match identity {
true => {
utopia_store::resolution::resolve_identity_name(
pool, kb_id, type_id, name, ctx, text, exclude,
)
.await?
}
false => {
utopia_store::resolution::resolve_mention(
pool, kb_id, type_id, name, ctx, name_vec, text, exclude,
)
.await?
}
};
// 疑似重复对(画像灰区 / 类型漂移 / 同名并列)入审核队列。多数走批量裁决器,
// 同名并列(`ReviewStage::Human`)分不出谁是谁,只能等人裁——它自己带着 stage。
for review in &r.reviews {
Expand Down Expand Up @@ -268,6 +279,7 @@ pub(crate) async fn resolve_handle(
ctx: Option<&[f32]>,
name_vec: Option<&[f32]>,
text: Option<&str>,
identity: bool,
response_claims: &mut HashMap<String, Vec<Uuid>>,
handled_by_name: &mut HashMap<String, Vec<Uuid>>,
ambiguous_bare_cache: &mut HashMap<String, Uuid>,
Expand Down Expand Up @@ -309,6 +321,7 @@ pub(crate) async fn resolve_handle(
name_vec,
text,
&excluded,
identity,
needs_adjudication,
)
.await?;
Expand Down Expand Up @@ -343,10 +356,14 @@ async fn run(state: &AppState, document_id: Uuid, proposer: Proposer) -> anyhow:
}
let kb = utopia_store::kbs::get(&state.pool, doc.kb_id).await?;
// 推送来的陈述(0054):块就是契约,抽取按契约解析、不问模型,没配对话模型也照抽
let pushed = crate::pipeline::source_kind(state, doc.source_id)
.await?
.as_deref()
== Some("statements");
let source = match doc.source_id {
Some(id) => Some(utopia_store::sources::get(&state.pool, id).await?),
None => None,
};
let pushed = source.as_ref().is_some_and(|s| s.kind == "statements");
let identity = source
.as_ref()
.is_some_and(utopia_core::models::Source::names_are_identities);
// settings 有就传:推送路径不问对话模型,但名字向量的嵌入模型(#877)仍从它来
let settings = utopia_store::settings::get(&state.pool, kb.workspace_id).await?;
let client = if pushed {
Expand Down Expand Up @@ -376,6 +393,7 @@ async fn run(state: &AppState, document_id: Uuid, proposer: Proposer) -> anyhow:
proposer,
await_nod,
pushed,
identity,
)
.await
}
Expand Down Expand Up @@ -496,6 +514,7 @@ mod tests {
None,
None,
None,
false,
&mut response_claims,
&mut document_claims,
&mut bare_cache,
Expand All @@ -510,6 +529,7 @@ mod tests {
None,
None,
None,
false,
&mut response_claims,
&mut document_claims,
&mut bare_cache,
Expand Down Expand Up @@ -588,6 +608,7 @@ mod tests {
None,
None,
None,
false,
&mut later_response_claims,
&mut document_claims,
&mut bare_cache,
Expand Down Expand Up @@ -616,6 +637,7 @@ mod tests {
None,
None,
None,
false,
&mut another_response_claims,
&mut document_claims,
&mut bare_cache,
Expand Down Expand Up @@ -743,6 +765,7 @@ mod tests {
Some(&ctx),
None,
None,
false,
&mut response_claims,
&mut document_claims,
&mut bare_cache,
Expand Down
13 changes: 12 additions & 1 deletion crates/utopia-server/src/extraction_open.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,7 @@ async fn apply_open_extraction(
attested_at: Option<chrono::DateTime<chrono::Utc>>,
bound_types: &HashMap<String, Uuid>,
pushed: bool,
identity: bool,
await_nod: bool,
proposer: Proposer,
pending_count: &mut usize,
Expand Down Expand Up @@ -330,6 +331,7 @@ async fn apply_open_extraction(
ctx,
name_vecs.get(&key).map(Vec::as_slice),
evidence.get(&key).map(String::as_str),
identity,
&mut response_claims,
handled_by_name,
ambiguous_bare_cache,
Expand Down Expand Up @@ -1010,6 +1012,8 @@ pub(crate) async fn run_open(
proposer: Proposer,
await_nod: bool,
pushed: bool,
// 0071: the source's names are identities, so they get no name vectors
identity: bool,
) -> anyhow::Result<()> {
let pool = &state.pool;
let document_id = doc.id;
Expand Down Expand Up @@ -1044,7 +1048,9 @@ pub(crate) async fn run_open(

// 名字向量的嵌入客户端(0041 决定 3 通道 2)。没配嵌入模型就是 None:召回退回
// 字面相等,抽取照常
let embed = settings.and_then(crate::llm_util::embed_client);
let embed = settings
.and_then(crate::llm_util::embed_client)
.filter(|_| !identity);
// 文档自己说到的日期(0064 决定 1):每一块报上来的,连它所在的标题路径。块与块之间
// 不传——一条日期管到哪,看的是它自己那一块正文里的标题,块并行抽的时候照样成立(#588)
let mut time_entries: Vec<utopia_extract::time::TimeEntry> = Vec::new();
Expand Down Expand Up @@ -1140,6 +1146,7 @@ pub(crate) async fn run_open(
attested_at,
&bound_types,
pushed,
identity,
await_nod,
proposer,
&mut pending_count,
Expand Down Expand Up @@ -1282,6 +1289,10 @@ pub(crate) async fn run_open(
#[path = "extraction_open_known_flow_tests.rs"]
mod known_flow_tests;

#[cfg(test)]
#[path = "extraction_open_identity_names_tests.rs"]
mod identity_names_tests;

#[cfg(test)]
#[path = "extraction_open_out_of_credit_tests.rs"]
mod out_of_credit_tests;
Expand Down
126 changes: 126 additions & 0 deletions crates/utopia-server/src/extraction_open_identity_names_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
//! 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.
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>)>> {
let Some(url) = utopia_store::test_db::url() else {
return Ok(None);
};
let pool = sqlx::PgPool::connect(&url).await?;
utopia_store::db::migrate(&pool).await?;
let [org, ws, kb, source, doc, chunk, known_id]: [Uuid; 7] =
std::array::from_fn(|_| Uuid::now_v7());
let text = serde_json::to_string(&json!({
"external_id": "commit:identity",
"e": [[PUSHED, "SourceFile", true]],
"s": [[null, PUSHED, "path", null, "src/x.ts", null, null, null]],
"n": []
}))?;
sqlx::raw_sql(&format!(
"INSERT INTO organizations(id,name) VALUES ('{org}','identity-names');
INSERT INTO workspaces(id,org_id,name) VALUES ('{ws}','{org}','identity-names');
INSERT INTO knowledge_bases(id,workspace_id,name) VALUES ('{kb}','{ws}','identity-names');
INSERT INTO sources(id,kb_id,kind,name,config) VALUES
('{source}','{kb}','statements','lore',$${config}$$::jsonb);
INSERT INTO documents(id,kb_id,filename,sha256,source_id) VALUES
('{doc}','{kb}','commit.json','x{doc}','{source}');
INSERT INTO chunks(id,kb_id,document_id,seq,text) VALUES
('{chunk}','{kb}','{doc}',0,$${text}$$);"
))
.execute(&pool)
.await?;
sqlx::query("INSERT INTO entities(id,kb_id,canonical_name) VALUES ($1,$2,$3)")
.bind(known_id)
.bind(kb)
.bind(KNOWN)
.execute(&pool)
.await?;
let fact = utopia_store::names::record(&pool, kb, known_id, KNOWN, None, None)
.await?
.expect("a named entity gets a name fact");
utopia_store::name_vectors::set(&pool, kb, &[(fact, known_id, vec![1.0, 0.0, 0.0, 0.0])])
.await?;

let calls = Arc::new(AtomicUsize::new(0));
let counted = calls.clone();
let router = Router::new().route(
"/embeddings",
post(move |Json(body): Json<Value>| async move {
counted.fetch_add(1, Ordering::SeqCst);
let inputs = body["input"].as_array().map_or(0, Vec::len);
Json(json!({"data": vec![json!({"embedding": [1.0, 0.0, 0.0, 0.0]}); inputs]}))
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
let base = format!("http://{}", listener.local_addr()?);
let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
utopia_store::settings::upsert(
&pool,
ws,
None,
None,
None,
Some(&base),
None,
Some("fake-embed"),
Some(4),
)
.await?;

let dir = tempfile::tempdir()?;
let cfg = utopia_core::config::AppConfig {
data_dir: dir.path().to_string_lossy().into_owned(),
..Default::default()
};
let search = Arc::new(utopia_search::SearchIndex::open(
&dir.path().join("search"),
)?);
let state = AppState::new(pool.clone(), &cfg, search, "test-only".into());
crate::extraction::extract_document(&state, doc, utopia_core::models::Proposer::default())
.await?;

let reasons: Vec<String> = sqlx::query_scalar(
"SELECT reason FROM resolution_reviews WHERE kb_id = $1 ORDER BY reason",
)
.bind(kb)
.fetch_all(&pool)
.await?;

server.abort();
sqlx::query("DELETE FROM jobs WHERE payload->>'kb_id' = $1")
.bind(kb.to_string())
.execute(&pool)
.await?;
sqlx::query("DELETE FROM organizations WHERE id = $1")
.bind(org)
.execute(&pool)
.await?;
Ok(Some((calls.load(Ordering::SeqCst), reasons)))
}

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 {
return Ok(());
};
assert_eq!(outcome, (0, Vec::<String>::new()));
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 {
return Ok(());
};
assert!(calls > 0 && reasons.iter().any(|r| r.starts_with("name_vector|")));
Ok(())
}
Loading
Loading