From f21ab02310c2aa1c3a4d36682ffe40a2942fe064 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:34:10 +0800 Subject: [PATCH 1/2] Search the whole request history, including request and answer text The Traffic page filters only the rows it loaded (the latest 2000), while the store keeps request rows for 90 days. This adds POST /history/search, which runs the same filter in the store and pages back through all of it. - Filters reproduce Lite's filterRows exactly: failed only, unpriced only (finished, reported usage, no cost), exact client / upstream / model, and a free-text query over path, client, client hint, peer, upstream, model and the error text. Error codes whose translation contains the query and a flag for the UI's "answered locally" sentence cover what the UI shows in its own language. - Matching runs in SQL through a small `tw_has()` function with the same Unicode lowercasing as JavaScript's toLowerCase (SQLite's LIKE folds ASCII only and treats % and _ as wildcards). It walks the at_ms index: 100k rows with no match take ~32 ms in a release build. - Pages are cursored by (at_ms, id), stable when rows share a timestamp; default 100 rows, at most 500. - Content search (`content: true`) also looks at the last user turn of each request (text and tool results, not the resent history) and the text of the answer, parsed with tw-dialect for all formats, streamed or whole. Each call reads at most 500 requests' bodies or runs 1.5 s, then returns what it found with a cursor to continue; rows older than the oldest body directory are matched by their record only. Content hits carry a short excerpt, masked like the request detail view. No schema change; CONTROL_API_VERSION and crate versions are unchanged. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 + crates/tw-api/src/ep.rs | 2 + crates/tw-api/src/lib.rs | 128 ++ crates/tw-api/src/ts.rs | 33 + crates/tw-control/src/lib.rs | 44 + crates/tw-control/tests/history_search.rs | 282 +++++ crates/tw-store/Cargo.toml | 8 +- crates/tw-store/src/blobs.rs | 63 + crates/tw-store/src/db.rs | 35 +- crates/tw-store/src/lib.rs | 1 + crates/tw-store/src/search/mod.rs | 1408 +++++++++++++++++++++ crates/tw-store/src/search/needle.rs | 572 +++++++++ crates/tw-store/src/search/sql.rs | 156 +++ crates/tw-store/src/search/text.rs | 591 +++++++++ scripts/smoke.sh | 27 + 15 files changed, 3350 insertions(+), 2 deletions(-) create mode 100644 crates/tw-control/tests/history_search.rs create mode 100644 crates/tw-store/src/search/mod.rs create mode 100644 crates/tw-store/src/search/needle.rs create mode 100644 crates/tw-store/src/search/sql.rs create mode 100644 crates/tw-store/src/search/text.rs diff --git a/Cargo.lock b/Cargo.lock index 6cfadc9d..34339dac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2983,8 +2983,10 @@ dependencies = [ "tokio", "tracing", "tw-api", + "tw-dialect", "tw-observe", "tw-pricing", + "tw-secret", ] [[package]] diff --git a/crates/tw-api/src/ep.rs b/crates/tw-api/src/ep.rs index 68c73814..0578f6ff 100644 --- a/crates/tw-api/src/ep.rs +++ b/crates/tw-api/src/ep.rs @@ -45,6 +45,8 @@ endpoints! { /// 各条路由走了多少请求、各条规则命中了多少,记录从哪一刻起是全的 RouteStats: GET "/summary/routes", api::Window => api::RouteStats; History: GET "/history", api::ListQuery => Vec; + /// 在整份记录里找,一页一页往回翻;也可以按正文找 + HistorySearch: POST "/history/search", api::HistorySearchQuery => api::HistorySearchPage; Latency: GET "/latency", api::Window => Vec; LatencyByProvider: GET "/latency/provider", api::Window => Vec; /// 生成速度的中位数,按模型、按上游 diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 7d0b0c7f..45bd014c 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -2952,6 +2952,72 @@ pub struct ListQuery { pub limit: Option, } +/// 在整份请求记录里找(`POST /history/search`)。 +/// +/// **筛法和流量页的筛选框一模一样**(桌面端 `requestTable.ts` 的 `filterRows`),只是 +/// 搬到了库里:那边只筛得到读进来的最近两千条,记录却留着三个月。几个条件之间是「且」。 +/// +/// 走请求体而不是查询串:错误码是一张清单,查询串放不下清单(core 读查询串用的 +/// `serde_urlencoded` 不认序列)。 +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct HistorySearchQuery { + /// 自由文本。**去掉首尾空白、不分大小写**,按子串对:路径、密钥名、按请求头 + /// 认出的应用、来源地址、上游、模型、失败原因,任何一样里有就算。空的是不按 + /// 文本筛 + #[serde(default, skip_serializing_if = "String::is_empty")] + pub q: String, + /// 只要失败的 + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub failed: bool, + /// 只要无法计价的:跑完了、报了用量,却没算出金额。还在跑的、失败的、取消的、 + /// 没报用量的不算 —— 它们没有金额是另一回事,和概览上「无法计价」那个数是同一批 + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub unpriced: bool, + /// 只要这把密钥的,整个名字相等。空串和不给一样 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client: Option, + /// 只要这个上游服务的,整个名字相等。本地应答的没有上游,按上游筛时一条都不留 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provider: Option, + /// 只要这个模型的,**整个名字相等** —— 点 gpt-5.5 不该带出 gpt-5.5-codex + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, + /// 失败原因按码也算对上:界面上那句话是按码翻的,库里只有英文原句。界面把 + /// **译文里含着 `q` 的那些码**交过来;英文原句照样按 `q` 对 + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub error_codes: Vec, + /// 本地应答的那几行「上游」一格写的是界面自己的一句说明(按当时的语言)。那句话 + /// 里含着 `q` 时界面交 `true`,本地应答的就都算对上 + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub local_matches: bool, + /// 也按正文找:请求里新的那一轮(最后一条用户消息,含工具结果)和回答的文字。 + /// 只有正文还在盘上的那些能这样找,更早的照样按上面那几样对。没有 `q` 时不起作用 + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub content: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub from_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub to_ms: Option, + /// 从这一条往前接着找:上一页的 [`HistorySearchPage::next`] + #[serde(default, skip_serializing_if = "Option::is_none")] + pub before: Option, + /// 一页最多几条。缺省 100、最多 500 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +/// 记录里的一个位置:一条请求开始的时刻和它的请求号。 +/// +/// **两样一起才定得住。**同一毫秒里开始的请求不止一条(并发的子代理、同时发出的 +/// 几个工具调用),只按时刻翻页,落在页缝上的那几条不是漏掉就是重复。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct HistoryCursor { + pub at_ms: i64, + pub id: i64, +} + /// 安全日志一页要的:哪一项、哪一段、从哪条往前、几条(`GET /security/events`)。 /// 缺省是全部,不是今天;条数缺省 100、最多 500。 #[derive(Debug, Clone, Default, Serialize, Deserialize)] @@ -3312,6 +3378,68 @@ pub struct HistoryRow { pub security: Vec, } +/// 搜索的一页(`POST /history/search`),新的在前。 +/// +/// **按正文找的那一页不一定满。**正文要一份一份从盘上读,一次只读一定的量(见 +/// `stopped`),读完就把找到的先交回来;`next` 说从哪儿接着找,`next.at_ms` 就是 +/// 这一次往回找到了哪一刻。 +#[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct HistorySearchPage { + /// 对上的请求,和 `GET /history` 同一个样子 + pub rows: Vec, + /// 按正文对上的那些各自对上了哪一段,一条请求一项。按记录就对上的不在这里 + /// (没有去读它的正文) + pub hits: Vec, + /// 下一页从哪儿接着找:交回去当 [`HistorySearchQuery::before`]。`None` 是整段都 + /// 找完了 + pub next: Option, + /// 按正文找时:正文最早留到哪一刻(盘上最老的那一天的零点,UTC)。比它早的 + /// 正文已经清掉了,那些请求只按记录对。没按正文找、或者盘上一份正文都没有时 + /// 是 `None` + pub bodies_since_ms: Option, + /// 这一页为什么停在这里 + pub stopped: SearchStop, +} + +slug_enum! { + /// 一页搜索停在哪儿的原因。 + pub enum SearchStop { + /// 凑够了一页 + Full = "full", + /// 正文读够了这一次的量,往前还没找。再问一次接着找 + Budget = "budget", + /// 整段都找完了 + End = "end", + } +} + +/// 一条请求的正文里对上的那一段:命中的前后各四十来个字,空白并成一个空格, +/// **已脱敏**(和详情抽屉里的正文同一套打码)。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct ContentHit { + /// 哪条请求 + pub id: i64, + pub side: ContentSide, + /// 命中之前的那一段。前面还有字时以 `…` 开头 + pub before: String, + /// 命中的那一段,原文的大小写 + pub matched: String, + /// 命中之后的那一段。后面还有字时以 `…` 结尾 + pub after: String, +} + +slug_enum! { + /// 正文里的哪一边。 + pub enum ContentSide { + /// 请求里新的那一轮:最后一条用户消息,含工具结果 + Request = "request", + /// 回答的文字 + Answer = "answer", + } +} + /// 一次请求做过的格式转换。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] diff --git a/crates/tw-api/src/ts.rs b/crates/tw-api/src/ts.rs index 86990752..de425ba1 100644 --- a/crates/tw-api/src/ts.rs +++ b/crates/tw-api/src/ts.rs @@ -222,6 +222,39 @@ mod tests { assert!(ts.contains(" RouteStats: { req: Window; res: RouteStats };")); } + /// 搜索的一页:接着找的位置和正文留到哪一刻是必有的字段,没有时是 null;请求里 + /// 不给的条件可以整个省掉 + #[test] + fn a_search_page_says_where_to_go_on_from() { + let ts = typescript(); + let page = decl_of(&ts, "HistorySearchPage"); + assert!(page.contains("rows: Array"), "{page}"); + assert!(page.contains("hits: Array"), "{page}"); + assert!(page.contains("next: HistoryCursor | null"), "{page}"); + assert!(page.contains("bodies_since_ms: number | null"), "{page}"); + assert!(page.contains("stopped: SearchStop"), "{page}"); + let q = decl_of(&ts, "HistorySearchQuery"); + for field in [ + "q?: string", + "failed?: boolean", + "error_codes?: Array", + "before?: HistoryCursor", + "limit?: number", + ] { + assert!(q.contains(field), "{field}: {q}"); + } + assert_eq!( + decl_of(&ts, "SearchStop"), + "export type SearchStop = \"full\" | \"budget\" | \"end\"" + ); + assert!( + ts.contains(" HistorySearch: { req: HistorySearchQuery; res: HistorySearchPage };") + ); + assert!(ts.contains( + " HistorySearch: { method: \"POST\", path: \"/history/search\", params: [], format: \"json\" }," + )); + } + #[test] fn every_endpoint_is_in_the_table() { let ts = typescript(); diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 1e2b95a6..dd6fff50 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -110,6 +110,7 @@ pub fn router(state: ControlState) -> Router { .at(ep::CostBy, cost_by) .at(ep::RouteStats, route_stats) .at(ep::History, history) + .at(ep::HistorySearch, history_search) .at(ep::Latency, latency) .at(ep::LatencyByProvider, latency_by_provider) .at(ep::TokenRate, token_rate) @@ -770,6 +771,49 @@ async fn history( )) } +/// 在整份记录里找,一页一页往回翻(见 `tw_store::search`)。 +/// +/// **放到阻塞线程上跑**:按正文找要读盘、解析几百 KB 的 JSON,只按记录找也可能要把十万 +/// 条扫一遍,都不该占着异步线程。库只在取一批行的时候锁一下 —— 记录和正文的落盘走的是 +/// 同一把锁,读正文时一直攥着它的话,这一秒半里刚结束的请求都要排队。 +async fn history_search( + State(s): State, + Json(q): Json, +) -> Result, Fail> { + let store = need_store(&s)?.clone(); + let query = tw_store::search::Query::new(&q); + // 正文目录只是一个路径,读它不需要锁 + let blobs = tw_store::Blobs::new(store.lock().await.blobs().root().to_path_buf()); + let found = { + let store = store.clone(); + tokio::task::spawn_blocking(move || { + tw_store::search::run(&query, &blobs, tw_store::search::Budget::DEFAULT, |ask| { + store.blocking_lock().db().search_rows(ask) + }) + }) + .await + .map_err(internal)? + .map_err(records)? + }; + // 这一页的安全记录,徽标靠它(和 `GET /history` 一样) + let ids: Vec = found.rows.iter().map(|r| r.id).collect(); + let mut security = store.lock().await.db().security_of(&ids).map_err(records)?; + Ok(Json(tw_api::HistorySearchPage { + rows: found + .rows + .into_iter() + .map(|r| { + let sec = security.remove(&r.id).unwrap_or_default(); + history_row(r, sec) + }) + .collect(), + hits: found.hits, + next: found.next, + bodies_since_ms: found.bodies_since_ms, + stopped: found.stopped, + })) +} + async fn latency( State(s): State, axum::extract::Query(q): axum::extract::Query, diff --git a/crates/tw-control/tests/history_search.rs b/crates/tw-control/tests/history_search.rs new file mode 100644 index 00000000..3263f68d --- /dev/null +++ b/crates/tw-control/tests/history_search.rs @@ -0,0 +1,282 @@ +//! `POST /history/search` 交给界面的那份 JSON。 +//! +//! 怎么筛、怎么翻页、怎么读正文在 tw-store 里测;这里盯的是**线上的样子**:行和 +//! `GET /history` 同一个形状(安全记录挂在行上),按正文对上的带着摘录,翻页的位置和 +//! 停下的原因都在。 + +use std::sync::Arc; + +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use tower::ServiceExt; +use tw_control::{ConfigManager, ControlState}; + +const BASE: &str = "version: 1\nlisten:\n control:\n key: c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00\nclients:\n - name: 我\n key: tw-一把钥匙就够\nproviders:\n - name: 官方\n base_url: https://api.anthropic.com\n key: sk-x\n"; + +/// 一条请求:现在开始的,`id` 越大越新 +fn req(id: i64, client: &str) -> tw_store::db::RequestRow { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as i64; + tw_store::db::RequestRow { + session_log_bytes: None, + key_masked: None, + peer: None, + id, + at_ms: now - 1000 + id, + client: client.into(), + client_hint: Some("claude-code".into()), + session: None, + provider: "官方".into(), + model: "claude-sonnet-4-5".into(), + path: "/v1/messages".into(), + status: Some(200), + ttfb_ms: Some(100), + ttft_ms: Some(300), + duration_ms: Some(2000), + tokens_per_sec: Some(80), + bytes: Some(10), + input_tokens: Some(50), + output_tokens: Some(20), + cache_read_tokens: None, + cache_write_tokens: None, + cost_micros: Some(1_000), + cost_estimated: false, + error: None, + local: false, + cancelled: false, + routing: None, + billing: tw_api::Billing::PerToken, + cache_saved_micros: None, + price_source: None, + translated: None, + } +} + +/// 一个带着请求库和正文目录的控制面。`bodies`:(请求号, 请求体) +fn app( + rows: &[tw_store::db::RequestRow], + bodies: &[(i64, String)], +) -> (tempfile::TempDir, axum::Router) { + let d = tempfile::tempdir().unwrap(); + let p = d.path().join("config.yaml"); + std::fs::write(&p, BASE).unwrap(); + let db = tw_store::Db::open(&d.path().join("data.db")).unwrap(); + let blobs = tw_store::Blobs::new(d.path().join("blobs")); + for r in rows { + db.insert(r).unwrap(); + if let Some((_, body)) = bodies.iter().find(|(id, _)| *id == r.id) { + assert!(blobs.put(r.at_ms, r.id, tw_store::Which::Request, body.as_bytes())); + } + } + db.insert_security_event(&tw_store::SecurityEvent { + at_ms: rows[0].at_ms, + request_id: rows[0].id, + guard: tw_api::Guard::Redact, + rule: "anthropic".into(), + custom: false, + action: tw_api::SecurityOutcome::Replaced, + provider: "官方".into(), + client: "我".into(), + tool: None, + excerpt: "sk-an…".into(), + count: 1, + }) + .unwrap(); + let rec = tw_store::Recorder::new( + db, + blobs, + tw_pricing::shared(tw_pricing::PriceBook::builtin().unwrap()), + ); + let cfg: tw_config::Config = serde_yaml_ng::from_str(BASE).unwrap(); + let gw = tw_gateway::AppState::new(cfg).unwrap(); + let bus = gw.bus.clone(); + let state = ControlState { + shutdown: Default::default(), + remote: Default::default(), + cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), + gateway: gw, + store: Some(Arc::new(tokio::sync::Mutex::new(rec))), + started: std::time::Instant::now(), + price_updater: Default::default(), + chatgpt: Default::default(), + zai: Default::default(), + }; + (d, tw_control::router(state)) +} + +async fn search(app: &axum::Router, q: serde_json::Value) -> serde_json::Value { + let r = app + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri(::PATH) + .header("content-type", "application/json") + .body(Body::from(q.to_string())) + .unwrap(), + ) + .await + .unwrap(); + let st = r.status(); + let b = axum::body::to_bytes(r.into_body(), 1 << 20).await.unwrap(); + assert_eq!(st, StatusCode::OK, "{}", String::from_utf8_lossy(&b)); + // 照契约的类型读得回来:界面拿到的就是这个形状 + serde_json::from_slice::(&b).unwrap(); + serde_json::from_slice(&b).unwrap() +} + +fn ids(page: &serde_json::Value) -> Vec { + page["rows"] + .as_array() + .unwrap() + .iter() + .map(|r| r["id"].as_i64().unwrap()) + .collect() +} + +#[tokio::test] +async fn a_record_search_pages_back_with_the_history_row_shape() { + let rows: Vec<_> = (1..=5) + .map(|i| req(i, if i % 2 == 0 { "codex" } else { "我" })) + .collect(); + let (_d, app) = app(&rows, &[]); + + // 什么条件都不给:最近的在前,和 `GET /history` 一样 + let p = search(&app, serde_json::json!({})).await; + assert_eq!(ids(&p), [5, 4, 3, 2, 1]); + assert_eq!(p["stopped"], "end"); + assert!(p["next"].is_null(), "{p}"); + assert!(p["bodies_since_ms"].is_null(), "{p}"); + // 行和 `GET /history` 同一个样子,安全记录挂在行上 + let first = &p["rows"][4]; + assert_eq!(first["client_hint"], "claude-code"); + assert_eq!(first["security"][0]["guard"], "redact", "{first}"); + + // 一页两条:`next` 交回去接着翻 + let p = search(&app, serde_json::json!({"q": "CODEX", "limit": 1})).await; + assert_eq!(ids(&p), [4]); + assert_eq!(p["stopped"], "full"); + let next = p["next"].clone(); + assert_eq!(next["id"], 4); + let p = search( + &app, + serde_json::json!({"q": "codex", "limit": 1, "before": next}), + ) + .await; + assert_eq!(ids(&p), [2]); + // 正好是最后一条:说找完了 + assert_eq!(p["stopped"], "end", "{p}"); +} + +#[tokio::test] +async fn a_content_search_brings_back_a_masked_excerpt() { + let rows: Vec<_> = (1..=3).map(|i| req(i, "我")).collect(); + let body = |text: &str| { + serde_json::json!({"model": "claude-sonnet-4-5", + "messages": [{"role": "user", "content": text}]}) + .to_string() + }; + let (_d, app) = app( + &rows, + &[ + ( + 1, + body("我的 key 是 sk-ant-api03-WIREKEYAAAAAAAAAAAAAAAAAAAA,帮我看看"), + ), + (2, body("别的话")), + ], + ); + let p = search(&app, serde_json::json!({"q": "我的 key", "content": true})).await; + assert_eq!(ids(&p), [1]); + let hit = &p["hits"][0]; + assert_eq!(hit["id"], 1); + assert_eq!(hit["side"], "request"); + assert_eq!(hit["matched"], "我的 key"); + let after = hit["after"].as_str().unwrap(); + assert!(after.starts_with(" 是 sk-an…"), "{hit}"); + assert!(!after.contains("WIREKEYAAAA"), "摘录里漏了密钥:{hit}"); + assert!(p["bodies_since_ms"].as_i64().is_some(), "{p}"); + assert_eq!(p["stopped"], "end"); + // 不开正文:只按记录找,正文里的词找不到 + let p = search(&app, serde_json::json!({"q": "我的 key"})).await; + assert!(ids(&p).is_empty(), "{p}"); + assert!(p["bodies_since_ms"].is_null()); +} + +#[tokio::test] +async fn without_a_store_the_search_says_recording_is_unavailable() { + let d = tempfile::tempdir().unwrap(); + let p = d.path().join("config.yaml"); + std::fs::write(&p, BASE).unwrap(); + let cfg: tw_config::Config = serde_yaml_ng::from_str(BASE).unwrap(); + let gw = tw_gateway::AppState::new(cfg).unwrap(); + let bus = gw.bus.clone(); + let app = tw_control::router(ControlState { + shutdown: Default::default(), + remote: Default::default(), + cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), + gateway: gw, + store: None, + started: std::time::Instant::now(), + price_updater: Default::default(), + chatgpt: Default::default(), + zai: Default::default(), + }); + let r = app + .oneshot( + Request::builder() + .method("POST") + .uri("/history/search") + .header("content-type", "application/json") + .body(Body::from("{}")) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(r.status(), StatusCode::SERVICE_UNAVAILABLE); + let b = axum::body::to_bytes(r.into_body(), 1 << 20).await.unwrap(); + let m: tw_api::ErrorBody = serde_json::from_slice(&b).unwrap(); + assert_eq!(m.code, "control.store_unavailable"); +} + +/// 按正文找只读生成回答的请求,**认路径的办法和网关是同一个**:网关只解码这些请求, +/// 记录里存的也是它们的请求体。两边各写一份(tw-store 不能依赖网关),这里逐条核对。 +#[test] +fn the_store_reads_the_same_paths_as_generation_calls_as_the_gateway() { + use tw_gateway::client_api::ClientApi; + for path in [ + "/v1/messages", + "/messages", + "/v1/messages/", + "/v1/messages/count_tokens", + "/v1/complete", + "/v1/chat/completions", + "/chat/completions", + "/v1/completions", + "/v1/embeddings", + "/v1/responses", + "/v1/responses/compact", + "/responses", + "/backend-api/codex/responses", + "/backend-api/codex/responses/compact", + "/v1beta/models/gemini-2.5-pro:generateContent", + "/v1beta/models/gemini-2.5-pro:streamGenerateContent", + "/v1/models/gemini-2.5-flash:generateContent", + "/v1beta/models/gemini-2.5-pro:countTokens", + "/v1beta/models/text-embedding-004:embedContent", + "/v1/models", + "/health_check", + "/", + ] { + let gateway = ClientApi::of_path(path) + .filter(|_| ClientApi::generates(path)) + .map(|a| a.dialect()); + assert_eq!( + tw_store::search::text::client_dialect(path), + gateway, + "{path}" + ); + } +} diff --git a/crates/tw-store/Cargo.toml b/crates/tw-store/Cargo.toml index d0ae45b8..4e7784bf 100644 --- a/crates/tw-store/Cargo.toml +++ b/crates/tw-store/Cargo.toml @@ -14,8 +14,14 @@ description = "Request history and runtime state on SQLite and the filesystem" tw-api = { workspace = true } tw-observe = { workspace = true } tw-pricing = { workspace = true } +# 按正文找:请求和回答怎么拆成文字,四种格式的读法都在这里,不另写一份 +tw-dialect = { workspace = true } +# 按正文找时交出去的那一小段要和详情抽屉同一套打码 +tw-secret = { workspace = true } bytes = { workspace = true } -rusqlite = { workspace = true } +# functions:搜索要一个 SQL 函数,按界面同一种小写规则比子串(见 `search::sql`)。 +# 只是打开 rusqlite 已有的接口,不多编任何东西 +rusqlite = { workspace = true, features = ["functions"] } serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } diff --git a/crates/tw-store/src/blobs.rs b/crates/tw-store/src/blobs.rs index 1b14ff57..fe9f2bda 100644 --- a/crates/tw-store/src/blobs.rs +++ b/crates/tw-store/src/blobs.rs @@ -41,6 +41,26 @@ fn day_of(at_ms: i64) -> String { format!("{y:04}-{m:02}-{d:02}") } +/// 一天的目录名换回那一天零点(UTC)的毫秒数,[`day_of`] 反过来。不是日期的是 `None`。 +fn start_of_day(name: &str) -> Option { + if !looks_like_a_day(name) { + return None; + } + let y: i64 = name[0..4].parse().ok()?; + let m: i64 = name[5..7].parse().ok()?; + let d: i64 = name[8..10].parse().ok()?; + if !(1..=12).contains(&m) || !(1..=31).contains(&d) { + return None; + } + // 同一位的 days_from_civil:三月算一年的头一个月,闰日落在年末 + let y = if m <= 2 { y - 1 } else { y }; + let era = y.div_euclid(400); + let yoe = y - era * 400; + let doy = (153 * ((m + 9) % 12) + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + Some((era * 146_097 + doe - 719_468) * 86_400_000) +} + impl Blobs { pub fn new(root: PathBuf) -> Self { Self { root } @@ -159,6 +179,15 @@ impl Blobs { out } + /// 盘上最老的那一天从哪一刻起(那天零点,UTC)。一天都没有是 `None`。 + /// + /// **按正文找时用它划界**:比它早的请求一份正文都不会有,不必一条一条去盘上问 —— + /// 三个月的记录里,正文只占最近几天。回收是整天整天地删(先删最老的),所以划在 + /// 最老的那一天上是准的。 + pub fn oldest_ms(&self) -> Option { + self.days().first().and_then(|(name, _)| start_of_day(name)) + } + /// 回收:先按天数删,再按总量删。返回删掉的字节数。 pub fn gc(&self, now_ms: i64, keep_days: u64, max_bytes: u64) -> u64 { let cutoff = day_of(now_ms - (keep_days as i64) * 86_400_000); @@ -301,6 +330,40 @@ mod tests { assert_eq!(day_of(951_782_400_000), "2000-02-29"); } + /// 目录名换回那一天的零点:和 `day_of` 互为反函数,闰日、世纪年都对得上 + #[test] + fn a_day_name_turns_back_into_the_start_of_that_day() { + for ms in [ + 0, + DAY - 1, + 1_709_164_800_000, + 951_782_400_000, + 1_788_912_000_000 + 12_345_678, + -DAY, + ] { + let start = start_of_day(&day_of(ms)).unwrap(); + assert_eq!(start, ms - ms.rem_euclid(DAY), "{}", day_of(ms)); + } + for d in 0..2000 { + assert_eq!(start_of_day(&day_of(d * DAY + 1)), Some(d * DAY)); + } + assert_eq!(start_of_day("2026-13-01"), None); + assert_eq!(start_of_day("我的备份"), None); + } + + #[test] + fn the_oldest_day_on_disk_is_where_bodies_start() { + let (_d, b) = setup(); + assert_eq!(b.oldest_ms(), None, "一份正文都没有"); + b.put(10 * DAY + 5, 1, Which::Request, b"x"); + b.put(12 * DAY + 5, 2, Which::Request, b"y"); + // 用户自己放的目录不算一天 + std::fs::create_dir_all(b.root().join("0000-backup")).unwrap(); + assert_eq!(b.oldest_ms(), Some(10 * DAY)); + b.gc(13 * DAY, 1, MAX_BYTES); + assert_eq!(b.oldest_ms(), Some(12 * DAY)); + } + #[test] fn day_names_sort_the_same_way_the_days_do() { // 回收靠字典序找「最旧的」。位数变化时字典序和时间序分家的话, diff --git a/crates/tw-store/src/db.rs b/crates/tw-store/src/db.rs index 5d5f6ff2..64af1b51 100644 --- a/crates/tw-store/src/db.rs +++ b/crates/tw-store/src/db.rs @@ -189,6 +189,11 @@ impl Db { Self::from_conn(Connection::open_in_memory()?) } + /// 给同一个 crate 里另写在别处的查询用(搜索在 `crate::search`) + pub(crate) fn conn(&self) -> &Connection { + &self.conn + } + fn from_conn(conn: Connection) -> Result { // WAL:读不挡写。**界面在查历史的同时数据面在写** —— 默认的 // rollback journal 下那是互相阻塞的。 @@ -198,6 +203,8 @@ impl Db { // 而配置文件那边是原子写加 fsync,因为那份丢不起。 conn.pragma_update(None, "synchronous", "NORMAL")?; conn.busy_timeout(std::time::Duration::from_secs(5))?; + // 搜索用的 SQL 函数。装在连接上,不进库文件:每次打开都要装 + crate::search::register(&conn)?; let found: i64 = conn.pragma_query_value(None, "user_version", |r| r.get(0))?; if found != 0 && found != SCHEMA { return Err(DbError::OtherVersion { @@ -836,6 +843,32 @@ impl Db { Ok(out) } + /// 这几条请求的安全记录,按请求号分好。 + /// + /// 搜索翻出来的那一页散在整份记录里,按请求号的范围取([`Db::security_of_requests`]) + /// 会把中间几万条请求的记录一起取回来,所以按号点名。 + pub fn security_of( + &self, + ids: &[i64], + ) -> Result>, DbError> { + let mut out: std::collections::HashMap> = + Default::default(); + if ids.is_empty() { + return Ok(out); + } + let mut st = self.conn.prepare(&format!( + "{SECURITY_SELECT} + WHERE e.request_id IN (SELECT value FROM json_each(?1)) + ORDER BY e.id" + ))?; + let ids = serde_json::to_string(ids).unwrap_or_default(); + for r in st.query_map([ids], security_view)? { + let r = r?; + out.entry(r.request_id).or_default().push(r); + } + Ok(out) + } + /// 一段时间里各项防护各留下了几条记录。**和日志数的是同一批。** pub fn security_counts( &self, @@ -1254,7 +1287,7 @@ fn error_from(r: &rusqlite::Row) -> rusqlite::Result> { Ok(Some(Msg { code, args, text })) } -fn row_from(r: &rusqlite::Row) -> rusqlite::Result { +pub(crate) fn row_from(r: &rusqlite::Row) -> rusqlite::Result { Ok(RequestRow { id: r.get("id")?, at_ms: r.get("at_ms")?, diff --git a/crates/tw-store/src/lib.rs b/crates/tw-store/src/lib.rs index 8c038230..92daac07 100644 --- a/crates/tw-store/src/lib.rs +++ b/crates/tw-store/src/lib.rs @@ -11,6 +11,7 @@ pub mod blobs; pub mod db; pub mod recorder; +pub mod search; pub mod task; pub use blobs::{Blobs, Which}; diff --git a/crates/tw-store/src/search/mod.rs b/crates/tw-store/src/search/mod.rs new file mode 100644 index 00000000..649faa70 --- /dev/null +++ b/crates/tw-store/src/search/mod.rs @@ -0,0 +1,1408 @@ +//! 在整份请求记录里找(`POST /history/search`)。 +//! +//! 流量页以前把最近两千条读进来再筛,可记录留着三个月 —— 再往前的,筛选框永远看不见。 +//! 这里把那个筛选搬进库里,一页一页往回翻。 +//! +//! **两种找法。**只按记录(路径、密钥、上游、模型、失败原因……)找,整个交给 SQL,三个月 +//! 十万条也是一次走索引的扫描。按正文找要读盘:一份请求体动辄几百 KB,只能一份一份地读, +//! 所以每次只读一定的量([`Budget`]),读完就把找到的先交回去,界面要再往前就再问一次。 +//! 正文只留几天(`retention.body_days`),比它早的照样按记录对。 + +mod needle; +mod sql; +pub mod text; + +pub(crate) use sql::register; + +use std::time::{Duration, Instant}; + +use tw_api::{ContentHit, ContentSide, HistoryCursor, SearchStop}; + +use needle::{Excerpt, Needle, fold}; + +use crate::blobs::{Blobs, Which}; +use crate::db::{DbError, RequestRow}; + +/// 一页缺省几条。 +pub const DEFAULT_LIMIT: usize = 100; +/// 一页最多几条。**结果要整页交给界面**,五百行已经是一屏看不完的量 +pub const MAX_LIMIT: usize = 500; + +/// 按正文找时,一次从库里取多少行来看。每取一批锁一次库,看正文的时候不锁 —— +/// 正在落库的请求不必等这边读盘 +const BATCH: usize = 64; + +/// 一次搜索的条件,已经按界面的规则整理过:搜索词去掉首尾空白、转了小写,空串的 +/// 条件当没给。 +#[derive(Debug, Clone)] +pub struct Query { + pub(crate) text: Option, + pub(crate) failed: bool, + pub(crate) unpriced: bool, + pub(crate) client: Option, + pub(crate) provider: Option, + pub(crate) model: Option, + pub(crate) error_codes: Vec, + pub(crate) local_matches: bool, + pub(crate) content: bool, + pub(crate) from_ms: i64, + pub(crate) to_ms: i64, + pub(crate) before: Option, + pub(crate) limit: usize, +} + +impl Query { + pub fn new(q: &tw_api::HistorySearchQuery) -> Query { + // 界面上「空串 = 不限」 + let exact = |s: &Option| s.clone().filter(|s| !s.is_empty()); + Query { + text: fold(&q.q), + failed: q.failed, + unpriced: q.unpriced, + client: exact(&q.client), + provider: exact(&q.provider), + model: exact(&q.model), + error_codes: q.error_codes.clone(), + local_matches: q.local_matches, + content: q.content, + from_ms: q.from_ms.unwrap_or(i64::MIN), + to_ms: q.to_ms.unwrap_or(i64::MAX), + before: q.before, + limit: q.limit.unwrap_or(DEFAULT_LIMIT).clamp(1, MAX_LIMIT), + } + } + + /// 这次要读正文吗:要了,而且有搜索词 + fn reads_bodies(&self) -> bool { + self.content && self.text.is_some() + } +} + +/// 向库要一批行:从哪儿往前、最早到哪一刻、最多几条。 +#[derive(Debug, Clone, Copy)] +pub struct Ask<'a> { + pub query: &'a Query, + /// 只要这一条之前的 + pub before: Option, + /// 只要这一刻及以后的(按正文找时,正文最早留到的那一刻) + pub floor: Option, + /// `true`:搜索词不进 `WHERE`,「按记录对上了没有」跟着行一起交回来;`false`:只要 + /// 按记录就对上了的 + pub flag_text: bool, + pub limit: usize, +} + +/// 按正文找时,一次最多做多少事。两样先到哪样算哪样。 +#[derive(Debug, Clone, Copy)] +pub struct Budget { + /// 最多读几条请求的正文 + pub bodies: usize, + /// 最多花多久 + pub time: Duration, +} + +impl Budget { + /// 界面上一次搜索的量。 + /// + /// **条数是常态下的那道线**:一条请求的正文平均几百 KB,读盘、粗筛、解开最后一轮和 + /// 回答,实测(发布构建、Claude Code 那样的长对话)一条半毫秒到一毫秒多,五百条大约 + /// 半秒 —— 结果先回来,界面说「已找到某一刻,再往前找」。**时间是兜底**:正文的开销 + /// 差得很远(一段长对话的请求体几 MB,光解析就几十毫秒,盘慢的时候更久),一点五秒 + /// 是「等一下」还不算「卡住了」的那条线。 + pub const DEFAULT: Budget = Budget { + bodies: 500, + time: Duration::from_millis(1500), + }; +} + +/// 一次搜索的结果,还没换成界面的样子(行要在 tw-control 里配上安全记录)。 +#[derive(Debug, Clone)] +pub struct Outcome { + pub rows: Vec, + pub hits: Vec, + pub next: Option, + pub bodies_since_ms: Option, + pub stopped: SearchStop, +} + +/// 找一页。`fetch` 向库要一批行([`crate::Db::search_rows`]):放在外面是因为库在调用方 +/// 的锁里,每批只锁一下;读正文不需要锁。 +pub fn run(q: &Query, blobs: &Blobs, budget: Budget, mut fetch: F) -> Result +where + F: FnMut(&Ask) -> Result, DbError>, +{ + let started = Instant::now(); + let mut out = Outcome { + rows: Vec::new(), + hits: Vec::new(), + next: None, + bodies_since_ms: None, + stopped: SearchStop::End, + }; + let mut cursor = q.before; + + // 正文还在盘上的那一段:一条一条看 + if let (true, Some(text), Some(floor)) = (q.reads_bodies(), &q.text, blobs.oldest_ms()) { + out.bodies_since_ms = Some(floor); + let needle = Needle::new(text.clone()); + let mut read = 0; + loop { + let batch = fetch(&Ask { + query: q, + before: cursor, + floor: Some(floor), + flag_text: true, + limit: BATCH, + })?; + let n = batch.len(); + for (row, by_record) in batch { + cursor = Some(HistoryCursor { + at_ms: row.at_ms, + id: row.id, + }); + if by_record { + out.rows.push(row); + } else { + match look(&row, blobs, &needle) { + Look::NoBodies => {} + Look::Read(None) => read += 1, + Look::Read(Some((side, e))) => { + read += 1; + out.hits.push(ContentHit { + id: row.id, + side, + before: e.before, + matched: e.matched, + after: e.after, + }); + out.rows.push(row); + } + } + } + if out.rows.len() >= q.limit { + out.next = cursor; + out.stopped = SearchStop::Full; + return Ok(out); + } + if read >= budget.bodies || started.elapsed() >= budget.time { + out.next = cursor; + out.stopped = SearchStop::Budget; + return Ok(out); + } + } + if n < BATCH { + break; + } + } + } + + // 剩下的(或者全部,没按正文找时)只按记录对:一句 SQL。多要一条,看后面还有没有 + let want = q.limit - out.rows.len(); + let mut rest = fetch(&Ask { + query: q, + before: cursor, + floor: None, + flag_text: false, + limit: want + 1, + })?; + if rest.len() > want { + rest.truncate(want); + out.next = rest.last().map(|(r, _)| HistoryCursor { + at_ms: r.at_ms, + id: r.id, + }); + out.stopped = SearchStop::Full; + } + out.rows.extend(rest.into_iter().map(|(r, _)| r)); + Ok(out) +} + +/// 看一条请求的正文的结果。 +enum Look { + /// 没有可读的正文:清掉了、没存下来,或者不是生成回答的调用。不算进读了几份 + NoBodies, + /// 读了。对上的话,在哪一边、前后是什么 + Read(Option<(ContentSide, Excerpt)>), +} + +/// 先看请求里新的那一轮,再看回答:一轮话里先有问、后有答。 +/// +/// 原始字节上先粗筛([`Needle::might_be_in`]):绝大多数请求体里根本没有这个词,不必解析。 +/// 流式的回答不能这样筛 —— 一个词可能被切在两帧里。 +fn look(row: &RequestRow, blobs: &Blobs, needle: &Needle) -> Look { + let Some(client) = text::client_dialect(&row.path) else { + return Look::NoBodies; + }; + let request = blobs.get(row.at_ms, row.id, Which::Request); + if let Some(body) = &request + && needle.might_be_in(body) + && let Some(turn) = text::user_turn(body, &row.path) + && let Some(e) = needle.excerpt(&turn) + { + return Look::Read(Some((ContentSide::Request, e))); + } + let Some(body) = blobs.get(row.at_ms, row.id, Which::Response) else { + return match request { + Some(_) => Look::Read(None), + None => Look::NoBodies, + }; + }; + // 回答它的那一家说的格式:转换过的记在行上,直通的就是客户端那一种 + let upstream = row + .translated + .as_deref() + .and_then(|j| serde_json::from_str::(j).ok()) + .map_or(client, |t| text::dialect_of(t.to)); + let whole = body.iter().find(|b| !b.is_ascii_whitespace()) == Some(&b'{'); + let hit = (!whole || needle.might_be_in(&body)) + .then(|| text::answer(&body, upstream)) + .flatten() + .and_then(|a| needle.excerpt(&a)); + Look::Read(hit.map(|e| (ContentSide::Answer, e))) +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use serde_json::json; + use tw_api::Msg; + + use super::*; + use crate::db::Db; + use crate::db::tests::row; + + const DAY: i64 = 86_400_000; + /// 测试里「今天」:正文目录按这一天建 + const NOW: i64 = 1_790_000_000_000; + + fn ask(q: tw_api::HistorySearchQuery) -> Query { + Query::new(&q) + } + + fn search(db: &Db, blobs: &Blobs, q: &Query, budget: Budget) -> Outcome { + run(q, blobs, budget, |a| db.search_rows(a)).unwrap() + } + + /// 只按记录找,一页拿完 + fn ids(db: &Db, q: tw_api::HistorySearchQuery) -> Vec { + let d = tempfile::tempdir().unwrap(); + let blobs = Blobs::new(d.path().join("blobs")); + let q = Query::new(&tw_api::HistorySearchQuery { + limit: Some(MAX_LIMIT), + ..q + }); + search(db, &blobs, &q, Budget::DEFAULT) + .rows + .iter() + .map(|r| r.id) + .collect() + } + + fn err(code: &str, text: &str) -> Msg { + Msg { + code: code.into(), + args: BTreeMap::new(), + text: text.into(), + } + } + + // ───────────────────────────────────────────────── 和界面的筛选一模一样 + + /// 界面那一边:桌面端 `useRequests.ts` 把一条 `HistoryRow` 变成表格的一行, + /// `requestTable.ts` 的 `filterRows` 筛它。**逐句照抄**,测试拿它当标准答案。 + mod ui { + use crate::db::RequestRow; + + /// 本地应答那一格写的话(中文界面) + pub const ANSWERED_LOCALLY: &str = "本地应答"; + + pub struct Filter<'a> { + pub q: &'a str, + pub failed_only: bool, + pub unpriced_only: bool, + pub client: &'a str, + pub provider: &'a str, + pub model: &'a str, + } + + /// `coreText(r.error)`:英文界面上就是那句英文 + fn core_text(r: &RequestRow) -> String { + r.error.as_ref().map(|e| e.text.clone()).unwrap_or_default() + } + + pub fn keeps(r: &RequestRow, f: &Filter) -> bool { + // mergeHistory:state、provider(本地应答没有上游)、model(空串当没有) + let state = if r.error.is_some() { + "failed" + } else if r.cancelled { + "cancelled" + } else { + "done" + }; + let provider = if r.local { "" } else { r.provider.as_str() }; + let model = (!r.model.is_empty()).then_some(r.model.as_str()); + // filterRows + let q = super::js_trim(f.q).to_lowercase(); + if f.failed_only && state != "failed" { + return false; + } + if f.unpriced_only + && (r.cost_micros.is_some() + || state != "done" + || (r.input_tokens.is_none() && r.output_tokens.is_none())) + { + return false; + } + if !f.client.is_empty() && r.client != f.client { + return false; + } + if !f.provider.is_empty() && provider != f.provider { + return false; + } + if !f.model.is_empty() && model != Some(f.model) { + return false; + } + if q.is_empty() { + return true; + } + let upstream = if r.local { ANSWERED_LOCALLY } else { provider }; + r.path.to_lowercase().contains(&q) + || r.client.to_lowercase().contains(&q) + || r.client_hint + .as_deref() + .unwrap_or("") + .to_lowercase() + .contains(&q) + || r.peer.as_deref().unwrap_or("").contains(&q) + || upstream.to_lowercase().contains(&q) + || model.unwrap_or("").to_lowercase().contains(&q) + || core_text(r).to_lowercase().contains(&q) + } + } + + use super::needle::js_trim; + + /// 各种样子的行:失败的、取消的、没报用量的、无法计价的、本地应答的(含网关替上游估 + /// token 数的那种:它有上游名,界面上却没有)、局域网来的、名字里有外文大写字母的…… + fn variety() -> (Db, Vec) { + let db = Db::in_memory().unwrap(); + let mut rows = Vec::new(); + let clients = ["claude-code", "Max's Mac", "Übersetzer", "50%off", "a_b"]; + let providers = ["官方", "relay-cn", "Яндекс"]; + let models = ["claude-sonnet-4-5", "gpt-5.5", "gpt-5.5-codex", ""]; + let paths = [ + "/v1/messages", + "/v1/chat/completions", + "/v1/messages/count_tokens", + ]; + for i in 0..120i64 { + let mut r = row(i + 1, NOW - i * 1000); + r.client = clients[i as usize % clients.len()].into(); + r.provider = providers[i as usize % providers.len()].into(); + r.model = models[i as usize % models.len()].into(); + r.path = paths[i as usize % paths.len()].into(); + r.client_hint = match i % 4 { + 0 => Some("claude-code".into()), + 1 => Some("codex".into()), + _ => None, + }; + r.peer = match i % 5 { + 0 => Some("192.168.1.23".into()), + 1 => Some("fe80::1".into()), + _ => None, + }; + match i % 7 { + 0 => { + r.error = Some(err( + "gw.upstream.timeout", + "Upstream `relay-cn` did not answer within 600s", + )) + } + 1 => r.error = Some(err("gw.denied.rule", "Rule `夜间` denied the request")), + 2 => r.cancelled = true, + 3 => r.cost_micros = None, + 4 => { + r.cost_micros = None; + r.input_tokens = None; + r.output_tokens = None; + } + 5 => { + r.cost_micros = None; + r.input_tokens = None; + } + _ => {} + } + if i % 11 == 0 { + r.local = true; + r.error = None; + r.cost_micros = Some(0); + } + if i % 22 == 0 { + r.provider = String::new(); + r.model = String::new(); + r.path = "health_check".into(); + } + db.insert(&r).unwrap(); + rows.push(r); + } + (db, rows) + } + + /// **和界面的筛选一模一样**:每一种筛选、每一个字段上的搜索词,库里找出来的和 + /// `filterRows` 留下的是同一批,顺序也一样(新的在前)。 + #[test] + fn searching_the_records_keeps_exactly_what_the_traffic_filter_keeps() { + let (db, rows) = variety(); + let queries = [ + "", + " ", + "claude", + "CLAUDE", + " sonnet ", + "gpt-5.5", + "über", + "ÜBERSETZER", + "яндекс", + "官方", + "本地", + "192.168", + "FE80", + "codex", + "max's", + "count_tokens", + "health", + "600s", + "夜间", + "%", + "_", + "50%", + "a_b", + "nothing-like-this", + ]; + let filters = [ + (false, false, "", "", ""), + (true, false, "", "", ""), + (false, true, "", "", ""), + (false, false, "Übersetzer", "", ""), + (false, false, "", "relay-cn", ""), + (false, false, "", "官方", ""), + (false, false, "", "", "gpt-5.5"), + (false, false, "", "", ""), + (true, false, "claude-code", "Яндекс", ""), + (false, true, "", "", "claude-sonnet-4-5"), + ]; + let mut checked = 0; + for q in queries { + for (failed, unpriced, client, provider, model) in filters { + let f = ui::Filter { + q, + failed_only: failed, + unpriced_only: unpriced, + client, + provider, + model, + }; + let want: Vec = rows + .iter() + .filter(|r| ui::keeps(r, &f)) + .map(|r| r.id) + .collect(); + let opt = |s: &str| (!s.is_empty()).then(|| s.to_string()); + let got = ids( + &db, + tw_api::HistorySearchQuery { + q: q.into(), + failed, + unpriced, + client: opt(client), + provider: opt(provider), + model: opt(model), + local_matches: ui::ANSWERED_LOCALLY.contains(&q.trim().to_lowercase()), + ..Default::default() + }, + ); + assert_eq!( + got, want, + "q={q:?} failed={failed} unpriced={unpriced} client={client:?} provider={provider:?} model={model:?}" + ); + checked += usize::from(!want.is_empty()); + } + } + assert!(checked > 100, "大多数组合都该筛出点什么:{checked}"); + } + + /// 失败原因按界面上那句话对:中文界面把译文里含着搜索词的码交过来。英文原句里没有 + /// 这个词,照样对上 + #[test] + fn an_error_is_found_by_the_words_of_its_translation() { + let (db, rows) = variety(); + let q = |codes: Vec<&str>| tw_api::HistorySearchQuery { + q: "超时".into(), + error_codes: codes.into_iter().map(String::from).collect(), + ..Default::default() + }; + assert!(ids(&db, q(vec![])).is_empty(), "英文原句里没有「超时」"); + let got = ids(&db, q(vec!["gw.upstream.timeout", "gw.never.seen"])); + let want: Vec = rows + .iter() + .filter(|r| { + r.error + .as_ref() + .is_some_and(|e| e.code == "gw.upstream.timeout") + }) + .map(|r| r.id) + .collect(); + assert!(!want.is_empty()); + assert_eq!(got, want); + } + + /// 本地应答的那一格写的是界面自己的一句话:那句话对得上时,本地应答的都算;它们的 + /// 上游名(网关替上游估 token 数的那种有)不参与 + #[test] + fn local_answers_are_found_by_the_sentence_the_ui_shows_for_them() { + let (db, rows) = variety(); + let local: Vec = rows.iter().filter(|r| r.local).map(|r| r.id).collect(); + assert!(local.len() > 3); + let got = ids( + &db, + tw_api::HistorySearchQuery { + q: "本地".into(), + local_matches: true, + ..Default::default() + }, + ); + assert_eq!(got, local); + let got = ids( + &db, + tw_api::HistorySearchQuery { + q: "官方".into(), + ..Default::default() + }, + ); + assert!(got.iter().all(|id| !local.contains(id)), "{got:?}"); + } + + /// `%` 和 `_` 是字面的字,不是通配符 + #[test] + fn percent_and_underscore_in_the_query_are_taken_literally() { + let db = Db::in_memory().unwrap(); + for (id, client) in [ + (1, "50%off"), + (2, "500ff"), + (3, "a_b"), + (4, "axb"), + (5, "a%b"), + ] { + let mut r = row(id, NOW - id); + r.client = client.into(); + r.model = "m".into(); + r.path = "/p".into(); + r.provider = "x".into(); + db.insert(&r).unwrap(); + } + let q = |s: &str| { + ids( + &db, + tw_api::HistorySearchQuery { + q: s.into(), + ..Default::default() + }, + ) + }; + assert_eq!(q("50%"), [1]); + assert_eq!(q("a_b"), [3]); + assert_eq!(q("%"), [1, 5]); + assert_eq!(q("_"), [3]); + assert_eq!(q("\\"), Vec::::new()); + } + + // ───────────────────────────────────────────────── 翻页 + + /// 同一毫秒里开始的几条落在页缝上:一条不漏、一条不重,顺序和 `GET /history` 一样 + #[test] + fn paging_back_through_rows_that_share_a_timestamp_misses_and_repeats_nothing() { + let db = Db::in_memory().unwrap(); + let mut want = Vec::new(); + // 三个时刻,每个时刻七条 + for (k, at) in [NOW, NOW - 10, NOW - 20].into_iter().enumerate() { + for j in 0..7 { + let id = (k * 7 + j) as i64 + 1; + db.insert(&row(id, at)).unwrap(); + want.push((at, id)); + } + } + want.sort_by(|a, b| b.cmp(a)); + let want: Vec = want.into_iter().map(|(_, id)| id).collect(); + let d = tempfile::tempdir().unwrap(); + let blobs = Blobs::new(d.path().join("blobs")); + for size in [1, 2, 3, 5, 7, 20] { + let mut got = Vec::new(); + let mut before = None; + let mut pages = 0; + loop { + let q = ask(tw_api::HistorySearchQuery { + before, + limit: Some(size), + ..Default::default() + }); + let page = search(&db, &blobs, &q, Budget::DEFAULT); + pages += 1; + assert!(page.rows.len() <= size); + got.extend(page.rows.iter().map(|r| r.id)); + match page.next { + Some(c) => { + assert_eq!(page.stopped, SearchStop::Full); + let last = page.rows.last().unwrap(); + assert_eq!((c.at_ms, c.id), (last.at_ms, last.id)); + before = Some(c); + } + None => { + assert_eq!(page.stopped, SearchStop::End); + break; + } + } + assert!(pages < 100); + } + assert_eq!(got, want, "一页 {size} 条"); + assert_eq!(pages, want.len().div_ceil(size), "一页 {size} 条"); + } + // 和 `GET /history` 同一个顺序 + let recent: Vec = db.recent(None, 100).unwrap().iter().map(|r| r.id).collect(); + assert_eq!(recent, want); + } + + #[test] + fn a_time_window_bounds_the_search_on_both_ends() { + let db = Db::in_memory().unwrap(); + for i in 0..10 { + db.insert(&row(i + 1, NOW + i * 100)).unwrap(); + } + let got = ids( + &db, + tw_api::HistorySearchQuery { + from_ms: Some(NOW + 200), + to_ms: Some(NOW + 500), + ..Default::default() + }, + ); + assert_eq!(got, [6, 5, 4, 3]); + } + + #[test] + fn a_page_holds_a_hundred_by_default_and_at_most_five_hundred() { + let db = Db::in_memory().unwrap(); + for i in 0..600 { + db.insert(&row(i + 1, NOW - i)).unwrap(); + } + let d = tempfile::tempdir().unwrap(); + let blobs = Blobs::new(d.path().join("blobs")); + let page = |limit| { + search( + &db, + &blobs, + &ask(tw_api::HistorySearchQuery { + limit, + ..Default::default() + }), + Budget::DEFAULT, + ) + }; + let p = page(None); + assert_eq!(p.rows.len(), DEFAULT_LIMIT); + assert_eq!(p.stopped, SearchStop::Full); + assert_eq!(p.next.unwrap().id, 100); + assert_eq!(page(Some(10_000)).rows.len(), MAX_LIMIT); + assert_eq!(page(Some(0)).rows.len(), 1); + // 正好取完的那一页说找完了,不留一个空的下一页 + let p = search( + &db, + &blobs, + &ask(tw_api::HistorySearchQuery { + before: Some(HistoryCursor { + at_ms: NOW - 499, + id: 500, + }), + limit: Some(100), + ..Default::default() + }), + Budget::DEFAULT, + ); + assert_eq!( + (p.rows.len(), p.stopped, p.next), + (100, SearchStop::End, None) + ); + } + + /// 三个月十万条记录,只按记录找、一条都对不上的时候,也是一次沿着索引走到头。 + /// + /// **门槛放得很宽**:测试是调试构建、CI 的机器也慢,挡的是「一条一条拿回 Rust 里比」 + /// 那种量级的退化。实测的数字见 PR(发布构建下十万条一条都对不上约几十毫秒)。 + #[test] + fn searching_a_hundred_thousand_rows_stays_fast() { + let d = tempfile::tempdir().unwrap(); + let db = Db::open(&d.path().join("data.db")).unwrap(); + hundred_thousand(&db); + let blobs = Blobs::new(d.path().join("blobs")); + let q = ask(tw_api::HistorySearchQuery { + q: "没有这个词".into(), + ..Default::default() + }); + let t = Instant::now(); + let p = search(&db, &blobs, &q, Budget::DEFAULT); + let none = t.elapsed(); + assert!(p.rows.is_empty() && p.stopped == SearchStop::End); + let q = ask(tw_api::HistorySearchQuery { + q: "Overloaded".into(), + ..Default::default() + }); + let t = Instant::now(); + let p = search(&db, &blobs, &q, Budget::DEFAULT); + let page = t.elapsed(); + assert_eq!(p.rows.len(), DEFAULT_LIMIT); + eprintln!("100k rows: no match {none:?}, first page {page:?}"); + assert!(none < Duration::from_secs(10), "{none:?}"); + assert!(page < Duration::from_secs(2), "{page:?}"); + } + + /// 十万条,一分钟一条往回排:三种密钥(一种名字带中文)、每十三条一条失败 + fn hundred_thousand(db: &Db) { + db.conn() + .execute( + "WITH RECURSIVE n(i) AS (SELECT 0 UNION ALL SELECT i + 1 FROM n WHERE i < 99999) + INSERT INTO requests (id, at_ms, client, client_hint, provider, model, path, status, + cost_estimated, billing, local, cancelled, input_tokens, output_tokens, cost_micros, + error, error_code) + SELECT i + 1, ?1 - i * 60000, + CASE i % 3 WHEN 0 THEN 'claude-code' WHEN 1 THEN 'codex' ELSE 'Cursor 编辑器' END, + CASE i % 2 WHEN 0 THEN 'claude-code' END, + '官方', 'claude-sonnet-4-5', '/v1/messages', 200, 0, 'per-token', 0, 0, 1000, 200, 300, + CASE WHEN i % 13 = 0 THEN 'Upstream `官方` answered HTTP 529: overloaded' END, + CASE WHEN i % 13 = 0 THEN 'gw.upstream.http' END + FROM n", + [NOW], + ) + .unwrap(); + } + + /// 查询计划:每一种问法都沿着时刻的索引走,不整表扫、不整表排序 + #[test] + fn the_search_walks_the_time_index() { + let db = Db::in_memory().unwrap(); + let full = ask(tw_api::HistorySearchQuery { + q: "x".into(), + failed: true, + unpriced: true, + client: Some("c".into()), + provider: Some("p".into()), + model: Some("m".into()), + error_codes: vec!["a.b".into()], + from_ms: Some(1), + to_ms: Some(9), + ..Default::default() + }); + let bare = ask(Default::default()); + let before = Some(HistoryCursor { at_ms: 5, id: 3 }); + for (q, before, floor, flag_text) in [ + (&bare, None, None, false), + (&full, before, None, false), + (&full, before, Some(2), true), + (&bare, before, Some(2), true), + ] { + let (sql, args) = super::sql::statement(&Ask { + query: q, + before, + floor, + flag_text, + limit: 101, + }); + let params: Vec<(&str, &dyn rusqlite::ToSql)> = + args.iter().map(|(k, v)| (*k, v.as_ref())).collect(); + let plan: Vec = db + .conn() + .prepare(&format!("EXPLAIN QUERY PLAN {sql}")) + .unwrap() + .query_map(params.as_slice(), |r| r.get::<_, String>(3)) + .unwrap() + .collect::>() + .unwrap(); + let plan = plan.join(" / "); + assert!(plan.contains("USING INDEX requests_at"), "{plan}\n{sql}"); + assert!(!plan.contains("SCAN requests"), "{plan}\n{sql}"); + // 同一毫秒里的几条按请求号排,不是把结果整个排一遍 + assert!( + !plan.contains("USE TEMP B-TREE FOR ORDER BY"), + "{plan}\n{sql}" + ); + // 真跑一遍:每个按名字绑定的参数都用得上 + db.search_rows(&Ask { + query: q, + before, + floor, + flag_text, + limit: 101, + }) + .unwrap(); + } + } + + // ───────────────────────────────────────────────── 按正文找 + + /// 一份测试用的盘:一个请求库,一个正文目录 + struct Disk { + _dir: tempfile::TempDir, + db: Db, + blobs: Blobs, + } + + fn disk() -> Disk { + let dir = tempfile::tempdir().unwrap(); + let blobs = Blobs::new(dir.path().join("blobs")); + Disk { + db: Db::in_memory().unwrap(), + blobs, + _dir: dir, + } + } + + impl Disk { + /// 一条带着正文的请求。`response` 空的是没存下回答 + fn put(&self, r: &RequestRow, request: &[u8], response: &[u8]) { + self.db.insert(r).unwrap(); + if !request.is_empty() { + assert!(self.blobs.put(r.at_ms, r.id, Which::Request, request)); + } + if !response.is_empty() { + assert!(self.blobs.put(r.at_ms, r.id, Which::Response, response)); + } + } + + fn find(&self, q: &str) -> Outcome { + self.find_with(q, Budget::DEFAULT, None) + } + + fn find_with(&self, q: &str, budget: Budget, before: Option) -> Outcome { + let q = ask(tw_api::HistorySearchQuery { + q: q.into(), + content: true, + before, + ..Default::default() + }); + search(&self.db, &self.blobs, &q, budget) + } + } + + fn at(id: i64, at_ms: i64, path: &str) -> RequestRow { + let mut r = row(id, at_ms); + r.path = path.into(); + r + } + + fn sse(frames: &[(&str, serde_json::Value)]) -> Vec { + let mut s = String::new(); + for (event, data) in frames { + if !event.is_empty() { + s.push_str(&format!("event: {event}\n")); + } + s.push_str(&format!("data: {data}\n\n")); + } + s.into_bytes() + } + + fn hit_of(o: &Outcome, id: i64) -> &ContentHit { + o.hits + .iter() + .find(|h| h.id == id) + .unwrap_or_else(|| panic!("{id} 没有按正文对上:{:?}", o.hits)) + } + + /// 四种格式,流式和整包,问在请求里、答在回答里,都找得到;`\u` 转义的中文按中文找 + #[test] + fn content_is_found_in_every_format_streamed_or_whole() { + let d = disk(); + let user = + |text: &str| json!({"model": "m", "messages": [{"role": "user", "content": text}]}); + // Anthropic,流式回答 + d.put( + &at(1, NOW - 1, "/v1/messages"), + user("你好").to_string().as_bytes(), + &sse(&[ + ("content_block_start", json!({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}})), + ("content_block_delta", json!({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "答案藏在 ZEBRA"}})), + ("content_block_delta", json!({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "-STRIPE 里"}})), + ]), + ); + // Chat,整包回答 + d.put( + &at(2, NOW - 2, "/v1/chat/completions"), + user("问").to_string().as_bytes(), + json!({"choices": [{"message": {"role": "assistant", "content": "整包里也有 zebra-stripe"}}]}) + .to_string() + .as_bytes(), + ); + // Responses,问题里有(Python 把中文全写成 \u 转义) + d.put( + &at(3, NOW - 3, "/v1/responses"), + br#"{"model":"gpt-5.5","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"\u6591\u9a6c\u7eb9 zebra-stripe \u5728\u54ea"}]}]}"#, + b"", + ); + // Gemini,流式回答里是 \u 转义的中文 + d.put( + &at(4, NOW - 4, "/v1beta/models/gemini-2.5-pro:streamGenerateContent"), + json!({"contents": [{"role": "user", "parts": [{"text": "问"}]}]}).to_string().as_bytes(), + b"data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"\\u6591\\u9a6c\"}]}}]}\n\ndata: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"\\u7eb9\"}]}}]}\n\n", + ); + // 一条什么都对不上的 + d.put( + &at(5, NOW - 5, "/v1/messages"), + user("无关").to_string().as_bytes(), + &sse(&[("content_block_delta", json!({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "无关"}}))]), + ); + + let o = d.find("Zebra-Stripe"); + assert_eq!(o.rows.iter().map(|r| r.id).collect::>(), [1, 2, 3]); + // 流里切成两帧的那个词照样对上 + let h = hit_of(&o, 1); + assert_eq!(h.side, ContentSide::Answer); + assert_eq!( + (h.before.as_str(), h.matched.as_str(), h.after.as_str()), + ("答案藏在 ", "ZEBRA-STRIPE", " 里") + ); + assert_eq!(hit_of(&o, 2).side, ContentSide::Answer); + let h = hit_of(&o, 3); + assert_eq!(h.side, ContentSide::Request); + assert_eq!(h.before, "斑马纹 "); + + let o = d.find("斑马纹"); + assert_eq!(o.rows.iter().map(|r| r.id).collect::>(), [3, 4]); + assert_eq!(hit_of(&o, 4).side, ContentSide::Answer); + assert_eq!(hit_of(&o, 4).matched, "斑马纹"); + assert_eq!(o.stopped, SearchStop::End); + assert_eq!(o.bodies_since_ms, Some(NOW - NOW.rem_euclid(DAY))); + } + + /// 一段长对话:早先一轮里说过的话,不让之后每个请求都对上;说在最后一轮里的才算 + #[test] + fn only_the_last_user_turn_of_a_long_conversation_counts() { + let d = disk(); + let mut messages = vec![json!({"role": "user", "content": "第一轮就提到了 KIWI-42"})]; + for id in 1..=5i64 { + let mut turn = messages.clone(); + turn.push(json!({"role": "user", "content": format!("第 {id} 轮的新问题")})); + d.put( + &at(id, NOW + id, "/v1/messages"), + json!({"messages": turn}).to_string().as_bytes(), + b"", + ); + messages.push(json!({"role": "user", "content": format!("第 {id} 轮的新问题")})); + messages.push(json!({"role": "assistant", "content": format!("第 {id} 轮的回答")})); + } + // 第一个请求:那句话就在它的最后一轮里(两条连着的用户消息都算这一轮) + let o = d.find("kiwi-42"); + assert_eq!(o.rows.iter().map(|r| r.id).collect::>(), [1]); + let o = d.find("第 4 轮的新问题"); + assert_eq!(o.rows.iter().map(|r| r.id).collect::>(), [4]); + } + + /// 转换过格式的请求:回答是上游的原话,按上游的格式读 + #[test] + fn a_translated_answer_is_read_in_the_upstream_format() { + let d = disk(); + let mut r = at(1, NOW, "/v1/messages"); + r.translated = Some( + serde_json::to_string(&tw_api::TranslatedView { + from: tw_api::Dialect::Anthropic, + to: tw_api::Dialect::OpenaiChat, + dropped: vec![], + }) + .unwrap(), + ); + let mut body = sse(&[ + ( + "", + json!({"choices": [{"index": 0, "delta": {"content": "来自 Chat 的"}}]}), + ), + ( + "", + json!({"choices": [{"index": 0, "delta": {"content": "回答"}}]}), + ), + ]); + body.extend_from_slice(b"data: [DONE]\n\n"); + d.put( + &r, + json!({"messages": [{"role": "user", "content": "问"}]}) + .to_string() + .as_bytes(), + &body, + ); + let o = d.find("chat 的回答"); + assert_eq!(hit_of(&o, 1).side, ContentSide::Answer); + } + + /// 问和答里都有:报问里那一处 + #[test] + fn a_hit_in_the_request_comes_before_one_in_the_answer() { + let d = disk(); + d.put( + &at(1, NOW, "/v1/chat/completions"), + json!({"messages": [{"role": "user", "content": "什么是 rust"}]}) + .to_string() + .as_bytes(), + json!({"choices": [{"message": {"content": "Rust 是一门语言"}}]}) + .to_string() + .as_bytes(), + ); + let o = d.find("rust"); + let h = hit_of(&o, 1); + assert_eq!( + (h.side, h.before.as_str()), + (ContentSide::Request, "什么是 ") + ); + } + + /// 按记录就对上的不去读正文,也不交摘录;按正文对上的才有 + #[test] + fn a_row_found_by_its_record_is_not_read_for_content() { + let d = disk(); + let mut r = at(1, NOW, "/v1/messages"); + r.client = "needle-client".into(); + d.put( + &r, + json!({"messages": [{"role": "user", "content": "needle 也在正文里"}]}) + .to_string() + .as_bytes(), + b"", + ); + let o = d.find("needle"); + assert_eq!(o.rows.len(), 1); + assert!(o.hits.is_empty(), "{:?}", o.hits); + } + + /// 筛选条件对按正文找的那一段一样管用 + #[test] + fn filters_apply_to_content_hits_too() { + let d = disk(); + let mut failed = at(1, NOW, "/v1/messages"); + failed.error = Some(err("gw.x", "boom")); + let ok = at(2, NOW - 1, "/v1/messages"); + for r in [&failed, &ok] { + d.put( + r, + json!({"messages": [{"role": "user", "content": "共同的 PHRASE"}]}) + .to_string() + .as_bytes(), + b"", + ); + } + let q = ask(tw_api::HistorySearchQuery { + q: "phrase".into(), + content: true, + failed: true, + ..Default::default() + }); + let o = search(&d.db, &d.blobs, &q, Budget::DEFAULT); + assert_eq!(o.rows.iter().map(|r| r.id).collect::>(), [1]); + } + + /// 一次只读这么多份正文:读够了先交回来,`next` 说从哪儿接着找;接着找下去,一条 + /// 不漏地找到头 + #[test] + fn content_search_stops_at_its_budget_and_picks_up_where_it_left_off() { + let d = disk(); + for id in 1..=10i64 { + let text = if id == 2 || id == 9 { + "目标 OKAPI 在这" + } else { + "没有" + }; + d.put( + &at(id, NOW + id, "/v1/messages"), + json!({"messages": [{"role": "user", "content": text}]}) + .to_string() + .as_bytes(), + b"", + ); + } + let budget = Budget { + bodies: 3, + time: Duration::from_secs(60), + }; + let mut found = Vec::new(); + let mut before = None; + let mut calls = Vec::new(); + loop { + let o = d.find_with("okapi", budget, before); + found.extend(o.rows.iter().map(|r| r.id)); + calls.push((o.stopped, o.next.map(|c| c.id))); + match o.next { + Some(c) => before = Some(c), + None => break, + } + } + assert_eq!(found, [9, 2]); + assert_eq!( + calls, + [ + (SearchStop::Budget, Some(8)), + (SearchStop::Budget, Some(5)), + (SearchStop::Budget, Some(2)), + (SearchStop::End, None), + ] + ); + // 时间用完也一样停 + let o = d.find_with( + "okapi", + Budget { + bodies: 100, + time: Duration::ZERO, + }, + None, + ); + assert_eq!( + (o.stopped, o.next.map(|c| c.id)), + (SearchStop::Budget, Some(10)) + ); + } + + /// 凑够一页就停,`next` 指着这一页最后一条 + #[test] + fn a_full_page_of_content_hits_stops_there() { + let d = disk(); + for id in 1..=5i64 { + d.put( + &at(id, NOW + id, "/v1/messages"), + json!({"messages": [{"role": "user", "content": "每条都有 LYNX"}]}) + .to_string() + .as_bytes(), + b"", + ); + } + let q = ask(tw_api::HistorySearchQuery { + q: "lynx".into(), + content: true, + limit: Some(2), + ..Default::default() + }); + let o = search(&d.db, &d.blobs, &q, Budget::DEFAULT); + assert_eq!(o.rows.iter().map(|r| r.id).collect::>(), [5, 4]); + assert_eq!( + (o.stopped, o.next.map(|c| c.id)), + (SearchStop::Full, Some(4)) + ); + } + + /// 正文清掉了的那些(比盘上最老的一天还早)不去盘上问,但按记录照样找得到; + /// 只在正文里有的词找不到它们 + #[test] + fn rows_whose_bodies_were_pruned_are_still_found_by_their_record() { + let d = disk(); + // 今天的两条有正文 + d.put( + &at(10, NOW, "/v1/messages"), + json!({"messages": [{"role": "user", "content": "正文里的 MARMOT"}]}) + .to_string() + .as_bytes(), + b"", + ); + d.put(&at(9, NOW - 1, "/v1/messages"), b"{}", b""); + // 十天前的:正文早清了 + for id in 1..=3i64 { + let mut r = at(id, NOW - 10 * DAY - id, "/v1/messages"); + if id == 2 { + r.client = "marmot-laptop".into(); + } + d.db.insert(&r).unwrap(); + } + let o = d.find("marmot"); + assert_eq!(o.rows.iter().map(|r| r.id).collect::>(), [10, 2]); + assert_eq!(o.hits.len(), 1); + assert_eq!(o.bodies_since_ms, Some(NOW - NOW.rem_euclid(DAY))); + assert_eq!(o.stopped, SearchStop::End); + // 正文那一段之外不计入读了几份:读的量只花在有正文的那几条上 + let o = d.find_with( + "marmot", + Budget { + bodies: 2, + time: Duration::from_secs(60), + }, + None, + ); + assert_eq!(o.rows.iter().map(|r| r.id).collect::>(), [10]); + assert_eq!( + (o.stopped, o.next.map(|c| c.id)), + (SearchStop::Budget, Some(9)) + ); + let o = d.find_with("marmot", Budget::DEFAULT, o.next); + assert_eq!(o.rows.iter().map(|r| r.id).collect::>(), [2]); + } + + /// 一份正文都没有的盘:按正文找就是按记录找,不报正文留到哪一刻 + #[test] + fn without_any_bodies_content_search_is_a_record_search() { + let d = disk(); + let mut r = at(1, NOW, "/v1/messages"); + r.model = "walrus-1".into(); + d.db.insert(&r).unwrap(); + let o = d.find("walrus"); + assert_eq!(o.rows.len(), 1); + assert_eq!(o.bodies_since_ms, None); + // 没有搜索词时不读正文 + let q = ask(tw_api::HistorySearchQuery { + content: true, + ..Default::default() + }); + assert_eq!( + search(&d.db, &d.blobs, &q, Budget::DEFAULT).bodies_since_ms, + None + ); + } + + /// 数 token 的请求和下一个请求带着同一段对话:不读它,免得一句话对上两条 + #[test] + fn token_counts_are_not_read_for_content() { + let d = disk(); + let body = json!({"messages": [{"role": "user", "content": "同一句 BEAVER"}]}).to_string(); + d.put( + &at(1, NOW, "/v1/messages/count_tokens"), + body.as_bytes(), + b"", + ); + d.put(&at(2, NOW - 1, "/v1/messages"), body.as_bytes(), b""); + let o = d.find("beaver"); + assert_eq!(o.rows.iter().map(|r| r.id).collect::>(), [2]); + } + + /// 摘录和详情抽屉一样打码;只在密钥里出现的词不算对上 + #[test] + fn content_hits_never_carry_a_secret() { + let d = disk(); + let key = "sk-ant-api03-SEARCHKEYAAAAAAAAAAAAAAAAAAAAAA"; + d.put( + &at(1, NOW, "/v1/messages"), + json!({"messages": [{"role": "user", "content": format!("我的 key 是 {key}")}]}) + .to_string() + .as_bytes(), + b"", + ); + let o = d.find("我的 key"); + let h = hit_of(&o, 1); + assert!(!h.after.contains("SEARCHKEYAAAA"), "{h:?}"); + assert!(d.find("searchkeyaaaa").rows.is_empty()); + } + + #[test] + fn security_records_come_back_for_exactly_the_requests_asked_for() { + let db = Db::in_memory().unwrap(); + for (id, req) in [(1, 10), (2, 20), (3, 10), (4, 30)] { + db.insert_security_event(&crate::db::SecurityEvent { + at_ms: NOW + id, + request_id: req, + guard: tw_api::Guard::Redact, + rule: "anthropic".into(), + custom: false, + action: tw_api::SecurityOutcome::Replaced, + provider: "官方".into(), + client: "me".into(), + tool: None, + excerpt: "sk-an…".into(), + count: 1, + }) + .unwrap(); + } + let got = db.security_of(&[10, 30, 99]).unwrap(); + assert_eq!(got.len(), 2); + assert_eq!(got[&10].len(), 2); + assert_eq!(got[&30][0].id, 4); + assert!(db.security_of(&[]).unwrap().is_empty()); + } + + // ───────────────────────────────────────────────── 量一量 + + /// 按正文找要花多少:照 Claude Code 的样子造几段长对话(每轮带着整段历史、工具结果 + /// 几 KB 到十几 KB、流式回答里有推理和工具调用),量一条请求的正文平均要多久。 + /// + /// 默认不跑:要写一两百 MB 的正文。发布构建下跑: + /// `cargo test --release -p tw-store content_search_cost -- --ignored --nocapture` + #[test] + #[ignore] + fn content_search_cost() { + let d = disk(); + let system = "You are Claude Code. ".repeat(1000); + let tools: Vec = (0..40) + .map(|i| { + json!({"name": format!("Tool{i}"), "description": "x".repeat(600), + "input_schema": {"type": "object", "properties": {"path": {"type": "string"}}}}) + }) + .collect(); + let mut id = 0; + let mut bytes = 0usize; + for s in 0..3 { + let mut messages = vec![ + json!({"role": "user", "content": format!("会话 {s} 的第一句:请重构 FIRST-TURN-{s}")}), + ]; + for turn in 0..100 { + id += 1; + let body = json!({"model": "claude-sonnet-4-5", "system": system, "tools": tools, + "messages": messages, "max_tokens": 32000, "stream": true}) + .to_string(); + let mut frames = vec![( + "message_start", + json!({"type": "message_start", "message": {"id": "m", "model": "claude-sonnet-4-5", "usage": {"input_tokens": 10}}}), + )]; + frames.push(("content_block_start", json!({"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": ""}}))); + for k in 0..200 { + frames.push(("content_block_delta", json!({"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": format!("想一想第 {k} 步 ")}}))); + } + frames.push(("content_block_start", json!({"type": "content_block_start", "index": 1, "content_block": {"type": "text", "text": ""}}))); + for k in 0..60 { + frames.push(("content_block_delta", json!({"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": format!("我来改第 {k} 处,")}}))); + } + frames.push(("content_block_start", json!({"type": "content_block_start", "index": 2, "content_block": {"type": "tool_use", "id": "t", "name": "Edit", "input": {}}}))); + for _ in 0..120 { + frames.push(("content_block_delta", json!({"type": "content_block_delta", "index": 2, "delta": {"type": "input_json_delta", "partial_json": "fn main() { println!(\\\"hi\\\"); }"}}))); + } + frames.push(("message_delta", json!({"type": "message_delta", "delta": {"stop_reason": "tool_use"}, "usage": {"output_tokens": 900}}))); + let answer = sse(&frames); + bytes += body.len() + answer.len(); + d.put(&at(id, NOW + id, "/v1/messages"), body.as_bytes(), &answer); + messages.push(json!({"role": "assistant", "content": [ + {"type": "text", "text": format!("第 {turn} 轮我来改")}, + {"type": "tool_use", "id": format!("t{turn}"), "name": "Edit", "input": {"code": "y".repeat(1500)}}]})); + messages.push(json!({"role": "user", "content": [{"type": "tool_result", "tool_use_id": format!("t{turn}"), + "content": format!("{}\n第 {turn} 轮的结果", "文件内容 let x = 1;\n".repeat(300))}]})); + } + } + eprintln!("{id} requests, {} MB of bodies", bytes / 1_000_000); + let all = Budget { + bodies: 100_000, + time: Duration::from_secs(600), + }; + for (what, q) in [ + ("an ASCII word that is nowhere", "zzqx-never"), + ("a Chinese word that is nowhere", "从未出现过"), + ( + "a word from each session's first turn (in every body)", + "first-turn-1", + ), + ("a word in most answers", "我来改第 3 处"), + ] { + let t = Instant::now(); + let o = d.find_with(q, all, None); + let took = t.elapsed(); + eprintln!( + "{what}: {} rows in {took:?} ({:?} per request), {} hits", + id, + took / id as u32, + o.hits.len() + ); + } + let t = Instant::now(); + let o = d.find_with("zzqx-never", Budget::DEFAULT, None); + eprintln!( + "default budget: stopped {:?} after {:?} at request {:?}", + o.stopped, + t.elapsed(), + o.next.map(|c| c.id) + ); + } +} diff --git a/crates/tw-store/src/search/needle.rs b/crates/tw-store/src/search/needle.rs new file mode 100644 index 00000000..b1ab82ab --- /dev/null +++ b/crates/tw-store/src/search/needle.rs @@ -0,0 +1,572 @@ +//! 搜索词怎么比:和界面同一种不分大小写、原始字节上的粗筛、命中前后的那一小段。 +//! +//! **大小写按界面的规则来。**流量页的筛选框是 `x.toLowerCase().includes(q)`,而 +//! JavaScript 的 `toLowerCase` 按 Unicode 的表转小写 —— 「Über」和「über」是对得上的。 +//! SQLite 的 `LIKE` 只认 ASCII 的大小写,搬到库里照样用它的话,同一个词在界面上筛得到、 +//! 在整份记录里却找不到。这里用 Rust 的 `str::to_lowercase`,和 JavaScript 是同一张表 +//! (连词尾的 Σ → ς 都一样)。 + +use std::ops::Range; + +/// 命中前后各留多少个字。 +pub const EXCERPT_CHARS: usize = 40; + +/// 脱敏时命中两边各多带多少个字。比摘录宽得多:密钥被打成 `sk-an…7f9c` 之后会变短, +/// 留得太窄的话,打完码摘录就只剩一两个字 +const MASK_MARGIN: usize = 160; + +/// 一段正文里最多试几处命中。前几处都在密钥里面(打码之后对不上)的,再往后找也多半 +/// 一样,而每试一处都要打一次码 +const MAX_TRIES: usize = 16; + +/// 去掉首尾的空白,**和 JavaScript 的 `String.prototype.trim` 去掉的是同一批字符**。 +/// +/// 界面先 trim 再比(`filterRows` 里的 `f.q.trim()`)。Rust 的 `str::trim` 按 Unicode 的 +/// White_Space 认,比 JavaScript 多去一个 U+0085、少去一个 U+FEFF。 +pub fn js_trim(s: &str) -> &str { + s.trim_matches(|c: char| (c.is_whitespace() && c != '\u{85}') || c == '\u{feff}') +} + +/// 搜索词的样子:去掉首尾空白、转小写。只剩空白的是 `None` —— 和界面一样,那等于 +/// 没有按文本筛。 +pub fn fold(q: &str) -> Option { + let t = js_trim(q); + (!t.is_empty()).then(|| t.to_lowercase()) +} + +/// `hay` 转小写之后含不含 `needle`(已经转过小写)。界面上 `hay.toLowerCase().includes(q)` +/// 那一句。 +pub fn contains_folded(hay: &str, needle: &str) -> bool { + if hay.is_ascii() { + // ASCII 的小写还是 ASCII,装不下 ASCII 以外的字;只有 A–Z 会变,不必整串转一遍 + return needle.is_ascii() && find_ascii_ci(hay.as_bytes(), needle.as_bytes(), 0).is_some(); + } + hay.to_lowercase().contains(needle) +} + +/// 从 `from` 起找 `needle`(小写的 ASCII),ASCII 字母不分大小写。 +fn find_ascii_ci(hay: &[u8], needle: &[u8], from: usize) -> Option { + let Some((&first, rest)) = needle.split_first() else { + return Some(from.min(hay.len())); + }; + let last = hay.len().checked_sub(needle.len())?; + let mut i = from; + while i <= last { + // 先找首字节,绝大多数位置在这一步就过去了 + let skip = hay[i..=last] + .iter() + .position(|b| b.to_ascii_lowercase() == first)?; + i += skip; + if hay[i + 1..i + needle.len()] + .iter() + .zip(rest) + .all(|(h, n)| h.to_ascii_lowercase() == *n) + { + return Some(i); + } + i += 1; + } + None +} + +/// 在 `text` 里从 `from`(字节,落在字符边界上)起找 `needle`,给出原文里的字节范围。 +fn find_folded(text: &str, needle: &str, from: usize) -> Option> { + if text.is_ascii() { + let i = needle + .is_ascii() + .then(|| find_ascii_ci(text.as_bytes(), needle.as_bytes(), from))??; + return Some(i..i + needle.len()); + } + // 小写会改字节数(İ → i̇、K → k),所以在小写之后的文本里找,再一个字一个字地数回 + // 原文。逐字的小写和整串的小写只在词尾的 Σ 上不同(σ/ς),两者字节数一样,数得准。 + // 整串转小写而不是只转 `from` 之后那段:Σ 是不是词尾要看前面的字 + let lower = text.to_lowercase(); + let lower_from: usize = text[..from] + .chars() + .map(|c| c.to_lowercase().map(char::len_utf8).sum::()) + .sum(); + let p = lower_from + lower[lower_from..].find(needle)?; + let end = p + needle.len(); + // 从头再数一遍,找出盖住 [p, end) 的那几个原文的字 + let mut acc = 0; + let mut start = None; + for (i, c) in text.char_indices() { + let w: usize = c.to_lowercase().map(char::len_utf8).sum(); + if start.is_none() && acc + w > p { + start = Some(i); + } + if acc + w >= end { + return Some(start.unwrap_or(i)..i + c.len_utf8()); + } + acc += w; + } + None +} + +/// 一个要在正文里找的词。 +#[derive(Debug, Clone)] +pub struct Needle { + /// 转过小写的搜索词 + folded: String, + /// 在原始字节上粗筛用的那一小段 + probe: Option, +} + +/// 搜索词里挑出来的一段,**它在 JSON 原文里一定照样写着**(只要正文里有这个词)。 +#[derive(Debug, Clone)] +enum Probe { + /// 一段 ASCII 字母和数字,小写。没有哪个 JSON 写法会转义它们;大写的照样认 + Ascii { + bytes: Vec, + /// 含 `i` 或 `k`:U+0130(İ)和 U+212A(开尔文符号 K)小写之后是 ASCII 的 + /// i 和 k,原文里写的却不是。只有这两个字会这样 + exotic: bool, + }, + /// 一段没有大小写之分的非 ASCII 字(汉字之类)。原文里要么就是这几个字的 UTF-8, + /// 要么全写成 `\uXXXX`:Python 默认把 ASCII 以外的字全部转义 + Wide { utf8: Vec, escaped: Vec }, +} + +impl Needle { + /// `folded` 是 [`fold`] 出来的样子。 + pub fn new(folded: String) -> Needle { + let probe = probe_of(&folded); + Needle { folded, probe } + } + + /// 这份 JSON 原文(请求体,或者整包的响应)里可能有这个词吗。 + /// + /// **只会多说、不会少说。**说「没有」的那些就不用解析了 —— 一个请求体动辄几百 KB, + /// 而绝大多数请求里根本没有这个词。只对整包的 JSON 成立:流式的回答一个词可能被切在 + /// 两帧里,原文里找不到整个词。 + pub fn might_be_in(&self, raw: &[u8]) -> bool { + match &self.probe { + None => true, + Some(Probe::Ascii { bytes, exotic }) => { + find_ascii_ci(raw, bytes, 0).is_some() || (*exotic && has_exotic(raw)) + } + Some(Probe::Wide { utf8, escaped }) => { + memfind(raw, utf8) || find_ascii_ci(raw, escaped, 0).is_some() + } + } + } + + /// 第一处对上、**打完码之后还对得上**的地方,连同前后那一小段。 + /// + /// 先在原文里找,找到了只给它两边的一段打码再核一遍:整段正文打码太贵(一个工具结果 + /// 就能有几十 KB),而对得上的只是少数。落在密钥里的命中打完码就对不上了 —— 那不能 + /// 交出去,接着找下一处。 + pub fn excerpt(&self, text: &str) -> Option { + let mut from = 0; + for _ in 0..MAX_TRIES { + let hit = find_folded(text, &self.folded, from)?; + let (ws, we) = mask_window(text, &hit); + let masked = tw_secret::mask_body(&text[ws..we]); + if let Some(m) = find_folded(&masked, &self.folded, 0) { + return Some(cut(&masked, m, ws > 0, we < text.len())); + } + // 下一处从这一处的第二个字起找:命中可以互相重叠 + from = hit.start + text[hit.start..].chars().next().map_or(1, char::len_utf8); + } + None + } +} + +/// 命中和前后的字:空白(含换行)并成一个空格。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Excerpt { + pub before: String, + pub matched: String, + pub after: String, +} + +/// 从搜索词里挑一段粗筛用的。 +/// +/// 优先长一点的 ASCII 字母数字(三个以上),否则一段汉字这类没有大小写的字,再否则短的 +/// ASCII 也行。一样都挑不出(全是标点、或者全是有大小写的外文字母)就不粗筛。 +fn probe_of(folded: &str) -> Option { + let ascii = longest_run(folded, |c| c.is_ascii_alphanumeric()); + let wide = longest_run(folded, literal_wide); + let ascii_probe = || { + let bytes = ascii.as_bytes().to_vec(); + let exotic = bytes.iter().any(|b| matches!(b, b'i' | b'k')); + Probe::Ascii { bytes, exotic } + }; + if ascii.len() >= 3 { + Some(ascii_probe()) + } else if !wide.is_empty() { + Some(Probe::Wide { + utf8: wide.as_bytes().to_vec(), + escaped: escape(wide).into_bytes(), + }) + } else if !ascii.is_empty() { + Some(ascii_probe()) + } else { + None + } +} + +/// 满足 `keep` 的最长一段(按字数)。 +fn longest_run(s: &str, keep: impl Fn(char) -> bool) -> &str { + let mut best = 0..0; + let mut start = None; + let mut count = 0; + let mut best_count = 0; + for (i, c) in s.char_indices().chain(std::iter::once((s.len(), '\0'))) { + if i < s.len() && keep(c) { + if start.is_none() { + start = Some(i); + count = 0; + } + count += 1; + } else if let Some(st) = start.take() + && count > best_count + { + best = st..i; + best_count = count; + } + } + &s[best] +} + +/// 这个字在 JSON 原文里只会写成它自己的 UTF-8 或者 `\uXXXX`,而且正文里只有它自己 +/// 小写之后是它。 +/// +/// 有大小写之分的不行(原文里可能是大写);U+0307 是 İ 小写之后的后半个字;U+2028、 +/// U+2029 Go 的 JSON 会单独转义(别的字照写),两种写法掺在一起时找不到。 +fn literal_wide(c: char) -> bool { + !c.is_ascii() + && !matches!(c, '\u{307}' | '\u{2028}' | '\u{2029}') + && c.to_lowercase().eq(std::iter::once(c)) + && c.to_uppercase().eq(std::iter::once(c)) +} + +/// 全写成 `\uXXXX` 的样子,十六进制小写。BMP 以外的字是一对代理项 +fn escape(s: &str) -> String { + let mut out = String::with_capacity(s.len() * 4); + let mut units = [0u16; 2]; + for c in s.chars() { + for u in c.encode_utf16(&mut units) { + out.push_str(&format!("\\u{u:04x}")); + } + } + out +} + +/// 原文里有没有那两个小写之后变成 ASCII 字母的字(见 `Probe::Ascii::exotic`), +/// UTF-8 或者转义的写法都算。 +fn has_exotic(raw: &[u8]) -> bool { + memfind(raw, "\u{130}".as_bytes()) + || memfind(raw, "\u{212a}".as_bytes()) + || find_ascii_ci(raw, b"\\u0130", 0).is_some() + || find_ascii_ci(raw, b"\\u212a", 0).is_some() +} + +fn memfind(hay: &[u8], needle: &[u8]) -> bool { + let Some((&first, rest)) = needle.split_first() else { + return true; + }; + let Some(last) = hay.len().checked_sub(needle.len()) else { + return false; + }; + let mut i = 0; + while i <= last { + let Some(skip) = hay[i..=last].iter().position(|b| *b == first) else { + return false; + }; + i += skip; + if &hay[i + 1..i + needle.len()] == rest { + return true; + } + i += 1; + } + false +} + +/// 和 `tw_secret::mask_body` 认同一种 token:一个密钥一定是一整个 token,窗口的两头 +/// 不能把它切开 +fn is_tok(c: char) -> bool { + c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') +} + +/// 给命中打码时取的那一段:两边各 [`MASK_MARGIN`] 个字,再往外扩到 token 的边界。 +/// +/// **两头都落在 token 边界上,这一段打出来的码就和整段正文打码时这一段的样子一样**: +/// `mask_body` 一个 token 一个 token 地判断,只看 token 自己和它前面那个字是不是 token 的 +/// 一部分。 +fn mask_window(text: &str, hit: &Range) -> (usize, usize) { + let mut start = hit.start; + let mut back = text[..hit.start].char_indices().rev(); + for _ in 0..MASK_MARGIN { + match back.next() { + Some((i, _)) => start = i, + None => break, + } + } + while let Some(c) = text[..start].chars().next_back() + && is_tok(c) + { + start -= c.len_utf8(); + } + let mut end = hit.end; + let mut fwd = text[hit.end..].chars(); + for _ in 0..MASK_MARGIN { + match fwd.next() { + Some(c) => end += c.len_utf8(), + None => break, + } + } + while let Some(c) = text[end..].chars().next() + && is_tok(c) + { + end += c.len_utf8(); + } + (start, end) +} + +/// 空白和控制字符都算空白:换行、制表符、NUL 在一行摘录里都只该是一个空格 +fn blank(c: char) -> bool { + c.is_whitespace() || c.is_control() +} + +/// 把空白并成一个空格。 +fn squeeze(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut gap = false; + for c in s.chars() { + if blank(c) { + gap = true; + continue; + } + if gap && !out.is_empty() { + out.push(' '); + } + gap = false; + out.push(c); + } + if gap { + out.push(' '); + } + out +} + +/// 切出命中和前后各 [`EXCERPT_CHARS`] 个字。`more_before` / `more_after`:这一段之外 +/// 还有正文。 +fn cut(text: &str, hit: Range, more_before: bool, more_after: bool) -> Excerpt { + // 往前数:空白并成一个空格,并完之后的字才算数 + let mut before: Vec = Vec::new(); + let mut seen = 0; + let mut gap = false; + let mut rest_before = false; + for c in text[..hit.start].chars().rev() { + if blank(c) { + gap = true; + continue; + } + if seen == EXCERPT_CHARS { + rest_before = true; + break; + } + if gap && !before.is_empty() { + before.push(' '); + } + gap = false; + before.push(c); + seen += 1; + } + // 紧挨着命中的空白要留一个:「我的 key」里命中 key 时,前面是「我的 」 + let touching = text[..hit.start].chars().next_back().is_some_and(blank); + before.reverse(); + let mut b: String = before.into_iter().collect(); + if touching && !b.is_empty() && !b.ends_with(' ') { + b.push(' '); + } + if rest_before || more_before { + b.insert(0, '…'); + } + + let mut after = String::new(); + let mut seen = 0; + let mut gap = false; + let mut rest_after = false; + for c in text[hit.end..].chars() { + if blank(c) { + gap = true; + continue; + } + if seen == EXCERPT_CHARS { + rest_after = true; + break; + } + // 命中后面紧跟着的空白也留一个 + if gap { + after.push(' '); + } + gap = false; + after.push(c); + seen += 1; + } + if rest_after || more_after { + after.push('…'); + } + Excerpt { + before: b, + matched: squeeze(&text[hit]), + after, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn needle(q: &str) -> Needle { + Needle::new(fold(q).unwrap()) + } + + /// 界面先 `trim()` 再比。JavaScript 去掉的那一批:U+FEFF 去、U+0085 不去 + #[test] + fn trimming_matches_javascript() { + assert_eq!(js_trim("\u{feff}\u{3000} hi\t\n"), "hi"); + assert_eq!(js_trim("\u{85}hi\u{85}"), "\u{85}hi\u{85}"); + assert_eq!(fold(" "), None); + assert_eq!(fold(" GPT-5.5 "), Some("gpt-5.5".into())); + } + + /// 和 `toLowerCase().includes()` 一样:ASCII 以外的大小写也认,词尾的 Σ 是 ς + #[test] + fn case_folding_is_the_unicode_one_the_ui_uses() { + assert!(contains_folded("Übersetzer-Relay", "über")); + assert!(contains_folded("ЯНДЕКС", "яндекс")); + assert!(contains_folded("ΟΔΟΣ", "οδος"), "词尾的 Σ 转成 ς"); + assert!(!contains_folded("ΟΔΟΣ", "οδοσ")); + assert!(contains_folded("Claude-Sonnet", "sonnet")); + assert!(!contains_folded("claude", "中")); + // 开尔文符号小写之后就是 k + assert!(contains_folded("2\u{212a}", "2k")); + // 不是通配符 + assert!(!contains_folded("500", "50%")); + assert!(!contains_folded("axb", "a_b")); + assert!(contains_folded("a_b 50%", "a_b")); + } + + #[test] + fn the_hit_is_reported_where_it_is_in_the_original_text() { + let t = "前缀 İstanbul ÜBER alles"; + let r = find_folded(t, "über", 0).unwrap(); + assert_eq!(&t[r], "ÜBER"); + // 小写之后变长的字(İ → i̇)在命中前面,位置照样对得上 + let r = find_folded(t, "alles", 0).unwrap(); + assert_eq!(&t[r], "alles"); + // 命中落在一个字小写之后的前半截上:报整个字 + let r = find_folded(t, "i", 0).unwrap(); + assert_eq!(&t[r], "İ"); + // 从后面接着找 + let r = find_folded("ab AB ab", "ab", 1).unwrap(); + assert_eq!(r, 3..5); + } + + /// 粗筛只会多说:正文里有这个词,原文里就一定找得到那一段 + #[test] + fn the_prefilter_never_hides_a_word_that_is_there() { + // 大写写着的 + assert!(needle("Read_File").might_be_in(br#"{"t":"READ_FILE x"}"#)); + // Python 把汉字全写成 \uXXXX,大写十六进制也有人写(`\x5c` 是反斜杠) + let n = needle("中文搜索"); + assert!(n.might_be_in("{\"t\":\"中文搜索\"}".as_bytes())); + assert!(n.might_be_in(b"{\"t\":\"\x5cu4e2d\x5cu6587\x5cu641c\x5cu7d22\"}")); + assert!(n.might_be_in(b"{\"t\":\"\x5cu4E2D\x5cu6587\x5cu641C\x5cu7D22\"}")); + // BMP 以外的字是一对代理项 + let n = needle("\u{1f980}"); + assert!(n.might_be_in(b"{\"t\":\"\x5cud83e\x5cudd80\"}")); + // 开尔文符号和 İ 小写之后是 ASCII 的 k、i + assert!(needle("2k").might_be_in("{\"t\":\"2\u{212a}\"}".as_bytes())); + assert!(needle("2k").might_be_in(b"{\"t\":\"2\x5cu212A\"}")); + assert!(needle("ist").might_be_in("{\"t\":\"\u{130}st\"}".as_bytes())); + // 有大小写的外文字母挑不出粗筛的那一段,一律放过 + assert!(needle("über").might_be_in(b"{\"t\":\"\x5cu00dcBER\"}")); + assert!(needle("\u{ff}").might_be_in(b"{}")); + } + + #[test] + fn the_prefilter_turns_away_what_cannot_contain_the_word() { + assert!(!needle("timeout").might_be_in(br#"{"t":"time out"}"#)); + // 转义写到一半就断了(截断的请求体) + assert!(!needle("中文").might_be_in(b"{\"t\":\"\x5cu4e2d\x5cu65")); + assert!(!needle("搜索").might_be_in("{\"t\":\"中文\"}".as_bytes())); + } + + #[test] + fn the_excerpt_is_forty_characters_each_side_with_blanks_squeezed() { + let text = format!("{}\n\n needle here\t{}", "前".repeat(60), "后".repeat(60)); + let e = needle("NEEDLE").excerpt(&text).unwrap(); + assert_eq!(e.matched, "needle"); + assert_eq!(e.before, format!("…{} ", "前".repeat(40))); + assert_eq!(e.after, format!(" here {}…", "后".repeat(36))); + assert_eq!( + e.after.chars().filter(|c| *c != ' ' && *c != '…').count(), + 40 + ); + } + + #[test] + fn a_short_text_is_not_marked_as_cut() { + let e = needle("key").excerpt("我的 key 是这个").unwrap(); + assert_eq!( + (e.before.as_str(), e.matched.as_str(), e.after.as_str()), + ("我的 ", "key", " 是这个") + ); + let e = needle("abc").excerpt("abc").unwrap(); + assert_eq!((e.before.as_str(), e.after.as_str()), ("", "")); + } + + /// 摘录要交给界面,**和详情抽屉同一套打码**:命中旁边的密钥打掉,落在密钥里面的 + /// 命中不算 + #[test] + fn the_excerpt_is_masked_and_a_hit_inside_a_secret_does_not_count() { + let key = "sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123"; + let text = format!("我的 key 是 {key},请保管好"); + let e = needle("key 是").excerpt(&text).unwrap(); + assert!(!e.after.contains("abcdefghijklmnop"), "{e:?}"); + assert!(e.after.contains("sk-an…"), "{e:?}"); + // 只出现在密钥里的词:打完码就没有了 + assert_eq!(needle("klmnop").excerpt(&text), None); + // 密钥里有、正文里也有:交出正文里那一处 + let text = format!("{key} 之后又说了一遍 klmnop"); + let e = needle("klmnop").excerpt(&text).unwrap(); + assert!(e.before.ends_with("说了一遍 "), "{e:?}"); + assert!(!e.before.contains("abcdefghij"), "{e:?}"); + } + + /// 打码的那一段两头不切开 token:一把很长的密钥正好跨在边界上也认得出来。 + /// + /// 这把密钥只靠 `sk-` 开头认得出来(后面没有数字)。从中间切开的话,后半截看着就是 + /// 一串普通字母,会原样漏进摘录 + #[test] + fn a_secret_straddling_the_mask_window_is_still_masked() { + let key = format!("sk-{}", "abcdefgh".repeat(30)); + assert!(key.len() > MASK_MARGIN); + let text = format!("{key} needle"); + let e = needle("needle").excerpt(&text).unwrap(); + assert!(!e.before.contains("abcdefghabcdefgh"), "{e:?}"); + assert!(e.before.starts_with("sk-ab…"), "{e:?}"); + } + + #[test] + fn longest_runs_pick_the_probe() { + assert_eq!( + longest_run("a.bcd-ef", |c| c.is_ascii_alphanumeric()), + "bcd" + ); + assert_eq!(longest_run("中文 x 搜索词", literal_wide), "搜索词"); + assert_eq!(longest_run("", literal_wide), ""); + assert!(matches!(probe_of("gpt"), Some(Probe::Ascii { .. }))); + assert!(matches!(probe_of("go 中文"), Some(Probe::Wide { .. }))); + assert!(matches!(probe_of("go"), Some(Probe::Ascii { .. }))); + assert!(probe_of("!?-").is_none()); + // 有大小写的外文字母不行(原文里可能是大写),省略号这种没有大小写的可以 + assert!(probe_of("ü").is_none()); + assert!(matches!(probe_of("…"), Some(Probe::Wide { .. }))); + assert_eq!(escape("中🦀"), "\\u4e2d\\ud83e\\udd80"); + } +} diff --git a/crates/tw-store/src/search/sql.rs b/crates/tw-store/src/search/sql.rs new file mode 100644 index 00000000..796de76b --- /dev/null +++ b/crates/tw-store/src/search/sql.rs @@ -0,0 +1,156 @@ +//! 搜索在库里的那一半:按条件挑行,新的在前。 +//! +//! **条件只写在这一处。**只按记录找时它们是 `WHERE`;按正文找时,「按记录对没对上」 +//! 作为一列一起取出来,没对上的再去读正文 —— 两种找法说的是同一句 SQL,不会一边多认 +//! 一个字段。 + +use rusqlite::functions::FunctionFlags; +use rusqlite::types::{ToSql, ValueRef}; + +use super::{Ask, needle}; +use crate::db::{Db, DbError, RequestRow, row_from}; + +/// 给连接装上搜索要的 SQL 函数。每个连接打开时都装([`Db`] 的构造里调它)。 +/// +/// `tw_has(字段, 小写的词)`:字段转小写之后含不含这个词,和界面上 +/// `x.toLowerCase().includes(q)` 是同一个判断(见 [`needle::contains_folded`])。 +/// **不用 `LIKE`**:它只认 ASCII 的大小写(「Über」对不上「über」),而且 `%` 和 `_` +/// 是通配符,要一个一个转义;这个函数比的是字面的子串,两样问题都没有。字段是 NULL 的 +/// 什么都不含。 +pub(crate) fn register(conn: &rusqlite::Connection) -> rusqlite::Result<()> { + conn.create_scalar_function( + "tw_has", + 2, + FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC, + |ctx| { + let (ValueRef::Text(hay), ValueRef::Text(needle)) = (ctx.get_raw(0), ctx.get_raw(1)) + else { + return Ok(false); + }; + Ok( + match (std::str::from_utf8(hay), std::str::from_utf8(needle)) { + (Ok(hay), Ok(needle)) => needle::contains_folded(hay, needle), + _ => false, + }, + ) + }, + ) +} + +/// 无法计价:跑完了、报了用量,却没算出金额。 +/// +/// 和界面 `filterRows` 里那一条逐字对应:失败的、取消的(记录里的取消就是界面上的 +/// `cancelled` 状态)、一项用量都没报的不算。**和库里别处的 `NO_PRICE` 不是一回事**:那个 +/// 数的是「配一个价格就能解决的」,要求按量计费;这个是界面上那个筛选,不计费的上游记的是 +/// 确定的 $0,本来就不会出现在这里。 +const UNPRICED: &str = "(cost_micros IS NULL AND error IS NULL AND cancelled = 0 \ + AND (input_tokens IS NOT NULL OR output_tokens IS NOT NULL))"; + +/// 一句查询和它的参数(按名字绑定)。 +pub(crate) type Statement = (String, Vec<(&'static str, Box)>); + +impl Db { + /// 按 `ask` 挑一批行,新的在前,带着「按记录对没对上搜索词」。 + /// + /// 时刻有索引(`requests_at`),条件里时刻是一个范围,所以从新往旧沿着索引走,凑够 + /// `limit` 条就停;同一毫秒里的几条按请求号排(查询计划里那个「LAST TERM OF ORDER BY」 + /// 只在同一毫秒的几条里排,不是整表排序)。 + pub fn search_rows(&self, ask: &Ask) -> Result, DbError> { + let (sql, args) = statement(ask); + let mut st = self.conn().prepare(&sql)?; + let params: Vec<(&str, &dyn ToSql)> = args.iter().map(|(k, v)| (*k, v.as_ref())).collect(); + let rows = st.query_map(params.as_slice(), |r| { + Ok((row_from(r)?, r.get::<_, i64>("meta_hit")? != 0)) + })?; + Ok(rows.collect::, _>>()?) + } +} + +/// [`Db::search_rows`] 跑的那一句。**只拼用得上的条件**:没给的条件不写成 +/// `(? IS NULL OR …)`,那样查询计划看不出时刻是一个范围,就走不了索引。 +pub(crate) fn statement(ask: &Ask) -> Statement { + let q = ask.query; + let mut from = q.from_ms; + let mut upper = q.to_ms; + let mut conds: Vec = vec!["at_ms >= :from".into(), "at_ms <= :upper".into()]; + let mut args: Vec<(&'static str, Box)> = Vec::new(); + if let Some(floor) = ask.floor { + from = from.max(floor); + } + if let Some(c) = ask.before { + upper = upper.min(c.at_ms); + // 同一毫秒里排在它后面的(请求号更小的)还要 + conds.push("(at_ms < :before_at OR id < :before_id)".into()); + args.push((":before_at", Box::new(c.at_ms))); + args.push((":before_id", Box::new(c.id))); + } + args.push((":from", Box::new(from))); + args.push((":upper", Box::new(upper))); + if q.failed { + conds.push("error IS NOT NULL".into()); + } + if q.unpriced { + conds.push(UNPRICED.into()); + } + if let Some(c) = &q.client { + conds.push("client = :client".into()); + args.push((":client", Box::new(c.clone()))); + } + if let Some(p) = &q.provider { + // 本地应答的那一行在界面上没有上游(那一格写的是一句说明) + conds.push("(local = 0 AND provider = :provider)".into()); + args.push((":provider", Box::new(p.clone()))); + } + if let Some(m) = &q.model { + conds.push("model = :model".into()); + args.push((":model", Box::new(m.clone()))); + } + let mut flag = "1".to_string(); + if let Some(t) = &q.text { + args.push((":q", Box::new(t.clone()))); + args.push((":local", Box::new(q.local_matches))); + if !q.error_codes.is_empty() { + let codes = serde_json::to_string(&q.error_codes).unwrap_or_default(); + args.push((":codes", Box::new(codes))); + } + let text = text_matches(!q.error_codes.is_empty()); + if ask.flag_text { + flag = text; + } else { + conds.push(text); + } + } + args.push((":limit", Box::new(ask.limit as i64))); + let sql = format!( + "SELECT *, {flag} AS meta_hit FROM requests WHERE {} \ + ORDER BY at_ms DESC, id DESC LIMIT :limit", + conds.join(" AND ") + ); + (sql, args) +} + +/// 搜索词按记录对:**和界面 `filterRows` 的那一串 `||` 逐项对应**。 +/// +/// - 路径、密钥名、应用(按请求头认的)、模型、失败原因(英文原句):转小写之后含着它; +/// - 来源地址:**原样**含着它 —— 界面那一句没有转小写(地址里没有大写字母,结果一样, +/// 照抄是为了两边说的是同一件事); +/// - 上游:界面那一格写的是什么就按什么对,本地应答的那一行写的是一句说明,由界面告诉 +/// 我们那句话对不对得上(`:local`),它的上游名不参与; +/// - 失败原因的码在界面交来的那张清单里(界面按码翻那句话)。 +/// +/// 每一项都不会是 NULL:这一串还要当作一列取出来。 +fn text_matches(codes: bool) -> String { + let mut terms = vec![ + "tw_has(path, :q)", + "tw_has(client, :q)", + "tw_has(client_hint, :q)", + "IFNULL(instr(peer, :q), 0) > 0", + "(CASE WHEN local = 1 THEN :local ELSE tw_has(provider, :q) END)", + "tw_has(model, :q)", + "tw_has(error, :q)", + ]; + if codes { + terms.push("IFNULL(error_code IN (SELECT value FROM json_each(:codes)), 0)"); + } + format!("({})", terms.join(" OR ")) +} diff --git a/crates/tw-store/src/search/text.rs b/crates/tw-store/src/search/text.rs new file mode 100644 index 00000000..a0a1d628 --- /dev/null +++ b/crates/tw-store/src/search/text.rs @@ -0,0 +1,591 @@ +//! 从存下来的正文里拆出要找的那两段文字:请求里新的那一轮、回答。 +//! +//! **怎么读四种格式不在这里写**:请求按 tw-dialect 解成中间表示,回答按它的整包解码和 +//! 流读法读 —— 网关转换格式用的就是这几样。这里只决定读哪一段。 + +use serde_json::Value; +use tw_dialect::ir::{Block, Delta, Dialect, Event, Part, Role}; + +/// 这个路径是不是生成回答的那个调用;是的话,客户端说的是哪种格式。 +/// +/// **和网关认的是同一批路径**(`tw_gateway::client_api::ClientApi` 的 `of_path` 加 +/// `generates`,tw-control 的测试逐条核对两边)。只读生成回答的那些:数 token 的请求带着 +/// 和下一个请求一样的整段对话,读它只会给同一轮话多出一条重复的命中。 +pub fn client_dialect(path: &str) -> Option { + let p = path.trim_end_matches('/'); + // 有的客户端把 base_url 写成带 `/v1` 的,有的不带 + match p.strip_prefix("/v1").unwrap_or(p) { + "/messages" => return Some(Dialect::Anthropic), + "/chat/completions" => return Some(Dialect::Chat), + "/responses" => return Some(Dialect::Responses), + _ => {} + } + if p == "/backend-api/codex/responses" { + return Some(Dialect::Responses); + } + (p.contains("/models/") + && (p.ends_with(":generateContent") || p.ends_with(":streamGenerateContent"))) + .then_some(Dialect::Gemini) +} + +/// 契约里的格式名换成 tw-dialect 的。 +pub fn dialect_of(d: tw_api::Dialect) -> Dialect { + match d { + tw_api::Dialect::Anthropic => Dialect::Anthropic, + tw_api::Dialect::OpenaiChat => Dialect::Chat, + tw_api::Dialect::OpenaiResponses => Dialect::Responses, + tw_api::Dialect::Gemini => Dialect::Gemini, + tw_api::Dialect::Bedrock => Dialect::Bedrock, + } +} + +/// 请求里新的那一轮:对话末尾连着的那几条用户消息里的文字和工具结果,一段一行。 +/// +/// **只读这一轮。**Claude Code 这类客户端每个请求都把整段对话重发一遍:按整个请求体找的 +/// 话,第三轮里说过的一句话会让之后每一个请求都对上。每个请求里新的只有最后这一轮 —— +/// 用户刚说的话,或者刚跑完的工具交回来的结果。 +/// +/// 解不开(截断了的、不是 JSON 的)就是 `None`。 +pub fn user_turn(body: &[u8], path: &str) -> Option { + let dialect = client_dialect(path)?; + let mut v: Value = serde_json::from_slice(body).ok()?; + trim_for_reading(&mut v, dialect); + let decoded = tw_dialect::convert::decode(dialect, &v, path, None).ok()?; + let msgs = &decoded.request.messages; + let last = msgs.iter().rposition(|m| m.role == Role::User)?; + let first = msgs[..last] + .iter() + .rposition(|m| m.role != Role::User) + .map_or(0, |i| i + 1); + let mut out = String::new(); + for m in &msgs[first..=last] { + for p in &m.parts { + match p { + Part::Text(t) => line(&mut out, t), + Part::ToolResult(r) => line(&mut out, &r.text()), + _ => {} + } + } + } + (!out.is_empty()).then_some(out) +} + +/// 解码之前去掉读文字用不着、又会让解码白费力气或者干脆拒绝的东西。 +/// +/// - **服务端状态的引用**(Responses 的 `previous_response_id`、`compaction` 这些,Gemini 的 +/// `cachedContent`):tw-dialect 见到它们就拒绝转换 —— 转给别家的上游会丢掉前文。可这里 +/// 只读请求里写着的字,那部分前文本来就不在请求里,不该因此连最后一轮也读不到。 +/// - **工具定义**:Claude Code 每个请求带着几十 KB,读文字用不着。 +/// - **最后一条助手消息之前的对话**:新的那一轮一定在它之后。长对话的请求体大头就在这里, +/// 解码会把每张截图的 base64 都复制一遍。只认确定是助手说的(`role` 写着 `assistant` / +/// `model`):剩下的交给解码去分,拿不准的留着不会读错,只是多读几条。 +fn trim_for_reading(v: &mut Value, dialect: Dialect) { + let Some(o) = v.as_object_mut() else { return }; + o.remove("tools"); + let turns = match dialect { + Dialect::Responses => { + for k in [ + "previous_response_id", + "conversation", + "prompt", + "background", + ] { + o.remove(k); + } + "input" + } + Dialect::Gemini => { + o.remove("cachedContent"); + o.remove("cached_content"); + "contents" + } + _ => "messages", + }; + let Some(items) = o.get_mut(turns).and_then(Value::as_array_mut) else { + return; + }; + let assistant = |m: &Value| { + matches!( + m.get("role").and_then(Value::as_str), + Some("assistant" | "model") + ) + }; + // 末尾的助手消息是预填(prefill,替模型开个头):新的那一轮在它前面,从它前面找 + let end = items + .iter() + .rposition(|m| !assistant(m)) + .map_or(0, |i| i + 1); + if let Some(i) = items[..end].iter().rposition(assistant) { + items.drain(..=i); + } + if dialect == Dialect::Responses { + items.retain(|it| { + !matches!( + it.get("type").and_then(Value::as_str), + Some("item_reference" | "compaction") + ) + }); + } +} + +/// 回答的文字,一个文字块一行。推理和工具调用不算 —— 它们不是写给人看的那部分。 +/// +/// `body` 是上游的原话(存的就是它):整包的 JSON、SSE 的流(Bedrock 的二进制帧在网关 +/// 进门时已经转成了 SSE),或者 Gemini 不带 `alt=sse` 时那个逐步写出的 JSON 数组。按 +/// 开头的字节分辨,不看请求要没要流:上游只给流、客户端要整包的时候,存下来的是流。 +/// `upstream` 是回答它的那一家说的格式。 +pub fn answer(body: &[u8], upstream: Dialect) -> Option { + let out = match body.iter().find(|b| !b.is_ascii_whitespace())? { + b'{' => { + let v: Value = serde_json::from_slice(body).ok()?; + let r = match upstream { + Dialect::Anthropic => tw_dialect::anthropic::decode_response(&v), + Dialect::Chat => tw_dialect::chat::decode_response(&v), + Dialect::Responses => tw_dialect::responses::decode_response(&v), + Dialect::Gemini => tw_dialect::gemini::decode_response(&v), + Dialect::Bedrock => tw_dialect::bedrock::decode_response(&v), + }; + let mut out = String::new(); + for b in &r.blocks { + if let Block::Text(t) = b { + line(&mut out, t); + } + } + out + } + b'[' if upstream == Dialect::Gemini => { + let v: Value = serde_json::from_slice(body).ok()?; + let mut p = tw_dialect::gemini::stream::Parser::default(); + let mut events = Vec::new(); + for chunk in v.as_array()? { + p.chunk(chunk, &mut events); + } + p.finish(&mut events); + text_of(events) + } + _ => { + // **一小块一小块地喂。**拆帧器从缓冲区头上一帧一帧地取,整份 256 KB 一次喂进去 + // 的话,每取一帧都要把后面的字节往前挪一遍 + let mut r = tw_dialect::convert::Reader::new(upstream); + let mut events = Vec::new(); + for piece in body.chunks(16 * 1024) { + events.extend(r.feed(piece)); + } + events.extend(r.finish()); + text_of(events) + } + }; + (!out.is_empty()).then_some(out) +} + +/// 流里的文字增量接起来。换了一个文字块就另起一行 +fn text_of(events: Vec) -> String { + let mut out = String::new(); + let mut block = None; + for e in events { + if let Event::Delta { + index, + delta: Delta::Text(t), + } = e + { + if block != Some(index) && !out.is_empty() && !out.ends_with('\n') { + out.push('\n'); + } + block = Some(index); + out.push_str(&t); + } + } + out +} + +fn line(out: &mut String, t: &str) { + if t.is_empty() { + return; + } + if !out.is_empty() { + out.push('\n'); + } + out.push_str(t); +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn turn(body: Value, path: &str) -> Option { + user_turn(body.to_string().as_bytes(), path) + } + + #[test] + fn the_same_paths_as_the_gateway_are_generation_calls() { + assert_eq!(client_dialect("/v1/messages"), Some(Dialect::Anthropic)); + assert_eq!(client_dialect("/messages/"), Some(Dialect::Anthropic)); + assert_eq!(client_dialect("/v1/chat/completions"), Some(Dialect::Chat)); + assert_eq!(client_dialect("/v1/responses"), Some(Dialect::Responses)); + assert_eq!( + client_dialect("/backend-api/codex/responses"), + Some(Dialect::Responses) + ); + assert_eq!( + client_dialect("/v1beta/models/gemini-2.5-pro:streamGenerateContent"), + Some(Dialect::Gemini) + ); + for p in [ + "/v1/messages/count_tokens", + "/v1/embeddings", + "/v1beta/models/gemini-2.5-pro:countTokens", + "/v1/models", + ] { + assert_eq!(client_dialect(p), None, "{p}"); + } + } + + /// 长对话里只读最后一轮:前面说过的话不算这个请求的 + #[test] + fn only_the_last_user_turn_of_a_long_conversation_is_read() { + let mut messages = vec![json!({"role": "user", "content": "第一轮:帮我找 OLD-WORD"})]; + for i in 0..30 { + messages.push(json!({"role": "assistant", "content": [ + {"type": "text", "text": format!("回复 {i}")}, + {"type": "tool_use", "id": format!("t{i}"), "name": "Read", "input": {"path": "a.rs"}} + ]})); + messages.push(json!({"role": "user", "content": [ + {"type": "tool_result", "tool_use_id": format!("t{i}"), "content": format!("文件内容 {i}")} + ]})); + } + messages.push(json!({"role": "assistant", "content": "好的"})); + messages.push(json!({"role": "user", "content": [ + {"type": "text", "text": "提醒"}, + {"type": "text", "text": "最后一句 NEW-WORD"} + ]})); + let body = json!({"model": "claude-sonnet-4-5", "system": "你是助手", "messages": messages, + "tools": [{"name": "Read", "input_schema": {"type": "object"}}]}); + let t = turn(body, "/v1/messages").unwrap(); + assert_eq!( + t, + "提醒\n最后一句 NEW-WORD" + ); + assert!(!t.contains("OLD-WORD")); + } + + /// 工具跑完交回来的结果就是这一轮新的东西 + #[test] + fn tool_results_are_part_of_the_turn_in_every_format() { + let anthropic = json!({"messages": [ + {"role": "user", "content": "跑一下"}, + {"role": "assistant", "content": [{"type": "tool_use", "id": "a", "name": "Bash", "input": {}}]}, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "a", + "content": [{"type": "text", "text": "exit 0: 编译通过"}]}]} + ]}); + assert_eq!(turn(anthropic, "/v1/messages").unwrap(), "exit 0: 编译通过"); + + // Chat 的工具结果是 `tool` 角色,几条连着的都算这一轮 + let chat = json!({"messages": [ + {"role": "system", "content": "sys"}, + {"role": "user", "content": "跑一下"}, + {"role": "assistant", "content": null, "tool_calls": [ + {"id": "a", "type": "function", "function": {"name": "ls", "arguments": "{}"}}, + {"id": "b", "type": "function", "function": {"name": "pwd", "arguments": "{}"}}]}, + {"role": "tool", "tool_call_id": "a", "content": "README.md"}, + {"role": "tool", "tool_call_id": "b", "content": "/home/me"} + ]}); + assert_eq!( + turn(chat, "/v1/chat/completions").unwrap(), + "README.md\n/home/me" + ); + + let responses = json!({"instructions": "You are Codex", "input": [ + {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "跑一下"}]}, + {"type": "reasoning", "summary": [], "encrypted_content": "gAAA"}, + {"type": "function_call", "call_id": "c1", "name": "shell", "arguments": "{}"}, + {"type": "function_call_output", "call_id": "c1", "output": "cargo build 成功"} + ]}); + assert_eq!( + turn(responses, "/backend-api/codex/responses").unwrap(), + "cargo build 成功" + ); + + let gemini = json!({"contents": [ + {"role": "user", "parts": [{"text": "跑一下"}]}, + {"role": "model", "parts": [{"functionCall": {"name": "run", "args": {}}}]}, + {"role": "user", "parts": [{"functionResponse": {"name": "run", "response": {"output": "完成"}}}]} + ]}); + assert_eq!( + turn( + gemini, + "/v1beta/models/gemini-2.5-pro:streamGenerateContent" + ) + .unwrap(), + "完成" + ); + } + + /// 末尾替模型开了个头(预填):新的那一轮是它前面那条用户消息 + #[test] + fn a_prefilled_answer_does_not_hide_the_turn_before_it() { + let body = json!({"messages": [ + {"role": "user", "content": "旧问题"}, + {"role": "assistant", "content": "旧回答"}, + {"role": "user", "content": "给我一段 JSON"}, + {"role": "assistant", "content": "{"} + ]}); + assert_eq!(turn(body, "/v1/messages").unwrap(), "给我一段 JSON"); + let only = json!({"messages": [{"role": "assistant", "content": "{"}]}); + assert_eq!(turn(only, "/v1/messages"), None); + } + + /// Responses 的 `input` 也可以直接是一句话 + #[test] + fn a_responses_input_can_be_one_string() { + let body = json!({"model": "gpt-5.5", "input": "一句话"}); + assert_eq!(turn(body, "/v1/responses").unwrap(), "一句话"); + } + + /// 带着服务端状态的请求转不了别家,可它写着的字照样读得到 + #[test] + fn server_side_state_does_not_stop_the_turn_from_being_read() { + let body = json!({"previous_response_id": "resp_1", "background": true, "input": [ + {"type": "compaction", "encrypted_content": "gAAA"}, + {"type": "item_reference", "id": "msg_1"}, + {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "接着来"}]} + ]}); + assert_eq!(turn(body, "/v1/responses").unwrap(), "接着来"); + let gemini = json!({"cachedContent": "cachedContents/abc", + "contents": [{"role": "user", "parts": [{"text": "缓存之后"}]}]}); + assert_eq!( + turn(gemini, "/v1beta/models/gemini-2.5-pro:generateContent").unwrap(), + "缓存之后" + ); + } + + /// Python 客户端把 ASCII 以外的字全写成 `\uXXXX`:按 JSON 解开之后就是原字 + #[test] + fn escaped_text_is_read_as_the_characters_it_stands_for() { + let body = b"{\"messages\":[{\"role\":\"user\",\"content\":\"\x5cu8bf7\x5cu5e2e\x5cu6211\x5cu770b\x5cu770b\"}]}"; + assert_eq!(user_turn(body, "/v1/messages").unwrap(), "请帮我看看"); + } + + #[test] + fn a_body_that_cannot_be_read_gives_nothing() { + assert_eq!( + user_turn(b"{\"messages\":[{\"role\":\"user\"", "/v1/messages"), + None + ); + assert_eq!(user_turn(b"{\"messages\":[]}", "/v1/messages"), None); + assert_eq!(user_turn(b"{}", "/v1/messages/count_tokens"), None); + } + + fn sse(frames: &[(&str, Value)]) -> Vec { + let mut s = String::new(); + for (event, data) in frames { + if !event.is_empty() { + s.push_str(&format!("event: {event}\n")); + } + s.push_str(&format!("data: {data}\n\n")); + } + s.into_bytes() + } + + #[test] + fn the_answer_of_an_anthropic_stream_is_its_text_deltas() { + let body = sse(&[ + ( + "message_start", + json!({"type": "message_start", "message": {"id": "m", "model": "x", "usage": {"input_tokens": 3}}}), + ), + ( + "content_block_start", + json!({"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": ""}}), + ), + ( + "content_block_delta", + json!({"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "推理不算"}}), + ), + ( + "content_block_start", + json!({"type": "content_block_start", "index": 1, "content_block": {"type": "text", "text": ""}}), + ), + ( + "content_block_delta", + json!({"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": "答案是"}}), + ), + ("ping", json!({"type": "ping"})), + ( + "content_block_delta", + json!({"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": "四十二"}}), + ), + ( + "content_block_start", + json!({"type": "content_block_start", "index": 2, "content_block": {"type": "tool_use", "id": "t", "name": "Write", "input": {}}}), + ), + ( + "content_block_delta", + json!({"type": "content_block_delta", "index": 2, "delta": {"type": "input_json_delta", "partial_json": "{\"x\":1}"}}), + ), + ( + "message_delta", + json!({"type": "message_delta", "delta": {"stop_reason": "tool_use"}, "usage": {"output_tokens": 9}}), + ), + ]); + assert_eq!(answer(&body, Dialect::Anthropic).unwrap(), "答案是四十二"); + } + + #[test] + fn the_answer_is_read_from_streams_of_every_format() { + let chat = sse(&[ + ( + "", + json!({"choices": [{"index": 0, "delta": {"role": "assistant", "content": "你"}}]}), + ), + ( + "", + json!({"choices": [{"index": 0, "delta": {"content": "好"}}]}), + ), + ( + "", + json!({"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}), + ), + ]); + let mut chat = chat; + chat.extend_from_slice(b"data: [DONE]\n\n"); + assert_eq!(answer(&chat, Dialect::Chat).unwrap(), "你好"); + + let responses = sse(&[ + ( + "response.created", + json!({"type": "response.created", "response": {"id": "r"}}), + ), + ( + "response.output_item.added", + json!({"type": "response.output_item.added", "output_index": 0, "item": {"type": "message"}}), + ), + ( + "response.output_text.delta", + json!({"type": "response.output_text.delta", "output_index": 0, "content_index": 0, "delta": "构建"}), + ), + ( + "response.output_text.delta", + json!({"type": "response.output_text.delta", "output_index": 0, "content_index": 0, "delta": "成功"}), + ), + ( + "response.completed", + json!({"type": "response.completed", "response": {"usage": {"input_tokens": 1, "output_tokens": 2}}}), + ), + ]); + assert_eq!(answer(&responses, Dialect::Responses).unwrap(), "构建成功"); + + let gemini = sse(&[ + ( + "", + json!({"candidates": [{"content": {"role": "model", "parts": [{"text": "晴"}]}}]}), + ), + ( + "", + json!({"candidates": [{"content": {"role": "model", "parts": [{"text": "天"}]}, "finishReason": "STOP"}]}), + ), + ]); + assert_eq!(answer(&gemini, Dialect::Gemini).unwrap(), "晴天"); + + // 不带 alt=sse 的 Gemini 流是一个 JSON 数组 + let array = json!([ + {"candidates": [{"content": {"role": "model", "parts": [{"text": "数"}]}}]}, + {"candidates": [{"content": {"role": "model", "parts": [{"text": "组"}]}}]} + ]); + assert_eq!( + answer(array.to_string().as_bytes(), Dialect::Gemini).unwrap(), + "数组" + ); + + // Bedrock 的二进制帧在网关进门时转成了 SSE:事件名进 `event:` + let bedrock = sse(&[ + ("messageStart", json!({"role": "assistant"})), + ( + "contentBlockDelta", + json!({"contentBlockIndex": 0, "delta": {"text": "基岩"}}), + ), + ("contentBlockStop", json!({"contentBlockIndex": 0})), + ("messageStop", json!({"stopReason": "end_turn"})), + ]); + assert_eq!(answer(&bedrock, Dialect::Bedrock).unwrap(), "基岩"); + } + + #[test] + fn the_answer_is_read_from_whole_responses_of_every_format() { + let cases = [ + ( + Dialect::Anthropic, + json!({"content": [ + {"type": "thinking", "thinking": "不算"}, + {"type": "text", "text": "整包"}, + {"type": "tool_use", "id": "t", "name": "x", "input": {}}]}), + ), + ( + Dialect::Chat, + json!({"choices": [{"message": {"role": "assistant", "content": "整包"}}]}), + ), + ( + Dialect::Responses, + json!({"output": [{"type": "message", "role": "assistant", + "content": [{"type": "output_text", "text": "整包"}]}]}), + ), + ( + Dialect::Gemini, + json!({"candidates": [{"content": {"parts": [{"text": "整包"}]}}]}), + ), + ( + Dialect::Bedrock, + json!({"output": {"message": {"role": "assistant", + "content": [{"text": "整包"}]}}, "stopReason": "end_turn"}), + ), + ]; + for (d, v) in cases { + assert_eq!( + answer(v.to_string().as_bytes(), d).as_deref(), + Some("整包"), + "{d:?}" + ); + } + } + + /// 流里的 `\u` 转义也一样解开 + #[test] + fn escaped_text_in_a_stream_is_read_as_characters() { + let body = b"data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"\\u4f60\\u597d\"}}]}\n\ndata: [DONE]\n\n"; + assert_eq!(answer(body, Dialect::Chat).unwrap(), "你好"); + } + + /// 两个文字块之间另起一行:一个词不会被拼在两块的接缝上 + #[test] + fn separate_text_blocks_go_on_separate_lines() { + let body = sse(&[ + ( + "content_block_start", + json!({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}), + ), + ( + "content_block_delta", + json!({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "前一块"}}), + ), + ( + "content_block_start", + json!({"type": "content_block_start", "index": 2, "content_block": {"type": "text", "text": ""}}), + ), + ( + "content_block_delta", + json!({"type": "content_block_delta", "index": 2, "delta": {"type": "text_delta", "text": "后一块"}}), + ), + ]); + assert_eq!(answer(&body, Dialect::Anthropic).unwrap(), "前一块\n后一块"); + } + + #[test] + fn an_answer_without_text_gives_nothing() { + assert_eq!(answer(b"", Dialect::Anthropic), None); + assert_eq!( + answer(b"{\"error\":{\"message\":\"x\"}}", Dialect::Anthropic), + None + ); + assert_eq!(answer(b"{\"choices\":[", Dialect::Chat), None); + } +} diff --git a/scripts/smoke.sh b/scripts/smoke.sh index c5ffc6ec..80062cd7 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -484,6 +484,33 @@ else bad "历史里一条记录都没有" fi +# 在整份记录里找,也按正文找。**摘录不带密钥出门**:数据面那一节发过「我的 key 是 +# sk-ant-api03-SMOKEKEY…」,按正文找得到那两条,摘录是打过码的;只在密钥里出现的 +# 词找不到。正文是另一条通道异步落盘的,没落下来之前找不到,所以多等几轮 +GOT="" +for _ in $(seq 1 20); do + C=$(post /history/search '{"q":"我的 key","content":true}') + GOT=$(python3 -c 'import sys, json +raw = sys.stdin.read() +p = json.loads(raw) +hits = p.get("hits") or [] +good = (p.get("stopped") in ("end", "full") and len(hits) >= 2 + and all(h["side"] == "request" for h in hits) + and all("sk-an" in h["after"] for h in hits) and "SMOKEKEYAAAA" not in raw) +print("ok" if good else raw[:600])' < "$TMP/out" 2>&1) + [ "$C" = "200" ] && [ "$GOT" = "ok" ] && break + sleep 0.25 +done +[ "$C" = "200" ] && [ "$GOT" = "ok" ] && ok "POST /history/search 按正文找到了那两条,摘录里的密钥打了码" \ + || bad "按正文找没找对($C)" "$GOT" +C=$(post /history/search '{"q":"smokekeyaaaa","content":true}') +if [ "$C" = "200" ] && ! grep -q "SMOKEKEYAAAA" "$TMP/out" \ + && python3 -c 'import sys, json; sys.exit(0 if not json.load(sys.stdin)["hits"] else 1)' < "$TMP/out"; then + ok "只在密钥里出现的词按正文找不到" +else + bad "按密钥里的字找到了东西($C)" "$(head -c 400 "$TMP/out")" +fi + # ---------------------------------------------------------------- 诊断包 step "诊断包不带密钥出门" get /diagnostics >/dev/null From e81fcd466bf12089910e41cbb8b7708de79f94b3 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 1 Oct 2026 19:11:44 +0800 Subject: [PATCH 2/2] Search the tool calls of the answer too For coding clients the model's actual action is the tool call: an Edit with code, a Bash command. Content search now reads each tool call of the answer as its name and input text, one per line, in block order with the text: the arguments as streamed (fragments of a block joined), or as a compact JSON object for whole responses, and the raw text of freeform tools such as apply_patch. Reasoning stays out. Excerpts from tool calls are masked like the rest. Co-Authored-By: Claude Opus 5.5 --- crates/tw-api/src/lib.rs | 5 +- crates/tw-store/src/search/mod.rs | 70 +++++++ crates/tw-store/src/search/text.rs | 286 ++++++++++++++++++++++++----- 3 files changed, 314 insertions(+), 47 deletions(-) diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 45bd014c..223e65b8 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -2991,7 +2991,8 @@ pub struct HistorySearchQuery { /// 里含着 `q` 时界面交 `true`,本地应答的就都算对上 #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub local_matches: bool, - /// 也按正文找:请求里新的那一轮(最后一条用户消息,含工具结果)和回答的文字。 + /// 也按正文找:请求里新的那一轮(最后一条用户消息,含工具结果)和回答(文字,和工具 + /// 调用的名字与参数:模型跑的命令、写的代码都在这里;推理不算)。 /// 只有正文还在盘上的那些能这样找,更早的照样按上面那几样对。没有 `q` 时不起作用 #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub content: bool, @@ -3435,7 +3436,7 @@ slug_enum! { pub enum ContentSide { /// 请求里新的那一轮:最后一条用户消息,含工具结果 Request = "request", - /// 回答的文字 + /// 回答:文字,和工具调用的名字与参数(一个调用一行)。推理不算 Answer = "answer", } } diff --git a/crates/tw-store/src/search/mod.rs b/crates/tw-store/src/search/mod.rs index 649faa70..dac3d121 100644 --- a/crates/tw-store/src/search/mod.rs +++ b/crates/tw-store/src/search/mod.rs @@ -1039,6 +1039,76 @@ mod tests { assert_eq!(hit_of(&o, 1).side, ContentSide::Answer); } + /// 编程客户端那边,模型做的事是工具调用:「哪一次跑了 npm install」要找得到 —— + /// 流里的参数片段接起来找,整包回答里的参数(Chat 的写成 JSON 字符串里的 JSON)也找 + #[test] + fn the_request_where_the_model_ran_a_command_is_found_by_its_tool_call() { + let d = disk(); + let question = json!({"messages": [{"role": "user", "content": "装一下依赖"}]}).to_string(); + d.put( + &at(1, NOW, "/v1/messages"), + question.as_bytes(), + &sse(&[ + ("content_block_start", json!({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}})), + ("content_block_delta", json!({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "好的"}})), + ("content_block_start", json!({"type": "content_block_start", "index": 1, "content_block": {"type": "tool_use", "id": "t", "name": "Bash", "input": {}}})), + ("content_block_delta", json!({"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"command\": \"npm ins"}})), + ("content_block_delta", json!({"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "tall\"}"}})), + ]), + ); + d.put( + &at(2, NOW - 1, "/v1/chat/completions"), + question.as_bytes(), + json!({"choices": [{"message": {"role": "assistant", "content": null, "tool_calls": [ + {"id": "c", "type": "function", "function": {"name": "shell", "arguments": "{\"cmd\": \"npm install\"}"}}]}}]}) + .to_string() + .as_bytes(), + ); + // 只想了想、没有动手的那一条不算 + d.put( + &at(3, NOW - 2, "/v1/messages"), + question.as_bytes(), + &sse(&[ + ("content_block_start", json!({"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": ""}})), + ("content_block_delta", json!({"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "也许该跑 npm install"}})), + ]), + ); + let o = d.find("NPM install"); + assert_eq!(o.rows.iter().map(|r| r.id).collect::>(), [1, 2]); + let h = hit_of(&o, 1); + assert_eq!(h.side, ContentSide::Answer); + assert_eq!( + (h.before.as_str(), h.matched.as_str(), h.after.as_str()), + ("好的 Bash {\"command\": \"", "npm install", "\"}") + ); + let h = hit_of(&o, 2); + assert_eq!( + (h.side, h.before.as_str()), + (ContentSide::Answer, "shell {\"cmd\":\"") + ); + } + + /// 工具调用的参数里带着密钥(命令里 export 了一把):摘录照样打码,只在密钥里的词不算 + #[test] + fn a_secret_in_a_tool_call_is_masked_in_the_excerpt() { + let d = disk(); + let key = "sk-proj-TOOLKEYAAAAAAAAAAAAAAAAAAAAAAAA"; + d.put( + &at(1, NOW, "/v1/messages"), + json!({"messages": [{"role": "user", "content": "部署"}]}).to_string().as_bytes(), + &sse(&[ + ("content_block_start", json!({"type": "content_block_start", "index": 0, "content_block": {"type": "tool_use", "id": "t", "name": "Bash", "input": {}}})), + ("content_block_delta", json!({"type": "content_block_delta", "index": 0, "delta": {"type": "input_json_delta", + "partial_json": format!("{{\"command\": \"OPENAI_API_KEY={key} npm run deploy\"}}")}})), + ]), + ); + let o = d.find("npm run deploy"); + let h = hit_of(&o, 1); + assert!(!h.before.contains("TOOLKEYAAAA"), "{h:?}"); + assert!(h.before.contains("OPENAI_API_KEY=sk-pr…"), "{h:?}"); + assert!(d.find("toolkeyaaaa").rows.is_empty()); + } + /// 问和答里都有:报问里那一处 #[test] fn a_hit_in_the_request_comes_before_one_in_the_answer() { diff --git a/crates/tw-store/src/search/text.rs b/crates/tw-store/src/search/text.rs index a0a1d628..208af6d0 100644 --- a/crates/tw-store/src/search/text.rs +++ b/crates/tw-store/src/search/text.rs @@ -1,10 +1,12 @@ -//! 从存下来的正文里拆出要找的那两段文字:请求里新的那一轮、回答。 +//! 从存下来的正文里拆出要找的那两段文字:请求里新的那一轮、回答(文字和工具调用)。 //! //! **怎么读四种格式不在这里写**:请求按 tw-dialect 解成中间表示,回答按它的整包解码和 //! 流读法读 —— 网关转换格式用的就是这几样。这里只决定读哪一段。 +use std::collections::HashMap; + use serde_json::Value; -use tw_dialect::ir::{Block, Delta, Dialect, Event, Part, Role}; +use tw_dialect::ir::{Block, BlockKind, Delta, Dialect, Event, Part, Role, ToolInput}; /// 这个路径是不是生成回答的那个调用;是的话,客户端说的是哪种格式。 /// @@ -128,7 +130,14 @@ fn trim_for_reading(v: &mut Value, dialect: Dialect) { } } -/// 回答的文字,一个文字块一行。推理和工具调用不算 —— 它们不是写给人看的那部分。 +/// 回答:文字和工具调用,按出现的先后一块一行。推理不算 —— 那是模型想的,不是它说的、 +/// 做的。 +/// +/// **工具调用要算。**编程客户端那边,模型真正做的事就是工具调用:一次 Edit 带着它写的 +/// 代码,一次 Bash 带着它跑的命令,「哪一次跑了 npm install」要找得到。一个调用一行:名字、 +/// 一个空格、参数。函数工具的参数是 JSON —— 流里是模型写出来的原样(同一块的片段接在 +/// 一起);整包的回答里它已经是一个 JSON 对象,按紧凑的 JSON 写出(键按字母排)。自由格式 +/// 的工具(Codex 的 `apply_patch`)是它的原文。 /// /// `body` 是上游的原话(存的就是它):整包的 JSON、SSE 的流(Bedrock 的二进制帧在网关 /// 进门时已经转成了 SSE),或者 Gemini 不带 `alt=sse` 时那个逐步写出的 JSON 数组。按 @@ -147,8 +156,10 @@ pub fn answer(body: &[u8], upstream: Dialect) -> Option { }; let mut out = String::new(); for b in &r.blocks { - if let Block::Text(t) = b { - line(&mut out, t); + match b { + Block::Text(t) => line(&mut out, t), + Block::ToolCall(c) => line(&mut out, &call(&c.name, &input_text(&c.input))), + Block::Thinking(_) => {} } } out @@ -178,21 +189,79 @@ pub fn answer(body: &[u8], upstream: Dialect) -> Option { (!out.is_empty()).then_some(out) } -/// 流里的文字增量接起来。换了一个文字块就另起一行 +/// 整包回答里一个工具调用的参数写成文字。 +fn input_text(input: &ToolInput) -> String { + match input { + // 不是合法 JSON 的参数,tw-dialect 原样留成一个字符串(见 `ToolInput::from_json_text`): + // 照原样交出去,不再给它套一层引号和转义 + ToolInput::Json(Value::String(s)) | ToolInput::Text(s) => s.clone(), + ToolInput::Json(v) => v.to_string(), + } +} + +/// 一个工具调用的那一行:名字,有参数的话一个空格接着参数 +fn call(name: &str, input: &str) -> String { + match (name.is_empty(), input.is_empty()) { + (_, true) => name.to_string(), + (true, false) => input.to_string(), + (false, false) => format!("{name} {input}"), + } +} + +/// 流里的事件拼回一块一块:文字块接起它的文字增量,工具调用接起它的参数片段。按块第一次 +/// 出现的先后排,一块一行 fn text_of(events: Vec) -> String { - let mut out = String::new(); - let mut block = None; + enum Piece { + Text(String), + Call { name: String, input: String }, + } + let mut pieces: Vec = Vec::new(); + // 块号 → 它在 `pieces` 里的位置 + let mut at: HashMap = HashMap::new(); for e in events { - if let Event::Delta { - index, - delta: Delta::Text(t), - } = e - { - if block != Some(index) && !out.is_empty() && !out.ends_with('\n') { - out.push('\n'); + match e { + Event::BlockStart { + index, + kind: BlockKind::ToolCall { name, .. }, + } => { + at.insert(index, pieces.len()); + pieces.push(Piece::Call { + name, + input: String::new(), + }); } - block = Some(index); - out.push_str(&t); + Event::Delta { + index, + delta: Delta::Text(t), + } => match at.get(&index).and_then(|&i| pieces.get_mut(i)) { + Some(Piece::Text(s)) => s.push_str(&t), + // 文字块不一定先报开始(Bedrock 的就没有):第一段增量到了就算开了一块 + _ => { + at.insert(index, pieces.len()); + pieces.push(Piece::Text(t)); + } + }, + Event::Delta { + index, + delta: Delta::ToolInput(p), + } => match at.get(&index).and_then(|&i| pieces.get_mut(i)) { + Some(Piece::Call { input, .. }) => input.push_str(&p), + _ => { + at.insert(index, pieces.len()); + pieces.push(Piece::Call { + name: String::new(), + input: p, + }); + } + }, + _ => {} + } + } + let mut out = String::new(); + for p in pieces { + match p { + Piece::Text(t) => line(&mut out, &t), + Piece::Call { name, input } => line(&mut out, &call(&name, &input)), } } out @@ -387,8 +456,10 @@ mod tests { s.into_bytes() } + /// 文字和工具调用按出现的先后一块一行,推理不算。工具调用是名字加参数:流里的参数 + /// 片段原样接起来;开始帧里就给全了的(不再发片段)也算 #[test] - fn the_answer_of_an_anthropic_stream_is_its_text_deltas() { + fn the_answer_of_an_anthropic_stream_is_its_text_and_tool_calls() { let body = sse(&[ ( "message_start", @@ -408,32 +479,43 @@ mod tests { ), ( "content_block_delta", - json!({"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": "答案是"}}), + json!({"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": "我来装"}}), ), ("ping", json!({"type": "ping"})), ( "content_block_delta", - json!({"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": "四十二"}}), + json!({"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": "依赖"}}), ), ( "content_block_start", - json!({"type": "content_block_start", "index": 2, "content_block": {"type": "tool_use", "id": "t", "name": "Write", "input": {}}}), + json!({"type": "content_block_start", "index": 2, "content_block": {"type": "tool_use", "id": "t", "name": "Bash", "input": {}}}), ), ( "content_block_delta", - json!({"type": "content_block_delta", "index": 2, "delta": {"type": "input_json_delta", "partial_json": "{\"x\":1}"}}), + json!({"type": "content_block_delta", "index": 2, "delta": {"type": "input_json_delta", "partial_json": "{\"command\": \"npm ins"}}), + ), + ( + "content_block_delta", + json!({"type": "content_block_delta", "index": 2, "delta": {"type": "input_json_delta", "partial_json": "tall\", \"description\": \"装依赖\"}"}}), + ), + ( + "content_block_start", + json!({"type": "content_block_start", "index": 3, "content_block": {"type": "tool_use", "id": "u", "name": "Read", "input": {"path": "a.rs"}}}), ), ( "message_delta", json!({"type": "message_delta", "delta": {"stop_reason": "tool_use"}, "usage": {"output_tokens": 9}}), ), ]); - assert_eq!(answer(&body, Dialect::Anthropic).unwrap(), "答案是四十二"); + assert_eq!( + answer(&body, Dialect::Anthropic).unwrap(), + "我来装依赖\nBash {\"command\": \"npm install\", \"description\": \"装依赖\"}\nRead {\"path\":\"a.rs\"}" + ); } #[test] fn the_answer_is_read_from_streams_of_every_format() { - let chat = sse(&[ + let mut chat = sse(&[ ( "", json!({"choices": [{"index": 0, "delta": {"role": "assistant", "content": "你"}}]}), @@ -444,13 +526,31 @@ mod tests { ), ( "", - json!({"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}), + json!({"choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, "id": "call_1", + "type": "function", "function": {"name": "Bash", "arguments": ""}}]}}]}), + ), + ( + "", + json!({"choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, + "function": {"arguments": "{\"command\":"}}]}}]}), + ), + ( + "", + json!({"choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, + "function": {"arguments": "\"npm install\"}"}}]}}]}), + ), + ( + "", + json!({"choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}]}), ), ]); - let mut chat = chat; chat.extend_from_slice(b"data: [DONE]\n\n"); - assert_eq!(answer(&chat, Dialect::Chat).unwrap(), "你好"); + assert_eq!( + answer(&chat, Dialect::Chat).unwrap(), + "你好\nBash {\"command\":\"npm install\"}" + ); + // Codex:函数工具的参数是 JSON 片段,自由格式的 apply_patch 是原文片段 let responses = sse(&[ ( "response.created", @@ -468,12 +568,54 @@ mod tests { "response.output_text.delta", json!({"type": "response.output_text.delta", "output_index": 0, "content_index": 0, "delta": "成功"}), ), + ( + "response.output_item.added", + json!({"type": "response.output_item.added", "output_index": 1, "item": {"type": "reasoning"}}), + ), + ( + "response.reasoning_summary_text.delta", + json!({"type": "response.reasoning_summary_text.delta", "output_index": 1, "delta": "推理不算"}), + ), + ( + "response.output_item.added", + json!({"type": "response.output_item.added", "output_index": 2, + "item": {"type": "function_call", "call_id": "c1", "name": "shell", "arguments": ""}}), + ), + ( + "response.function_call_arguments.delta", + json!({"type": "response.function_call_arguments.delta", "output_index": 2, "delta": "{\"command\":[\"npm\","}), + ), + ( + "response.function_call_arguments.delta", + json!({"type": "response.function_call_arguments.delta", "output_index": 2, "delta": "\"install\"]}"}), + ), + ( + "response.output_item.done", + json!({"type": "response.output_item.done", "output_index": 2, + "item": {"type": "function_call", "call_id": "c1", "name": "shell", "arguments": "{\"command\":[\"npm\",\"install\"]}"}}), + ), + ( + "response.output_item.added", + json!({"type": "response.output_item.added", "output_index": 3, + "item": {"type": "custom_tool_call", "call_id": "c2", "name": "apply_patch", "input": ""}}), + ), + ( + "response.custom_tool_call_input.delta", + json!({"type": "response.custom_tool_call_input.delta", "output_index": 3, "delta": "*** Begin Patch\n"}), + ), + ( + "response.custom_tool_call_input.delta", + json!({"type": "response.custom_tool_call_input.delta", "output_index": 3, "delta": "*** End Patch"}), + ), ( "response.completed", json!({"type": "response.completed", "response": {"usage": {"input_tokens": 1, "output_tokens": 2}}}), ), ]); - assert_eq!(answer(&responses, Dialect::Responses).unwrap(), "构建成功"); + assert_eq!( + answer(&responses, Dialect::Responses).unwrap(), + "构建成功\nshell {\"command\":[\"npm\",\"install\"]}\napply_patch *** Begin Patch\n*** End Patch" + ); let gemini = sse(&[ ( @@ -482,19 +624,25 @@ mod tests { ), ( "", - json!({"candidates": [{"content": {"role": "model", "parts": [{"text": "天"}]}, "finishReason": "STOP"}]}), + json!({"candidates": [{"content": {"role": "model", "parts": [{"text": "天"}, + {"functionCall": {"name": "run_shell_command", "args": {"command": "npm install"}}}]}, + "finishReason": "STOP"}]}), ), ]); - assert_eq!(answer(&gemini, Dialect::Gemini).unwrap(), "晴天"); + assert_eq!( + answer(&gemini, Dialect::Gemini).unwrap(), + "晴天\nrun_shell_command {\"command\":\"npm install\"}" + ); // 不带 alt=sse 的 Gemini 流是一个 JSON 数组 let array = json!([ {"candidates": [{"content": {"role": "model", "parts": [{"text": "数"}]}}]}, - {"candidates": [{"content": {"role": "model", "parts": [{"text": "组"}]}}]} + {"candidates": [{"content": {"role": "model", "parts": [{"text": "组"}, + {"functionCall": {"name": "run_shell_command", "args": {"command": "npm install"}}}]}}]} ]); assert_eq!( answer(array.to_string().as_bytes(), Dialect::Gemini).unwrap(), - "数组" + "数组\nrun_shell_command {\"command\":\"npm install\"}" ); // Bedrock 的二进制帧在网关进门时转成了 SSE:事件名进 `event:` @@ -505,49 +653,97 @@ mod tests { json!({"contentBlockIndex": 0, "delta": {"text": "基岩"}}), ), ("contentBlockStop", json!({"contentBlockIndex": 0})), - ("messageStop", json!({"stopReason": "end_turn"})), + ( + "contentBlockStart", + json!({"contentBlockIndex": 1, "start": {"toolUse": {"toolUseId": "t1", "name": "Bash"}}}), + ), + ( + "contentBlockDelta", + json!({"contentBlockIndex": 1, "delta": {"toolUse": {"input": "{\"command\":"}}}), + ), + ( + "contentBlockDelta", + json!({"contentBlockIndex": 1, "delta": {"toolUse": {"input": "\"npm install\"}"}}}), + ), + ("contentBlockStop", json!({"contentBlockIndex": 1})), + ("messageStop", json!({"stopReason": "tool_use"})), ]); - assert_eq!(answer(&bedrock, Dialect::Bedrock).unwrap(), "基岩"); + assert_eq!( + answer(&bedrock, Dialect::Bedrock).unwrap(), + "基岩\nBash {\"command\":\"npm install\"}" + ); } + /// 整包的回答:工具调用的参数已经是 JSON 对象,按紧凑的 JSON 写出;自由格式的是原文 #[test] fn the_answer_is_read_from_whole_responses_of_every_format() { + let bash = "Bash {\"command\":\"npm install\"}"; let cases = [ ( Dialect::Anthropic, json!({"content": [ - {"type": "thinking", "thinking": "不算"}, - {"type": "text", "text": "整包"}, - {"type": "tool_use", "id": "t", "name": "x", "input": {}}]}), + {"type": "thinking", "thinking": "推理不算"}, + {"type": "text", "text": "整包"}, + {"type": "tool_use", "id": "t", "name": "Bash", + "input": {"command": "npm install", "description": "装依赖"}}]}), + "整包\nBash {\"command\":\"npm install\",\"description\":\"装依赖\"}".to_string(), ), ( Dialect::Chat, - json!({"choices": [{"message": {"role": "assistant", "content": "整包"}}]}), + json!({"choices": [{"message": {"role": "assistant", "content": "整包", + "reasoning_content": "推理不算", + "tool_calls": [{"id": "c", "type": "function", + "function": {"name": "Bash", "arguments": "{\"command\": \"npm install\"}"}}]}}]}), + format!("整包\n{bash}"), ), ( Dialect::Responses, - json!({"output": [{"type": "message", "role": "assistant", - "content": [{"type": "output_text", "text": "整包"}]}]}), + json!({"output": [ + {"type": "reasoning", "summary": [{"type": "summary_text", "text": "推理不算"}]}, + {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "整包"}]}, + {"type": "function_call", "call_id": "c1", "name": "Bash", "arguments": "{\"command\":\"npm install\"}"}, + {"type": "custom_tool_call", "call_id": "c2", "name": "apply_patch", "input": "*** Begin Patch"}]}), + format!("整包\n{bash}\napply_patch *** Begin Patch"), ), ( Dialect::Gemini, - json!({"candidates": [{"content": {"parts": [{"text": "整包"}]}}]}), + json!({"candidates": [{"content": {"parts": [ + {"text": "推理不算", "thought": true}, + {"text": "整包"}, + {"functionCall": {"name": "Bash", "args": {"command": "npm install"}}}]}}]}), + format!("整包\n{bash}"), ), ( Dialect::Bedrock, - json!({"output": {"message": {"role": "assistant", - "content": [{"text": "整包"}]}}, "stopReason": "end_turn"}), + json!({"output": {"message": {"role": "assistant", "content": [ + {"reasoningContent": {"reasoningText": {"text": "推理不算"}}}, + {"text": "整包"}, + {"toolUse": {"toolUseId": "t", "name": "Bash", "input": {"command": "npm install"}}}]}}, + "stopReason": "tool_use"}), + format!("整包\n{bash}"), ), ]; - for (d, v) in cases { + for (d, v, want) in cases { assert_eq!( answer(v.to_string().as_bytes(), d).as_deref(), - Some("整包"), + Some(want.as_str()), "{d:?}" ); } } + /// 不是合法 JSON 的参数照模型写的原样,不套引号和转义;只有工具调用的回答也有字 + #[test] + fn tool_arguments_that_are_not_json_stay_as_written() { + let v = json!({"choices": [{"message": {"role": "assistant", "content": null, + "tool_calls": [{"id": "c", "type": "function", + "function": {"name": "Bash", "arguments": "npm install --save"}}]}}]}); + assert_eq!( + answer(v.to_string().as_bytes(), Dialect::Chat).as_deref(), + Some("Bash npm install --save") + ); + } + /// 流里的 `\u` 转义也一样解开 #[test] fn escaped_text_in_a_stream_is_read_as_characters() {