diff --git a/Cargo.lock b/Cargo.lock index 23de9c05d..069c37471 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5477,6 +5477,7 @@ dependencies = [ "thiserror 2.0.20", "tokio", "tracing", + "wiremock", ] [[package]] diff --git a/crates/utopia-llm/Cargo.toml b/crates/utopia-llm/Cargo.toml index 9b0b0eb98..792e7160a 100644 --- a/crates/utopia-llm/Cargo.toml +++ b/crates/utopia-llm/Cargo.toml @@ -16,3 +16,4 @@ thiserror.workspace = true [dev-dependencies] tokio = { workspace = true, features = ["macros", "rt"] } +wiremock = "0.6.5" diff --git a/crates/utopia-llm/src/lib.rs b/crates/utopia-llm/src/lib.rs index c311f72f4..aa2bfe67a 100644 --- a/crates/utopia-llm/src/lib.rs +++ b/crates/utopia-llm/src/lib.rs @@ -449,6 +449,9 @@ pub struct LlmClient { /// 端点报过的上下文窗口(token),起初是 `u32::MAX`。同一个客户端(含它的克隆)此后 /// 都按它算历史预算,只降不升;对话客户端按工作区留着,所以下一轮也记得(#964) context_window: std::sync::Arc, + /// 端点说过带工具的请求不收推理强度之后置位(#1353):此后带工具的请求体都写 + /// `reasoning_effort: "none"`,别的调用照旧按设置发。同一个客户端(含克隆)只吃一次拒绝 + tools_without_effort: std::sync::Arc, } /// 建连多久算失败。 @@ -580,6 +583,7 @@ impl LlmClient { model: model.to_string(), reasoning_effort: None, context_window: std::sync::Arc::new(std::sync::atomic::AtomicU32::new(u32::MAX)), + tools_without_effort: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), completion_ceiling: std::sync::Arc::new(std::sync::atomic::AtomicU32::new( MAX_COMPLETION_TOKENS, )), @@ -875,10 +879,56 @@ impl LlmClient { if let Some(choice) = tool_choice { body["tool_choice"] = choice.clone(); } + if self + .tools_without_effort + .load(std::sync::atomic::Ordering::Relaxed) + { + body["reasoning_effort"] = json!("none"); + } } body } + /// 发一个带工具的请求。推理部署上,端点可能整个拒收带工具又带推理强度的请求体 + /// (Azure:`Function tools with reasoning_effort are not supported`),而部署本身的默认 + /// 强度就算数,不发这个字段也一样被拒——于是对话退回一步检索,治理的第二眼跑不了(#1353)。 + /// 吃到这句 400 就记在客户端上,改发 `none` 重试一次;只动带工具的请求,抽取与对齐照旧 + async fn post_tools( + &self, + messages: &[serde_json::Value], + tools: Option<&serde_json::Value>, + tool_choice: Option<&serde_json::Value>, + stream: bool, + ) -> anyhow::Result { + use std::sync::atomic::Ordering; + loop { + let learned = self.tools_without_effort.load(Ordering::Relaxed); + let resp = self + .request("/chat/completions") + .json(&self.tools_body(messages, tools, tool_choice, stream)) + .send() + .await + .map_err(Unreachable)?; + let status = resp.status(); + if status.is_success() { + return Ok(resp); + } + let retry_after = retry_after_of(resp.headers()); + let raw = resp.text().await.map_err(Unreachable)?; + let parsed = serde_json::from_str(&raw).unwrap_or_default(); + if status == reqwest::StatusCode::BAD_REQUEST + && tools.is_some() + && !learned + && says_tools_refuse_effort(&err_detail(&parsed, &raw)) + { + tracing::info!(model = %self.model, "端点不收带工具的推理强度,带工具的请求改发 none 并记住"); + self.tools_without_effort.store(true, Ordering::Relaxed); + continue; + } + return Err(failure("LLM", status, retry_after, &parsed, &raw)); + } + } + /// Exact serialized streaming request size, including model and protocol fields. /// Used by the bounded answer phase before any network I/O. pub fn tool_free_request_bytes(&self, messages: &[serde_json::Value]) -> usize { @@ -894,17 +944,7 @@ impl LlmClient { tools: Option<&serde_json::Value>, tool_choice: Option<&serde_json::Value>, ) -> anyhow::Result { - let resp = self - .request("/chat/completions") - .json(&self.tools_body(messages, tools, tool_choice, false)) - .send() - .await - .map_err(Unreachable)?; - let status = resp.status(); - let retry_after = retry_after_of(resp.headers()); - if !status.is_success() { - return Err(response_failure("LLM", status, retry_after, resp).await?); - } + let resp = self.post_tools(messages, tools, tool_choice, false).await?; let body: serde_json::Value = resp.json().await.map_err(Unreachable)?; let msg = &body["choices"][0]["message"]; if msg.is_null() { @@ -961,17 +1001,7 @@ impl LlmClient { tools: Option<&serde_json::Value>, tool_choice: Option<&serde_json::Value>, ) -> anyhow::Result> + Send + use<>> { - let resp = self - .request("/chat/completions") - .json(&self.tools_body(messages, tools, tool_choice, true)) - .send() - .await - .map_err(Unreachable)?; - if !resp.status().is_success() { - let status = resp.status(); - let retry_after = retry_after_of(resp.headers()); - return Err(response_failure("LLM", status, retry_after, resp).await?); - } + let resp = self.post_tools(messages, tools, tool_choice, true).await?; let mut bytes = resp.bytes_stream(); let stream = async_stream::try_stream! { @@ -1268,6 +1298,13 @@ fn err_detail(body: &serde_json::Value, raw: &str) -> String { .unwrap_or_else(|| "unknown error".to_string()) } +/// 端点说不说「带工具的请求不收推理强度」。只有措辞可认:Azure 给的 code 是笼统的 +/// `invalid_request_error`。两样都得提到——只说工具或只说推理强度的 400 是别的毛病 +fn says_tools_refuse_effort(detail: &str) -> bool { + let d = detail.to_lowercase(); + d.contains("reasoning_effort") && (d.contains("tool") || d.contains("function")) +} + /// 响应体说不说这是余额问题。 /// /// **给 429 用的**:OpenAI 用同一个状态码表示「太快了」和「没钱了」, @@ -1567,6 +1604,118 @@ mod tests { } } + #[test] + fn a_400_about_tools_and_reasoning_effort_is_recognised_and_others_are_not() { + assert!(super::says_tools_refuse_effort( + "Function tools with reasoning_effort are not supported for gpt-x in /v1/chat/completions. Please use /v1/responses instead." + )); + assert!(!super::says_tools_refuse_effort( + "Unsupported value: 'reasoning_effort' does not support 'minimal'" + )); + assert!(!super::says_tools_refuse_effort( + "Invalid 'tools[0].function.name'" + )); + } + + #[tokio::test] + async fn a_tool_request_refused_for_its_reasoning_effort_retries_with_none_and_remembers() { + use wiremock::matchers::{body_partial_json, method}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + let server = MockServer::start().await; + let ok = serde_json::json!({ "choices": [{ "message": { "role": "assistant", "content": "pong" }, "finish_reason": "stop" }] }); + Mock::given(method("POST")) + .and(body_partial_json( + serde_json::json!({ "reasoning_effort": "none" }), + )) + .respond_with(ResponseTemplate::new(200).set_body_json(ok.clone())) + .with_priority(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(wiremock::matchers::body_string_contains("\"tools\"")) + .respond_with(ResponseTemplate::new(400).set_body_json(serde_json::json!({ "error": { + "message": "Function tools with reasoning_effort are not supported for gpt-x in /v1/chat/completions.", + "type": "invalid_request_error" } }))) + .with_priority(2) + .mount(&server) + .await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(200).set_body_json(ok)) + .with_priority(3) + .mount(&server) + .await; + let client = + LlmClient::new(&server.uri(), None, "m").with_reasoning_effort(Some("low".into())); + let tool = serde_json::json!([{ "type": "function", "function": { "name": "ping", "parameters": { "type": "object", "properties": {} } } }]); + let ask = [serde_json::json!({ "role": "user", "content": "ping" })]; + assert_eq!( + client + .chat_tools(&ask, &tool) + .await + .unwrap() + .content + .as_deref(), + Some("pong") + ); + assert_eq!( + client + .clone() + .chat_tools(&ask, &tool) + .await + .unwrap() + .content + .as_deref(), + Some("pong") + ); + let plain = [ChatMessage { + role: "user".into(), + content: "hi".into(), + }]; + client.chat(&plain).await.unwrap(); + let sent: Vec = server + .received_requests() + .await + .unwrap() + .iter() + .map(|r| serde_json::from_slice(&r.body).unwrap()) + .collect(); + let efforts: Vec<_> = sent + .iter() + .map(|b| (b.get("tools").is_some(), b["reasoning_effort"].clone())) + .collect(); + assert_eq!( + efforts, + [ + (true, serde_json::json!("low")), // refused once + (true, serde_json::json!("none")), // retried + (true, serde_json::json!("none")), // remembered, also by a clone + (false, serde_json::json!("low")), // a call without tools keeps the setting + ] + ); + } + + #[tokio::test] + async fn another_400_on_a_tool_request_is_not_retried() { + use wiremock::{matchers::method, Mock, MockServer, ResponseTemplate}; + let server = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(400).set_body_json( + serde_json::json!({ "error": { "message": "Invalid 'tools[0].function.name'" } }), + )) + .mount(&server) + .await; + let client = LlmClient::new(&server.uri(), None, "m"); + let tool = serde_json::json!([{ "type": "function", "function": { "name": "bad name" } }]); + assert!(client + .chat_tools( + &[serde_json::json!({ "role": "user", "content": "x" })], + &tool + ) + .await + .is_err()); + assert_eq!(server.received_requests().await.unwrap().len(), 1); + } + #[test] fn reasoning_effort_rides_in_every_chat_body_only_when_set() { let plain = LlmClient::new("http://x", None, "m"); diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rs index c64cb8c9d..795e30c4a 100644 --- a/crates/utopia-server/src/api/ontology_routes.rs +++ b/crates/utopia-server/src/api/ontology_routes.rs @@ -85,7 +85,8 @@ fn missing_link(q: &InstancesQuery) -> Result, AppError> } /// 某个类下的实体实例列表(详情区右侧,分页)。 -/// 令牌也读得到(0014 决定 7)。带 `missing_predicate` 时只列缺那条关系的成员,并回显认作它的属性与短语。 +/// 带 `missing_predicate` 时只列缺那条关系的成员,并回显认作它的属性与短语。 +/// 令牌也读得到(0014 决定 7)。 pub async fn list_entity_instances( State(state): State, reader: SessionOrToken, diff --git a/crates/utopia-server/src/api/settings_routes.rs b/crates/utopia-server/src/api/settings_routes.rs index d79302b23..d837c5bda 100644 --- a/crates/utopia-server/src/api/settings_routes.rs +++ b/crates/utopia-server/src/api/settings_routes.rs @@ -236,7 +236,64 @@ pub async fn put_transcribe( Ok(Json(json!({ "ok": true, "requeued": requeued }))) } -/// 连通性测试:对话发一条最小消息;embedding 试算一条并返回维度;版面识别服务问一声健康。 +/// 对话模型按任务真正发出的三种请求各试一次(#1354):普通一问;抽取那种流式、带完成上限、 +/// 温度 0 的一问;带一个工具的一问。只发普通一问的话,拒收 `max_tokens`、`temperature` 或工具的 +/// 端点照样「测试通过」,毛病要等到抽取任务成片失败、对话悄悄退回一步检索时才露出来。 +/// 普通一问就失败的,端点本身不通,后两问不再发,免得同一个错报三遍。每问只要一个词, +/// 托管模型上花不了几个 token。后两问同时发,每一问都有 [`PROBE_LIMIT`] 的上限:接了连接却 +/// 不说话的端点,最多让人等两个上限,而不是三次五分钟的沉默超时 +async fn chat_checks(client: &utopia_llm::LlmClient) -> serde_json::Value { + let msg = [ChatMessage { + role: "user".into(), + content: "Reply with exactly one word: OK".into(), + }]; + let reply = match limited(client.chat(&msg)).await { + Ok(reply) => reply.chars().take(50).collect::(), + Err(e) => return json!({ "ok": false, "error": e.to_string() }), + }; + let tool = json!([{ "type": "function", "function": { + "name": "ping", "description": "Answers pong.", + "parameters": { "type": "object", "properties": {} } } }]); + let ask = [json!({ "role": "user", "content": "Call the ping tool." })]; + let (streaming, tools) = tokio::join!( + limited(async { client.chat_at_streaming(&msg, Some(0.0)).await.map(|_| ()) }), + limited(async { client.chat_tools(&ask, &tool).await.map(|_| ()) }), + ); + let check = |r: &anyhow::Result<()>| match r { + Ok(()) => json!({ "ok": true }), + Err(e) => json!({ "ok": false, "error": e.to_string() }), + }; + let failed: Vec = [("streaming", &streaming), ("tools", &tools)] + .into_iter() + .filter_map(|(name, r)| r.as_ref().err().map(|e| format!("{name}: {e}"))) + .collect(); + let mut out = json!({ + "ok": failed.is_empty(), + "reply": reply, + "checks": { "plain": { "ok": true }, "streaming": check(&streaming), "tools": check(&tools) }, + }); + if !failed.is_empty() { + out["error"] = json!(format!("plain ok; {}", failed.join("; "))); + } + out +} + +/// 设置页测试里每一问的上限 +const PROBE_LIMIT: std::time::Duration = std::time::Duration::from_secs(45); + +async fn limited(f: impl std::future::Future>) -> anyhow::Result { + tokio::time::timeout(PROBE_LIMIT, f) + .await + .unwrap_or_else(|_| { + Err(anyhow::anyhow!( + "no answer within {} s", + PROBE_LIMIT.as_secs() + )) + }) +} + +/// 连通性测试:对话按任务的三种请求形状各试一次(见 [`chat_checks`]);embedding 试算一条并 +/// 返回维度;版面识别服务问一声健康。 pub async fn test( State(state): State, AuthUser(user): AuthUser, @@ -252,20 +309,9 @@ pub async fn test( )); }; - let chat_result = match llm_util::chat_client(&s) { + let chat_result = match llm_util::chat_probe_client(&s) { None => json!({ "ok": false, "error": "Not configured" }), - Some(client) => { - let msg = [ChatMessage { - role: "user".into(), - content: "Reply with exactly one word: OK".into(), - }]; - match client.chat(&msg).await { - Ok(reply) => { - json!({ "ok": true, "reply": reply.chars().take(50).collect::() }) - } - Err(e) => json!({ "ok": false, "error": e.to_string() }), - } - } + Some(client) => chat_checks(&client).await, }; let embed_result = match llm_util::embed_client(&s) { @@ -300,3 +346,99 @@ pub async fn test( "transcribe": transcribe_result, }))) } + +#[cfg(test)] +mod tests { + use wiremock::matchers::method; + use wiremock::{Mock, MockServer, Request, ResponseTemplate}; + + /// 只认普通与流式、见到工具就 400 的端点;`down` 时什么都 500。收到的请求体由测试逐个查 + async fn endpoint(down: bool) -> MockServer { + let server = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(move |r: &Request| { + let body: serde_json::Value = serde_json::from_slice(&r.body).unwrap(); + if down { + return ResponseTemplate::new(500).set_body_string("down"); + } + if body.get("tools").is_some() { + return ResponseTemplate::new(400).set_body_json(serde_json::json!({ + "error": { "message": "tools are not supported by this deployment" } })); + } + if body["stream"] == true { + let frame = serde_json::json!({ "choices": [{ "index": 0, "delta": { "content": "OK" }, "finish_reason": "stop" }] }); + return ResponseTemplate::new(200) + .insert_header("content-type", "text/event-stream") + .set_body_string(format!("data: {frame}\n\ndata: [DONE]\n\n")); + } + ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "choices": [{ "message": { "role": "assistant", "content": "OK" }, "finish_reason": "stop" }] })) + }) + .mount(&server) + .await; + server + } + + async fn bodies(server: &MockServer) -> Vec { + server + .received_requests() + .await + .unwrap() + .iter() + .map(|r| serde_json::from_slice(&r.body).unwrap()) + .collect() + } + + #[tokio::test] + async fn each_job_shape_is_sent_and_a_refused_one_is_named() { + let server = endpoint(false).await; + let out = + super::chat_checks(&utopia_llm::LlmClient::new(&server.uri(), None, "scripted")).await; + assert_eq!(out["ok"], false, "{out}"); + assert_eq!(out["checks"]["plain"]["ok"], true); + assert_eq!(out["checks"]["streaming"]["ok"], true, "{out}"); + assert_eq!(out["checks"]["tools"]["ok"], false); + let error = out["error"].as_str().unwrap(); + assert!(error.starts_with("plain ok; tools: "), "{error}"); + assert!(!error.contains("streaming:"), "{error}"); + + let sent = bodies(&server).await; + assert_eq!(sent.len(), 3, "{sent:?}"); + let plain = &sent[0]; + assert!( + plain["stream"] == false + && plain.get("tools").is_none() + && plain.get("max_tokens").is_none(), + "{plain}" + ); + // 后两问同时发,到达的先后不定 + let streamed = sent + .iter() + .find(|b| b["stream"] == true) + .expect("a streamed request"); + assert_eq!(streamed["temperature"], 0.0, "{streamed}"); + assert!( + streamed["max_tokens"].as_u64().is_some_and(|n| n > 0), + "the job's completion ceiling rides along: {streamed}" + ); + let tooled = sent + .iter() + .find(|b| b.get("tools").is_some()) + .expect("a request with a tool"); + assert_eq!(tooled["tools"][0]["function"]["name"], "ping"); + } + + #[tokio::test] + async fn an_endpoint_that_is_down_is_reported_once() { + let server = endpoint(true).await; + let out = + super::chat_checks(&utopia_llm::LlmClient::new(&server.uri(), None, "scripted")).await; + assert_eq!(out["ok"], false); + assert!(out.get("checks").is_none(), "{out}"); + assert_eq!( + bodies(&server).await.len(), + 1, + "the streamed and tool shapes are not sent when the plain one fails" + ); + } +} diff --git a/crates/utopia-server/src/api/token_read_tests.rs b/crates/utopia-server/src/api/token_read_tests.rs index b9d52d525..289b35100 100644 --- a/crates/utopia-server/src/api/token_read_tests.rs +++ b/crates/utopia-server/src/api/token_read_tests.rs @@ -1,5 +1,5 @@ -//! 个人令牌读图(0014 决定 7):搜实体、实体详情、认知历史、事实证据、图总览、邻域六条读路由 -//! 收任何一枚活着的令牌。角色照旧是上限,`kb_ids` 排除了的库答 404;改实体仍只认会话。 +//! 个人令牌读图(0014 决定 7):搜实体、实体详情、认知历史、事实证据、图总览、邻域、本体、 +//! 某类的实例这些读路由收任何一枚活着的令牌。角色照旧是上限,`kb_ids` 排除了的库答 404;改实体仍只认会话。 use crate::state::AppState; use axum::body::Body; use axum::http::{Request, StatusCode}; @@ -15,6 +15,7 @@ struct Fixture { /// 令牌够不着的另一个库 other_kb: Uuid, reader: Uuid, + person: Uuid, entity: Uuid, fact: Uuid, _dir: tempfile::TempDir, @@ -68,6 +69,7 @@ impl Fixture { kb, other_kb, reader, + person, entity, fact, _dir: dir, @@ -81,8 +83,8 @@ impl Fixture { .1 } - fn read_paths(&self) -> [String; 6] { - let (kb, entity, fact) = (self.kb, self.entity, self.fact); + fn read_paths(&self) -> [String; 8] { + let (kb, person, entity, fact) = (self.kb, self.person, self.entity, self.fact); [ format!("/kbs/{kb}/entities?q=Zhang"), format!("/kbs/{kb}/entities/{entity}"), @@ -90,6 +92,8 @@ impl Fixture { format!("/kbs/{kb}/facts/{fact}/evidence"), format!("/kbs/{kb}/graph/overview"), format!("/kbs/{kb}/graph/neighborhood?entity={entity}"), + format!("/kbs/{kb}/ontology"), + format!("/kbs/{kb}/ontology/entity-types/{person}/entities"), ] } diff --git a/crates/utopia-server/src/auth.rs b/crates/utopia-server/src/auth.rs index 2e671fea4..0050e0fbe 100644 --- a/crates/utopia-server/src/auth.rs +++ b/crates/utopia-server/src/auth.rs @@ -178,7 +178,7 @@ impl FromRequestParts for AuthUser { /// 路由上一律是 401——那是有意的:哪条路由准令牌进来,要在 0014 里说出理由。 /// 用这个提取器的只有文档原件(0052,含按推送时的 external_id 读回)、「把一个库搭起来」 /// 那几条、分块检索和读图那几条:搜实体、实体详情、认知历史、事实证据、图总览、邻域、 -/// 本体、抽取、导出(决定 7)。 +/// 本体、某类的实例、抽取、导出(决定 7)。 /// /// 按推送时的 `external_id` 读回一篇文档(#1276)也是文档原件,开给令牌的理由写在决定 7。 /// diff --git a/crates/utopia-server/src/extraction_open.rs b/crates/utopia-server/src/extraction_open.rs index ab3a4f8ce..ba741cfe5 100644 --- a/crates/utopia-server/src/extraction_open.rs +++ b/crates/utopia-server/src/extraction_open.rs @@ -45,6 +45,41 @@ struct ChunkParsed { name_vecs: HashMap>, } +/// Identity clues belong to the statement's subject, not to every name in the chunk. +/// Keep only grounded, single-sentence quotes with one subject owner. Overlapping +/// quotes assigned to different subjects cannot tell us whose department was named. +fn mention_evidence( + extraction: &utopia_extract::open::OpenExtraction, + text: &str, +) -> HashMap { + let quotes: Vec<_> = extraction + .statements + .iter() + .filter_map(|s| { + let quote = s.quote.as_deref()?.trim(); + Some((name_key(&s.subject), quote, locate(text, quote)?)) + }) + .collect(); + let mut evidence = HashMap::::new(); + for (subject, quote, (start, end)) in "es { + // Conservative about abbreviations too: a missed clue falls back to the + // existing resolver; joining separate sentences can attach to the wrong person. + let body = quote.trim_end_matches(['.', '!', '?', '。', '!', '?', '"', '”', '’']); + if body.contains(['.', '!', '?', '。', '!', '?', ';', ';']) + || !span_in_quote(subject, quote) + || quotes.iter().any(|(other, _, (a, b))| { + other != subject && ((a < end && start < b) || span_in_quote(other, quote)) + }) + { + continue; + } + let entry = evidence.entry(subject.clone()).or_default(); + entry.push_str(quote); + entry.push('\n'); + } + evidence +} + /// 回复为什么是半截的:端点撞上了 token 上限(#760),或护栏看见它在复读、停了读(#1301)。 /// 两种都当半截处理,丢弃行要说清是哪一种——复读的去查上限,是找错了地方 #[derive(Debug, Clone, Copy)] @@ -270,6 +305,10 @@ async fn apply_open_extraction( touched_names: &mut HashSet, ) -> anyhow::Result<()> { // ---- 东西:有名字的走身份消解,被描述的建成没有名字事实的实体 ---- + // Object-only mentions and rejected quotes deliberately supply None, including + // to the old #331 tie/grey-zone paths: another subject's chunk is not their clue. + // With no owned clue, profile tiers and their ordinary review requests decide. + let evidence = mention_evidence(extraction, &chunk.text); let mut response_claims: HashMap> = HashMap::new(); let mut local: HashMap = HashMap::new(); // 被描述的东西:先记下名字和类别词,等陈述指到它再建(见 `place`) @@ -299,7 +338,7 @@ async fn apply_open_extraction( } else { NameRecall::Full(name_vecs.get(&key).map(Vec::as_slice)) }, - Some(&chunk.text), + evidence.get(&key).map(String::as_str), &mut response_claims, handled_by_name, ambiguous_bare_cache, diff --git a/crates/utopia-server/src/llm_util.rs b/crates/utopia-server/src/llm_util.rs index 15428c630..3f833c1ef 100644 --- a/crates/utopia-server/src/llm_util.rs +++ b/crates/utopia-server/src/llm_util.rs @@ -23,6 +23,25 @@ pub fn chat_client(s: &LlmSettings) -> Option { ) } +/// 设置页「测试」用的对话客户端:设置与 [`chat_client`] 相同,超时短得多(#1354 评审)。 +/// 任务的客户端容得下五分钟的沉默,是因为推理模型先想再答;测试只问一个词,一个接了 +/// 连接却不说话的端点不该让人在设置页干等一刻钟 +pub fn chat_probe_client(s: &LlmSettings) -> Option { + if !s.chat_ready() { + return None; + } + Some( + LlmClient::with_timeouts( + s.chat_base_url.as_deref()?, + s.chat_api_key.as_deref(), + s.chat_model.as_deref()?, + std::time::Duration::from_secs(10), + std::time::Duration::from_secs(30), + ) + .with_reasoning_effort(s.chat_reasoning_effort.clone()), + ) +} + /// 对话模型的设置:地址、密钥、模型、推理力度。任一项变了就是另一个客户端 type ChatConfig = ( Option, diff --git a/crates/utopia-server/src/namesake_scripted_cases.rs b/crates/utopia-server/src/namesake_scripted_cases.rs index 62847d6c8..4fbcdd9b1 100644 --- a/crates/utopia-server/src/namesake_scripted_cases.rs +++ b/crates/utopia-server/src/namesake_scripted_cases.rs @@ -33,6 +33,24 @@ const EMPLOYEES: [&str; 2] = ["E17", "F42"]; enum Check { Resolver { target: usize }, Adjudicator { literal: bool }, + Guard(Guard), + ObjectOnly, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Guard { + Unrelated, + CrossSentence, + SharedQuote, + OverlappingQuotes, + SharedDepartment, + ConflictingQuotes, + MissingQuote, + UngroundedQuote, + TypedToUntyped, + UntypedToTyped, + IncompatibleType, + Markdown, } struct Case { @@ -40,7 +58,11 @@ struct Case { check: Check, } -const CASES: [Case; 4] = [ +const CASES: &[Case] = &[ + Case { + id: "object_only_mention_without_owned_quote_keeps_tie_review", + check: Check::ObjectOnly, + }, Case { id: "resolver_passage_over_profile", check: Check::Resolver { target: 1 }, @@ -57,14 +79,59 @@ const CASES: [Case; 4] = [ id: "adjudicator_entity_clues_reach_request", check: Check::Adjudicator { literal: false }, }, + Case { + id: "unrelated_sentence_is_not_evidence", + check: Check::Guard(Guard::Unrelated), + }, + Case { + id: "cross_sentence_quote_is_not_evidence", + check: Check::Guard(Guard::CrossSentence), + }, + Case { + id: "two_subjects_share_a_quote", + check: Check::Guard(Guard::SharedQuote), + }, + Case { + id: "two_subjects_have_overlapping_quotes", + check: Check::Guard(Guard::OverlappingQuotes), + }, + Case { + id: "shared_department_is_not_unique", + check: Check::Guard(Guard::SharedDepartment), + }, + Case { + id: "conflicting_quotes_do_not_choose", + check: Check::Guard(Guard::ConflictingQuotes), + }, + Case { + id: "missing_quote_does_not_choose", + check: Check::Guard(Guard::MissingQuote), + }, + Case { + id: "ungrounded_quote_does_not_choose", + check: Check::Guard(Guard::UngroundedQuote), + }, + Case { + id: "typed_mention_can_choose_untyped_namesake", + check: Check::Guard(Guard::TypedToUntyped), + }, + Case { + id: "untyped_mention_can_choose_typed_namesake", + check: Check::Guard(Guard::UntypedToTyped), + }, + Case { + id: "incompatible_type_is_not_chosen", + check: Check::Guard(Guard::IncompatibleType), + }, + Case { + id: "markdown_clue_recalls_the_stored_spelling", + check: Check::Guard(Guard::Markdown), + }, ]; // #1136: a listed case MUST fail today; every other case MUST pass. A fix removes // the corresponding names with its code change, so success cannot silently go stale. -const KNOWN_FAILURES: [(&str, &str); 2] = [ - ("resolver_passage_over_profile", "forward"), - ("resolver_passage_over_profile", "reverse"), -]; +const KNOWN_FAILURES: [(&str, &str); 0] = []; struct Step { prompt_has: String, @@ -261,6 +328,8 @@ impl Fx { holders[i] = self.seed(i, case.check).await?; } let (passed, observation) = match case.check { + Check::Guard(guard) => self.guard(guard, holders).await?, + Check::ObjectOnly => self.object_only(holders).await?, Check::Resolver { target } => { self.model.steps.lock().unwrap().push_back(Step { prompt_has: self.quotes[2].clone(), stream: true, @@ -353,12 +422,17 @@ impl Fx { let model_calls = self.model.requests.lock().unwrap().len(); anyhow::ensure!( model_calls == 1, - "expected exactly one scripted request, got {model_calls}" + "expected one scripted request, got {model_calls}" ); let pending_human: i64 = sqlx::query_scalar("SELECT count(*) FROM resolution_reviews WHERE kb_id=$1 AND stage='human' AND status='pending'") .bind(self.kb).fetch_one(&self.pool).await?; anyhow::ensure!( - pending_human == 0, + pending_human + == if matches!(case.check, Check::ObjectOnly) { + 2 + } else { + 0 + }, "unexpected pending Human reviews: {pending_human}" ); Ok( @@ -367,6 +441,208 @@ impl Fx { ) } + async fn object_only(&self, holders: [Uuid; 2]) -> anyhow::Result<(bool, Value)> { + let text = "Finance assigned a report to Alex Lee."; + // Both namesakes tie. Finance is the statement's subject, so its quote + // cannot rescue the object through the old #331 whole-chunk tie shortcut. + sqlx::query("UPDATE entities SET profile_embedding='[1,0,0]'::vector WHERE id=$1") + .bind(holders[1]) + .execute(&self.pool) + .await?; + sqlx::query("UPDATE chunks SET text=$1 WHERE id=$2") + .bind(text) + .bind(self.chunks[2]) + .execute(&self.pool) + .await?; + self.model.steps.lock().unwrap().push_back(Step { + prompt_has: text.into(), + stream: true, + text: json!({"e":[["Alex Lee","person",1],["Finance","department",1]], + "s":[[text,"Finance","assigned","Alex Lee",null,null,null,null]],"n":[]}) + .to_string(), + }); + crate::extraction::extract_document(&self.state, self.docs[2], Default::default()).await?; + let owners: Vec = sqlx::query_scalar("SELECT DISTINCT f.object_id FROM facts f JOIN fact_evidence fe ON fe.fact_id=f.id WHERE f.kb_id=$1 AND fe.document_id=$2 AND f.layer='open' AND f.phrase='assigned'") + .bind(self.kb).bind(self.docs[2]).fetch_all(&self.pool).await?; + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM entities WHERE kb_id=$1 AND canonical_name='Alex Lee' AND merged_into IS NULL") + .bind(self.kb).fetch_one(&self.pool).await?; + Ok(( + owners.len() == 1 && !holders.contains(&owners[0]) && count == 3, + json!({"original_candidates":holders,"object_owners":owners,"entities":count}), + )) + } + + async fn guard(&self, guard: Guard, holders: [Uuid; 2]) -> anyhow::Result<(bool, Value)> { + use Guard::*; + let simple = "Alex Lee submitted a report."; + let finance = "Alex Lee from Finance submitted a report."; + let unrelated = "Alex Lee submitted a report. Finance reviewed the annual budget."; + let shared = "Alex Lee submitted a report while Bob Chen from Finance approved it."; + let conflicting = "Alex Lee from Platform Engineering submitted a report. Alex Lee from Finance submitted a report."; + let text = match guard { + Markdown => "**Alex Lee** from Finance submitted a report.", + UngroundedQuote => simple, + Unrelated | CrossSentence => unrelated, + SharedQuote | OverlappingQuotes => shared, + ConflictingQuotes => conflicting, + _ => finance, + }; + let quote = match guard { + MissingQuote => None, + Unrelated => Some(simple), + UngroundedQuote => Some(finance), + ConflictingQuotes => Some("Alex Lee from Platform Engineering submitted a report."), + _ => Some(text), + }; + let mut entities = vec![json!(["Alex Lee", "person", 1])]; + let mut statements = vec![json!([ + quote, + "Alex Lee", + "submitted", + null, + "a report", + null, + null, + null + ])]; + match guard { + Markdown => { + // Both the folded name and a legacy formatted spelling are exact + // candidates; limiting corroboration to one spelling loses the clue. + entities[0] = json!(["**Alex Lee**", "person", 1]); + statements[0][1] = json!("**Alex Lee**"); + sqlx::query("UPDATE entities SET canonical_name='**Alex Lee**' WHERE id=$1") + .bind(holders[1]) + .execute(&self.pool) + .await?; + } + Unrelated => { + entities.push(json!(["Finance", "department", 1])); + statements.push(json!([ + "Finance reviewed the annual budget.", + "Finance", + "reviewed", + null, + "the annual budget", + null, + null, + null + ])); + } + SharedQuote | OverlappingQuotes => { + entities.push(json!(["Bob Chen", "person", 1])); + let other_quote = if guard == SharedQuote { + shared + } else { + "Bob Chen from Finance approved it." + }; + statements.push(json!([ + other_quote, + "Bob Chen", + "approved", + null, + "it", + null, + null, + null + ])); + } + ConflictingQuotes => statements.push(json!([ + finance, + "Alex Lee", + "submitted", + null, + "a report", + null, + null, + null + ])), + SharedDepartment => { + sqlx::query("UPDATE facts SET object_id=$1 WHERE kb_id=$2 AND subject_id=$3 AND layer='open'") + .bind(self.departments[1]).bind(self.kb).bind(holders[0]).execute(&self.pool).await?; + } + _ => {} + } + if matches!(guard, TypedToUntyped | UntypedToTyped | IncompatibleType) { + let person = Uuid::now_v7(); + sqlx::query( + "INSERT INTO entity_types(id,kb_id,key,label) VALUES ($1,$2,'person','Person')", + ) + .bind(person) + .bind(self.kb) + .execute(&self.pool) + .await?; + let typed_holder = if guard == UntypedToTyped { + holders[1] + } else { + holders[0] + }; + sqlx::query("UPDATE entities SET type_id=$1 WHERE id=$2") + .bind(person) + .bind(typed_holder) + .execute(&self.pool) + .await?; + if guard != UntypedToTyped { + utopia_store::type_bindings::decide( + &self.pool, + self.kb, + "person", + &[], + Some(person), + "bound", + &json!({}), + "person", + ) + .await?; + } + if guard == IncompatibleType { + let organization = Uuid::now_v7(); + sqlx::query("INSERT INTO entity_types(id,kb_id,key,label) VALUES ($1,$2,'organization','Organization')") + .bind(organization).bind(self.kb).execute(&self.pool).await?; + sqlx::query("UPDATE entities SET type_id=$1 WHERE id=$2") + .bind(organization) + .bind(holders[1]) + .execute(&self.pool) + .await?; + } + } + sqlx::query("UPDATE chunks SET text=$1 WHERE id=$2") + .bind(text) + .bind(self.chunks[2]) + .execute(&self.pool) + .await?; + let expected = + holders[usize::from(matches!(guard, TypedToUntyped | UntypedToTyped | Markdown))]; + self.model.steps.lock().unwrap().push_back(Step { + prompt_has: text.into(), + stream: true, + text: json!({"e":entities,"s":statements,"n":[]}).to_string(), + }); + crate::extraction::extract_document(&self.state, self.docs[2], Default::default()).await?; + let owners: Vec = sqlx::query_scalar("SELECT DISTINCT f.subject_id FROM facts f JOIN fact_evidence fe ON fe.fact_id=f.id WHERE f.kb_id=$1 AND fe.document_id=$2 AND f.layer='open' AND f.phrase='submitted'") + .bind(self.kb).bind(self.docs[2]).fetch_all(&self.pool).await?; + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM entities WHERE kb_id=$1 AND canonical_name IN ('Alex Lee','**Alex Lee**') AND merged_into IS NULL") + .bind(self.kb).fetch_one(&self.pool).await?; + let reviews: i64 = sqlx::query_scalar( + "SELECT count(*) FROM resolution_reviews WHERE kb_id=$1 AND status='pending'", + ) + .bind(self.kb) + .fetch_one(&self.pool) + .await?; + let type_preserved = if guard == TypedToUntyped { + sqlx::query_scalar::<_, bool>("SELECT type_id IS NULL FROM entities WHERE id=$1") + .bind(expected) + .fetch_one(&self.pool) + .await? + } else { + true + }; + Ok(( + owners == vec![expected] && count == 2 && reviews == 0 && type_preserved, + json!({"expected_owner":expected,"owners":owners,"entities":count,"pending_reviews":reviews,"type_preserved":type_preserved}), + )) + } + async fn cleanup(&self) -> anyhow::Result<()> { self.server.abort(); sqlx::query( @@ -394,7 +670,7 @@ async fn scripted_namesake_cases_have_only_the_named_known_failures() -> anyhow: let mut mismatches = Vec::new(); let mut seen = Vec::new(); let mut failed = 0; - for case in &CASES { + for case in CASES { for reverse in [false, true] { let order = if reverse { "reverse" } else { "forward" }; let org = Uuid::now_v7(); diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rs index 27e835335..965350d3f 100644 --- a/crates/utopia-store/src/resolution.rs +++ b/crates/utopia-store/src/resolution.rs @@ -243,6 +243,8 @@ fn cosine(a: &[f32], b: &[f32]) -> Option { struct Candidate { id: Uuid, canonical_name: String, + type_id: Option, + exact_name: bool, profile_embedding: Option, profile_n: i32, } @@ -492,8 +494,8 @@ async fn resolve_by_name( type_id: Option, raw_name: &str, context: Option<&[f32]>, - // 这次提及所在的**块原文**。画像分不出谁是谁时拿它做事实旁证(#331)—— - // 传整篇文档会让每个部门都命中,所以这里要的是句子或块,不是文档。 + // Grounded quotes owned by this mention's subject, supplied by the extractor. + // A whole chunk can mention another person's department and is not identity evidence. text: Option<&str>, // Candidates already claimed by a different response-local handle. They remain stored // and recallable on later calls, but this mention cannot attach to them. @@ -508,29 +510,66 @@ async fn resolve_by_name( let name = fold_markdown_markers(&normalized); // 名字召回读名字事实(0041 决定 1):本名、简称、曾用名都是 `known_as` 上的一条。 // 度数不数名字事实——名字不是一条「关于它的事」,数进去每个实体都凭空多一 - // 度数要等真有几个候选得比时才数:每个候选一条计数子查询,大库上很贵(#1296) - let candidates: Vec = sqlx::query_as(&format!( - "SELECT e.id, e.canonical_name, e.profile_embedding, e.profile_n + // Keep degree counting lazy, including when corroboration widens exact-name recall. + let mut candidates: Vec = sqlx::query_as(&format!( + "SELECT e.id, e.canonical_name, e.type_id, e.profile_embedding, e.profile_n, + (lower(e.canonical_name) = ANY($4) OR {exact_named}) AS exact_name FROM entities e -- IS NOT DISTINCT FROM 而不是 =(0009 的那个陷阱):开放图谱里的实体都没有类 -- (类由对齐来定),`type_id = NULL` 永远不成立,同名的它就永远撞不上—— -- 实测一个库里 Securities and Exchange Commission 与它的全大写写法成了两个实体 - WHERE e.kb_id = $1 AND e.type_id IS NOT DISTINCT FROM $2 AND e.merged_into IS NULL + WHERE e.kb_id = $1 AND e.merged_into IS NULL + AND (e.type_id IS NOT DISTINCT FROM $2 + OR ($5 AND ($2::uuid IS NULL OR e.type_id IS NULL) + AND (lower(e.canonical_name) = ANY($4) OR {exact_named}))) -- 被描述的东西没有名字(0044):它的 canonical_name 只是显示用的描述, -- 不是召回的桥——两篇文档里描述得一样的两个东西不能因此接到一起 AND e.description IS NULL AND (lower(e.canonical_name) = ANY($3) OR {named})", named = crate::names::has_name_in("e", 1, 3), + exact_named = crate::names::has_name_in("e", 1, 4), )) .bind(kb_id) .bind(type_id) .bind(&keys) + // Match both the folded spelling and already-stored formatting, as recall does. + .bind(vec![name.to_lowercase(), normalized.to_lowercase()]) + .bind(text.is_some()) .fetch_all(pool) .await? .into_iter() .filter(|candidate: &Candidate| !exclude.contains(&candidate.id)) .collect(); + // A clear mention-local clue outranks the chunk's profile, even outside the tie + // margin. Include exact names whose class is not yet known on either side, but + // do not let that wider recall change profile fallback or classify the winner. + let tier_evidence = if let Some(text) = text { + let exact: Vec<_> = candidates.iter().filter(|c| c.exact_name).collect(); + if exact.len() > 1 { + if let Some(c) = corroborating_candidate(pool, kb_id, &exact, text).await? { + if let Some(ctx) = context { + update_profile(pool, c.id, c.profile_n, ctx).await?; + } else { + touch_entity(pool, c.id).await?; + } + return Ok(Resolution { + entity_id: c.id, + created: false, + reviews: Vec::new(), + }); + } + // Shared/conflicting clues must not become unique by retrying a smaller + // subset (the best two profiles, or only candidates above SIM_NEW). + None + } else { + Some(text) + } + } else { + None + }; + candidates.retain(|c| c.type_id == type_id); + if candidates.is_empty() { // 同类型无候选 ≠ 新名字:类型标签会漂(同一团队被抽成 organization/project/ // concept),先查其它类型下的同名实体,按类型对的互斥强度分流。 @@ -609,7 +648,7 @@ async fn resolve_by_name( { // 画像掷硬币之前,先问事实(#331):这句话里提到了其中一个人的 // 部门或职位吗?提到了就不是硬币,是线索 - if let Some(t) = text { + if let Some(t) = tier_evidence { if let Some(c) = corroborating_candidate(pool, kb_id, &[best, runner], t).await? { @@ -684,7 +723,7 @@ async fn resolve_by_name( // 这句话里若正好写着某一个候选的部门或职位,那比余弦值可靠。 // **只认灰区**(≥ SIM_NEW):分数低于它的候选连审核对都不配入队, // 拿一条旁证把它拉成同一人,等于绕过阈值而不是补充它。 - if let Some(t) = text { + if let Some(t) = tier_evidence { let in_grey: Vec<&Candidate> = scored .iter() .filter(|(_, s)| *s >= SIM_NEW) diff --git a/docs/decisions/0013-a-source-should-hand-over-its-history.md b/docs/decisions/0013-a-source-should-hand-over-its-history.md index 0fed62a3b..a8c1631f4 100644 --- a/docs/decisions/0013-a-source-should-hand-over-its-history.md +++ b/docs/decisions/0013-a-source-should-hand-over-its-history.md @@ -1,6 +1,6 @@ # 0013 · A source hands over its history -- **Status**: Implemented for GitHub, Jira and Notion (#134, #135, #213) · open: Feishu, Confluence +- **Status**: Implemented for GitHub, Jira and Notion (#134, #135, #213) · open: Feishu, Confluence, decision 7 (#1327) - **Written**: 2026-08-31 · condensed into English 2026-09-03 - **Related**: the bitemporal ground of [0001](0001-ontology-import-and-governance.md); the same judgment on the corpus side in `scripts/bench/fetch-wiki-history.mjs` (#122); [0012](0012-the-ontology-is-a-contract-not-a-suggestion.md) is the other end of the line — this record is about how things come in, that one about the rules they land by; the grant layer added afterwards (#142, `data_source_grants`) decides who may mount a source: provenance visible, destination governed @@ -83,6 +83,61 @@ Wikipedia; there revisions have to be sampled, an issue tracker hands the events render in UTC (local conversion shows a UTC-5 reader the previous day); `recorded_at` is a real instant and renders in the viewer's timezone. The difference is intentional. +7. **Three trackers share one ticket document, not one fetch.** *Added 2026-10-22 (#1327).* + Decision 1 already made the document the shared part, but each connector carries its own + `render()`, and the shape has drifted in small ways: GitHub opens with "Opened by", Jira with + "Reported by"; #691 changed the timestamps twice, with two comments saying the same thing. A third + copy for GitLab triples that. So a pure `ticket::render(&Ticket)` owns the document: the + heading, the dated sentences, `## Description`, a `## History` sorted by time, `## Comments`. + Each connector maps its payload into `Ticket` and keeps its own fetch: three pulls with `since` + for GitHub, one JQL call for Jira, and for GitLab a list per kind plus, per ticket, its notes and + its `resource_state_events`, `resource_label_events` and `resource_milestone_events`. Still no + provider trait: the fetch strategies are as different as the dead end says, and they stay in + their own modules. + + `Ticket` holds what the two renderers write today, in the order each writes it, and nothing + that would let `render` reword it: + + - `heading`: the title line after `# ` (`#12 Fix it`, `KAFKA-1 Summary`, `!7 Fix it`); + - `sentences`: the dated and plain sentences under the heading, each already worded and in the + connector's own order (GitHub: opened, state, closed, labels, assignees; Jira: reported, + type, state, priority, assignee, resolved, labels); + - `description`: the body under `## Description`, or none; + - `history`: `(time, text)` pairs written as `-