From 75c62a2b727f3c55913e74efa595d6b7fd9ecb4d Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Fri, 25 Sep 2026 11:09:44 +0800 Subject: [PATCH] feat(stats): per-group missing-money counts and security log totals /summary/buckets/by: every CostBucketGroup now carries unpriced_requests and no_usage_requests, counted with the same NO_PRICE / NO_USAGE conditions as CostBucket and CostGroup, for every dim (model, provider, client). A group whose cost is 0 can now be told apart as "no price", "no usage" or genuinely free, and the groups of a bucket add up to that bucket's own counts. GET /security/events: SecurityEventsPage gains `total` (every event that matches the guard and time window, not just this page) and `by_outcome` (SecurityOutcomeCounts: recorded / replaced / cut / blocked, all four always present; they add up to `total`). The page and the count share one WHERE clause (SECURITY_FILTER); `before` is a cursor, not a filter, so every page of the same window reports the same total. `more` stays. Db::security_events now returns the whole tw_api::SecurityEventsPage. Co-Authored-By: Claude Opus 5.5 --- crates/tw-api/src/lib.rs | 32 ++- crates/tw-control/src/security.rs | 4 +- crates/tw-control/tests/security.rs | 59 ++++- crates/tw-control/tests/summary.rs | 147 +++++++++++++ crates/tw-store/src/db.rs | 325 +++++++++++++++++++++++++++- crates/tw-store/src/recorder.rs | 16 +- 6 files changed, 562 insertions(+), 21 deletions(-) create mode 100644 crates/tw-control/tests/summary.rs diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 8dc406e7..5b123bc0 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -2647,12 +2647,20 @@ pub struct CostBucket { #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct CostBucketGroup { pub at_ms: i64, - /// 模型名或上游名,看查的是哪一维 + /// 模型名、上游名或密钥名,看查的是哪一维 pub name: String, pub requests: i64, pub failed: i64, pub cost_micros_exact: i64, pub cost_micros_estimated: i64, + /// 这一格里这一项有几条请求的模型不在价目表里(用量是有的),见 + /// `Summary::unpriced_requests`。 + /// + /// **每一项自己带着。**这一项的金额是 0 时,要分得清「没有价格」和「确实 + /// 没花钱」—— 只有整格的数的话,说不出缺着钱的是哪一项。 + pub unpriced_requests: i64, + /// 这一格里这一项有几条请求没有拿到用量,见 `Summary::no_usage_requests` + pub no_usage_requests: i64, /// 这一格里这一项用掉的 token。 /// /// **四类分开给。**它们的单价差十倍以上,加成一个数之后既算不回 @@ -3596,6 +3604,28 @@ pub struct SecurityEventView { pub struct SecurityEventsPage { pub events: Vec, pub more: bool, + /// 这一段时间里、按这一项筛出来的一共几条 —— **整段的,不只是这一页**。 + /// + /// `before` 是翻页的位置,不是筛选:翻到第几页,这个数都一样。页头的 + /// 「N 次命中」是它;拿读到的条数去数,读满一页就只能写「100+」 + pub total: i64, + /// `total` 里各做了什么。四项加起来就是 `total` + pub by_outcome: SecurityOutcomeCounts, +} + +/// 一段安全日志里,每一种做法各几条(见 [`SecurityOutcome`])。没有的是 0, +/// 四项都在。 +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct SecurityOutcomeCounts { + /// 只记录 + pub recorded: i64, + /// 已替换成占位符 + pub replaced: i64, + /// 已切断 + pub cut: i64, + /// 请求被拒,没有发出去 + pub blocked: i64, } /// 一条内置规则按什么认。**给界面说明用**,界面按类型写成自己的话。 diff --git a/crates/tw-control/src/security.rs b/crates/tw-control/src/security.rs index a62ddb3a..ae914d92 100644 --- a/crates/tw-control/src/security.rs +++ b/crates/tw-control/src/security.rs @@ -346,7 +346,7 @@ async fn events( let g = store.lock().await; // **缺省是「全部」,不是「今天」。**这是一张列表,「最近 N 条」本身就是 // 一个完整的回答 - let (events, more) = g + let page = g .db() .security_events( guard, @@ -356,7 +356,7 @@ async fn events( q.limit.unwrap_or(100).clamp(1, PAGE_MAX), ) .map_err(crate::records)?; - Ok(Json(tw_api::SecurityEventsPage { events, more })) + Ok(Json(page)) } // ---------------------------------------------------------------- 写 diff --git a/crates/tw-control/tests/security.rs b/crates/tw-control/tests/security.rs index 49b7c66f..eb709844 100644 --- a/crates/tw-control/tests/security.rs +++ b/crates/tw-control/tests/security.rs @@ -649,6 +649,12 @@ async fn the_log_pages_backwards_and_names_the_upstream_that_served_the_request( let events = v["events"].as_array().unwrap(); assert_eq!(events.len(), 2); assert_eq!(v["more"], true); + // 页头的数是整段的,不是这一页的 + assert_eq!(v["total"], 3, "{v}"); + assert_eq!( + v["by_outcome"], + json!({ "recorded": 1, "replaced": 1, "cut": 1, "blocked": 0 }) + ); assert_eq!(events[0]["rule"], "jwt", "倒序:新的在前"); assert_eq!(events[0]["provider"], "首选"); assert_eq!( @@ -675,8 +681,9 @@ async fn the_log_pages_backwards_and_names_the_upstream_that_served_the_request( .await; assert_eq!(v["events"].as_array().unwrap().len(), 1); assert_eq!(v["more"], false); + assert_eq!(v["total"], 3, "翻页不是筛选,总数不该变:{v}"); - // 按类型、按时间段筛 + // 按类型、按时间段筛:总数跟着一起筛 let (_, v) = call( &b.app, "GET", @@ -687,6 +694,11 @@ async fn the_log_pages_backwards_and_names_the_upstream_that_served_the_request( let only = v["events"].as_array().unwrap(); assert_eq!(only.len(), 1, "{v}"); assert_eq!(only[0]["rule"], "jwt"); + assert_eq!(v["total"], 1); + assert_eq!( + v["by_outcome"], + json!({ "recorded": 0, "replaced": 1, "cut": 0, "blocked": 0 }) + ); // 概览上的计数和日志数的是同一批 let (_, v) = call( @@ -708,6 +720,51 @@ async fn the_log_pages_backwards_and_names_the_upstream_that_served_the_request( assert_eq!(v[0]["security"].as_array().unwrap().len(), 2, "{v}"); } +/// 比一页多的时候,页头照样说得出一共几条(以前只能写「100+」);一条都 +/// 没有的一段,四项都在、都是 0。 +#[tokio::test] +async fn the_log_counts_past_one_page_and_an_empty_window_counts_zero() { + let b = bed_with(BASE, |db| { + for i in 0..150 { + let (guard, action) = match i % 3 { + 0 => ("redact", "recorded"), + 1 => ("redact", "replaced"), + _ => ("inspect_tools", "cut"), + }; + db.insert_security_event(&event(i, 1_000 + i, guard, "r", action)) + .unwrap(); + } + }); + // 不给条数是一页 100 条 + let (st, v) = call(&b.app, "GET", "/security/events", serde_json::Value::Null).await; + assert_eq!(st, StatusCode::OK, "{v}"); + assert_eq!(v["events"].as_array().unwrap().len(), 100); + assert_eq!(v["more"], true); + assert_eq!(v["total"], 150); + assert_eq!( + v["by_outcome"], + json!({ "recorded": 50, "replaced": 50, "cut": 50, "blocked": 0 }) + ); + + let (st, v) = call( + &b.app, + "GET", + "/security/events?from_ms=5000&to_ms=6000", + serde_json::Value::Null, + ) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + assert_eq!( + v, + json!({ + "events": [], + "more": false, + "total": 0, + "by_outcome": { "recorded": 0, "replaced": 0, "cut": 0, "blocked": 0 }, + }) + ); +} + // ─────────────────────────────────────────────────────────── 藏匿字符、内容过滤、输出长度 #[tokio::test] diff --git a/crates/tw-control/tests/summary.rs b/crates/tw-control/tests/summary.rs new file mode 100644 index 00000000..fc530ebe --- /dev/null +++ b/crates/tw-control/tests/summary.rs @@ -0,0 +1,147 @@ +//! 汇总端点的形状。 +//! +//! 各种请求怎么数在 tw-store 里测;这里盯的是**界面拿到的那份 JSON**:按模型 +//! 分层的趋势图上,每一格的每一项都要自己说出缺着多少钱。 + +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"; + +/// 一条有用量、有价格的请求。 +fn req(id: i64, model: &str) -> tw_store::db::RequestRow { + tw_store::db::RequestRow { + key_masked: None, + peer: None, + id, + at_ms: 1000 + id, + client: "我".into(), + client_hint: None, + session: None, + provider: "官方".into(), + model: model.into(), + path: "/v1/messages".into(), + status: Some(200), + ttfb_ms: Some(100), + duration_ms: Some(200), + 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, + } +} + +fn app(rows: &[tw_store::db::RequestRow]) -> (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(); + for r in rows { + db.insert(r).unwrap(); + } + let rec = tw_store::Recorder::new( + db, + tw_store::Blobs::new(d.path().join("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 get(app: &axum::Router, path: &str) -> serde_json::Value { + let r = app + .clone() + .oneshot(Request::builder().uri(path).body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(r.status(), StatusCode::OK, "{path}"); + let b = axum::body::to_bytes(r.into_body(), 1 << 20).await.unwrap(); + serde_json::from_slice(&b).unwrap() +} + +/// 趋势图的每一格、每一项都带着「没有价格」和「没有用量」的条数。 +/// +/// 金额是 0 的那一项,界面要分得清是价目表里没有它、上游没报用量,还是确实 +/// 没花钱 —— 以前只有整格的数,只能笼统地说「这一格少算了」。 +#[tokio::test] +async fn every_group_in_the_trend_says_how_much_of_its_money_is_missing() { + let mut unknown = req(2, "中转站自己起的名字"); + unknown.cost_micros = None; + let mut silent = req(3, "claude-sonnet-4-5"); + silent.input_tokens = None; + silent.output_tokens = None; + silent.cost_micros = None; + let (_d, app) = app(&[req(1, "claude-sonnet-4-5"), unknown, silent]); + + let v = get( + &app, + "/summary/buckets/by?from_ms=0&to_ms=10000&bucket_ms=10000&dim=model", + ) + .await; + let groups = v.as_array().unwrap(); + assert_eq!(groups.len(), 2, "{v}"); + let group = |name: &str| { + groups + .iter() + .find(|g| g["name"] == name) + .unwrap_or_else(|| panic!("没有「{name}」这一项:{v}")) + }; + let sonnet = group("claude-sonnet-4-5"); + assert_eq!(sonnet["requests"], 2); + assert_eq!(sonnet["cost_micros_exact"], 1_000); + assert_eq!(sonnet["unpriced_requests"], 0, "{sonnet}"); + assert_eq!(sonnet["no_usage_requests"], 1, "{sonnet}"); + // 金额是 0,但不是免费的:价目表里没有它 + let unknown = group("中转站自己起的名字"); + assert_eq!(unknown["cost_micros_exact"], 0); + assert_eq!(unknown["unpriced_requests"], 1, "{unknown}"); + assert_eq!(unknown["no_usage_requests"], 0, "{unknown}"); + + // 按上游、按密钥分也一样带着;这三条同一家、同一把,合成一项 + for dim in ["provider", "client"] { + let v = get( + &app, + &format!("/summary/buckets/by?from_ms=0&to_ms=10000&bucket_ms=10000&dim={dim}"), + ) + .await; + assert_eq!(v.as_array().unwrap().len(), 1, "{dim}: {v}"); + assert_eq!(v[0]["unpriced_requests"], 1, "{dim}: {v}"); + assert_eq!(v[0]["no_usage_requests"], 1, "{dim}: {v}"); + } + + // 一条都没有的一段:没有组 + let v = get( + &app, + "/summary/buckets/by?from_ms=20000&to_ms=30000&bucket_ms=10000&dim=model", + ) + .await; + assert_eq!(v, serde_json::json!([])); +} diff --git a/crates/tw-store/src/db.rs b/crates/tw-store/src/db.rs index 96bcf29a..58a33e5c 100644 --- a/crates/tw-store/src/db.rs +++ b/crates/tw-store/src/db.rs @@ -712,11 +712,14 @@ impl Db { Ok(()) } - /// 安全日志的一页,按时间倒序。 + /// 安全日志的一页,按时间倒序,连同这一段一共几条、各做了什么。 /// /// 上游、密钥和模型**尽量取请求那一行的**:记录发生在请求发出之前,那时 /// 知道的只是首选的上游,而故障转移之后真正服务它的是另一家。请求还没 /// 落库时退回记录自己的。 + /// + /// **总数和这一页用同一句筛选**([`SECURITY_FILTER`]):页头的「一共几条」 + /// 和往下翻能翻出来的是同一批。`before_id` 只管翻到哪儿,不进总数。 pub fn security_events( &self, guard: Option<&str>, @@ -724,11 +727,10 @@ impl Db { until_ms: i64, before_id: Option, limit: usize, - ) -> Result<(Vec, bool), DbError> { + ) -> Result { let mut st = self.conn.prepare(&format!( "{SECURITY_SELECT} - WHERE e.at_ms >= ?1 AND e.at_ms < ?2 - AND (?3 IS NULL OR e.guard = ?3) + WHERE {SECURITY_FILTER} AND (?4 IS NULL OR e.id < ?4) ORDER BY e.id DESC LIMIT ?5" @@ -737,10 +739,39 @@ impl Db { params![since_ms, until_ms, guard, before_id, limit as i64 + 1], security_view, )?; - let mut out = rows.collect::, _>>()?; - let more = out.len() > limit; - out.truncate(limit); - Ok((out, more)) + let mut events = rows.collect::, _>>()?; + let more = events.len() > limit; + events.truncate(limit); + + let mut st = self.conn.prepare(&format!( + "SELECT e.action, COUNT(*) FROM security_events e + WHERE {SECURITY_FILTER} + GROUP BY e.action" + ))?; + let rows = st.query_map(params![since_ms, until_ms, guard], |r| { + Ok(( + slug_col(r, 0, tw_api::SecurityOutcome::from_slug)?, + r.get::<_, i64>(1)?, + )) + })?; + let mut by = tw_api::SecurityOutcomeCounts::default(); + for row in rows { + let (outcome, n) = row?; + // 逐个列出来:多一种做法时这里编译不过,而不是悄悄少数一种 + let slot = match outcome { + tw_api::SecurityOutcome::Recorded => &mut by.recorded, + tw_api::SecurityOutcome::Replaced => &mut by.replaced, + tw_api::SecurityOutcome::Cut => &mut by.cut, + tw_api::SecurityOutcome::Blocked => &mut by.blocked, + }; + *slot = n; + } + Ok(tw_api::SecurityEventsPage { + events, + more, + total: by.recorded + by.replaced + by.cut + by.blocked, + by_outcome: by, + }) } /// 请求号落在 `[from, to]` 里的那些请求的安全记录,按请求号分好。 @@ -911,12 +942,16 @@ impl Db { tw_api::CostDim::Provider => "provider", tw_api::CostDim::Client => "client", }; + // 缺着钱的两种和 `cost_buckets` 用同一对条件:每一格里各项加起来, + // 就是那一格自己的数 let sql = format!( "SELECT ((at_ms - ?1) / ?3) AS b, {col}, COUNT(*), SUM(CASE WHEN error IS NOT NULL THEN 1 ELSE 0 END), COALESCE(SUM(CASE WHEN cost_estimated = 0 THEN cost_micros ELSE 0 END), 0), COALESCE(SUM(CASE WHEN cost_estimated = 1 THEN cost_micros ELSE 0 END), 0), + COALESCE(SUM({NO_PRICE}), 0), + COALESCE(SUM({NO_USAGE}), 0), COALESCE(SUM(input_tokens), 0), COALESCE(SUM(output_tokens), 0), COALESCE(SUM(cache_read_tokens), 0), @@ -934,10 +969,12 @@ impl Db { failed: r.get(3)?, cost_micros_exact: r.get(4)?, cost_micros_estimated: r.get(5)?, - input_tokens: r.get(6)?, - output_tokens: r.get(7)?, - cache_read_tokens: r.get(8)?, - cache_write_tokens: r.get(9)?, + unpriced_requests: r.get(6)?, + no_usage_requests: r.get(7)?, + input_tokens: r.get(8)?, + output_tokens: r.get(9)?, + cache_read_tokens: r.get(10)?, + cache_write_tokens: r.get(11)?, }) })?; rows.collect::, _>>().map_err(Into::into) @@ -1112,6 +1149,13 @@ const SECURITY_SELECT: &str = r.client_hint, r.peer, r.key_masked FROM security_events e LEFT JOIN requests r ON r.id = e.request_id"; +/// 安全日志按什么筛:`?1`–`?2` 这一段时间,`?3` 这一项(NULL 是全部)。 +/// +/// **读一页和数总数用的是这一句**,两句 SQL 各写一份条件的话,迟早有一边多 +/// 一个少一个,页头的数就和列表对不上了。只看 `e` 的列:连上请求那一行不会 +/// 多出或少掉一条记录。 +const SECURITY_FILTER: &str = "e.at_ms >= ?1 AND e.at_ms < ?2 AND (?3 IS NULL OR e.guard = ?3)"; + /// 存成词的一列读回契约里的枚举。不认得的词是这一行坏了 fn slug_col( r: &rusqlite::Row, @@ -1863,6 +1907,10 @@ mod cost_state_tests { assert_eq!((b[0].unpriced_requests, b[0].no_usage_requests), (0, 3)); let g = db.cost_by(tw_api::CostDim::Model, 0, 1000).unwrap(); assert_eq!((g[0].unpriced_requests, g[0].no_usage_requests), (0, 3)); + let bg = db + .cost_buckets_by(tw_api::CostDim::Model, 0, 1000, 1000) + .unwrap(); + assert_eq!((bg[0].unpriced_requests, bg[0].no_usage_requests), (0, 3)); } /// **钱缺着的只有按量计费的那些。**不计费的,没有用量也好、模型不在价目表 @@ -1896,9 +1944,128 @@ mod cost_state_tests { ), (1, 1) ); + let bg = db + .cost_buckets_by(tw_api::CostDim::Model, 0, 1000, 1000) + .unwrap(); + assert_eq!( + ( + bg.iter().map(|g| g.unpriced_requests).sum::(), + bg.iter().map(|g| g.no_usage_requests).sum::() + ), + (1, 1) + ); assert_eq!(db.unpriced_recent(365_000).unwrap().0, 1); } + /// 分组的每一格**自己说缺着多少钱**,三个维度都是。 + /// + /// 概览按模型分层的图上,一个模型那一格的金额是 0:没有价格、没有用量、 + /// 还是确实不花钱,是三句不同的话。只有整格的数的话,说得出这一格缺着 + /// 钱,说不出缺在哪个模型上。 + #[test] + fn every_group_in_a_bucket_says_how_much_of_its_money_is_missing() { + use std::collections::BTreeMap; + use tw_api::CostDim; + + let db = Db::in_memory().unwrap(); + let hour = 3_600_000i64; + let t0 = 1_000_000_000i64; + // (模型, 上游, 密钥) 每一行各不相同地交叉开,三个维度分出来的组都不一样 + let set = |mut r: RequestRow, model: &str, provider: &str, client: &str| { + r.model = model.into(); + r.provider = provider.into(); + r.client = client.into(); + r + }; + let mut free = unknown_model(7, t0 + hour + 3); + free.billing = tw_api::Billing::Free; + for r in [ + // 第 0 格 + set(row(1, t0 + 1), "opus", "官方", "alice"), + set(unknown_model(2, t0 + 2), "自起名", "中转", "alice"), + set(without_usage(3, t0 + 3), "opus", "中转", "bob"), + set(failed_before_usage(4, t0 + 4), "opus", "官方", "bob"), + // 第 1 格 + set(unknown_model(5, t0 + hour + 1), "自起名", "官方", "bob"), + set(without_usage(6, t0 + hour + 2), "opus", "官方", "alice"), + // 不计费的:模型不在价目表里也不缺钱,这一组是真的 $0 + set(free, "自起名", "中转", "bob"), + ] { + db.insert(&r).unwrap(); + } + + let missing = |dim| { + db.cost_buckets_by(dim, t0, t0 + 2 * hour, hour) + .unwrap() + .into_iter() + .map(|g| { + ( + ((g.at_ms - t0) / hour, g.name), + (g.unpriced_requests, g.no_usage_requests), + ) + }) + .collect::>() + }; + let want = |xs: [(i64, &str, (i64, i64)); 4]| { + xs.into_iter() + .map(|(b, name, n)| ((b, name.to_string()), n)) + .collect::>() + }; + assert_eq!( + missing(CostDim::Model), + want([ + (0, "opus", (0, 1)), + (0, "自起名", (1, 0)), + (1, "opus", (0, 1)), + (1, "自起名", (1, 0)), + ]) + ); + assert_eq!( + missing(CostDim::Provider), + want([ + (0, "官方", (0, 0)), + (0, "中转", (1, 1)), + (1, "官方", (1, 1)), + (1, "中转", (0, 0)), + ]) + ); + assert_eq!( + missing(CostDim::Client), + want([ + (0, "alice", (1, 0)), + (0, "bob", (0, 1)), + (1, "alice", (0, 1)), + (1, "bob", (1, 0)), + ]) + ); + + // 每一格里各组加起来,就是不分组那一格自己的数 + let plain = db.cost_buckets(t0, t0 + 2 * hour, hour).unwrap(); + assert_eq!(plain.len(), 2); + for dim in [CostDim::Model, CostDim::Provider, CostDim::Client] { + let by = db.cost_buckets_by(dim, t0, t0 + 2 * hour, hour).unwrap(); + for b in &plain { + let here = by.iter().filter(|g| g.at_ms == b.at_ms); + let sum = here.fold((0, 0), |(p, u), g| { + (p + g.unpriced_requests, u + g.no_usage_requests) + }); + assert_eq!( + sum, + (b.unpriced_requests, b.no_usage_requests), + "{dim:?} 在 {} 这一格加起来和不分组的对不上", + b.at_ms + ); + } + } + + // 一条都没有的一段:没有组,不是一组零 + assert!( + db.cost_buckets_by(CostDim::Model, t0 + 5 * hour, t0 + 6 * hour, hour) + .unwrap() + .is_empty() + ); + } + /// 价格页只列**配一个价格就能解决**的模型。列出一个失败了的、或者 /// 上游没报用量的模型,用户照做了,那几行也还是算不出钱。 #[test] @@ -1976,3 +2143,137 @@ mod cost_state_tests { ); } } + +#[cfg(test)] +mod security_log_tests { + use super::*; + use tw_api::{Guard, SecurityOutcome, SecurityOutcomeCounts}; + + fn event(at_ms: i64, guard: Guard, action: SecurityOutcome) -> SecurityEvent { + SecurityEvent { + at_ms, + request_id: at_ms, + guard, + rule: "r".into(), + custom: false, + action, + provider: "官方".into(), + client: "default".into(), + tool: None, + excerpt: "…".into(), + count: 1, + } + } + + /// 九条,时刻 1–9,号也是 1–9。只记录 3 条、已替换 1 条、已切断 3 条、 + /// 被拒 2 条 + fn seeded() -> Db { + let db = Db::in_memory().unwrap(); + for (at, guard, action) in [ + (1, Guard::Redact, SecurityOutcome::Recorded), + (2, Guard::Redact, SecurityOutcome::Replaced), + (3, Guard::InspectTools, SecurityOutcome::Cut), + (4, Guard::Redact, SecurityOutcome::Recorded), + (5, Guard::HiddenText, SecurityOutcome::Blocked), + (6, Guard::Content, SecurityOutcome::Recorded), + (7, Guard::InspectTools, SecurityOutcome::Cut), + (8, Guard::Content, SecurityOutcome::Blocked), + (9, Guard::OutputLimit, SecurityOutcome::Cut), + ] { + db.insert_security_event(&event(at, guard, action)).unwrap(); + } + db + } + + fn ids(p: &tw_api::SecurityEventsPage) -> Vec { + p.events.iter().map(|e| e.id).collect() + } + + /// 页头的数是**整段的**。以前只能拿读到的条数去数,读满一页就只能写 + /// 「100+」。往下翻页也不变:`before` 是翻到哪儿,不是筛选。 + #[test] + fn the_total_counts_the_whole_window_not_just_the_page() { + let db = seeded(); + let all = SecurityOutcomeCounts { + recorded: 3, + replaced: 1, + cut: 3, + blocked: 2, + }; + + let p = db.security_events(None, 0, i64::MAX, None, 4).unwrap(); + assert_eq!(ids(&p), vec![9, 8, 7, 6]); + assert!(p.more); + assert_eq!(p.total, 9, "数的是这一页,不是这一段"); + assert_eq!(p.by_outcome, all); + + let p = db.security_events(None, 0, i64::MAX, Some(6), 4).unwrap(); + assert_eq!(ids(&p), vec![5, 4, 3, 2]); + assert!(p.more); + assert_eq!((p.total, &p.by_outcome), (9, &all), "翻到第二页,总数变了"); + + let p = db.security_events(None, 0, i64::MAX, Some(2), 4).unwrap(); + assert_eq!(ids(&p), vec![1]); + assert!(!p.more); + assert_eq!((p.total, &p.by_outcome), (9, &all)); + } + + /// **总数就是一页一页翻到底翻得出来的那些**,按哪一项、哪一段筛都一样: + /// 两句 SQL 用的是同一句筛选。 + #[test] + fn the_total_is_what_paging_to_the_end_yields_under_every_filter() { + let db = seeded(); + for (guard, since, until) in [ + (None, 0, i64::MAX), + (Some("redact"), 0, i64::MAX), + (None, 3, 7), + (Some("inspect_tools"), 0, 8), + (Some("content"), 7, 100), + // 输出长度那条在 9,终点不含:一条都没有 + (Some("output_limit"), 0, 9), + ] { + let first = db.security_events(guard, since, until, None, 2).unwrap(); + let mut seen = first.events.clone(); + let mut last = first.clone(); + while last.more { + let before = last.events.last().unwrap().id; + last = db + .security_events(guard, since, until, Some(before), 2) + .unwrap(); + assert_eq!( + (last.total, &last.by_outcome), + (first.total, &first.by_outcome), + "{guard:?} {since}..{until}:翻页之后总数变了" + ); + seen.extend(last.events.iter().cloned()); + } + let mut counted = SecurityOutcomeCounts::default(); + for e in &seen { + match e.action { + SecurityOutcome::Recorded => counted.recorded += 1, + SecurityOutcome::Replaced => counted.replaced += 1, + SecurityOutcome::Cut => counted.cut += 1, + SecurityOutcome::Blocked => counted.blocked += 1, + } + } + assert_eq!( + first.total, + seen.len() as i64, + "{guard:?} {since}..{until}:总数和翻得出来的条数对不上" + ); + assert_eq!(first.by_outcome, counted, "{guard:?} {since}..{until}"); + } + } + + /// 一条都没有:零条,四项都在、都是 0。 + #[test] + fn an_empty_window_counts_zero_of_everything() { + for db in [Db::in_memory().unwrap(), seeded()] { + let p = db.security_events(None, 100, 200, None, 10).unwrap(); + assert!(p.events.is_empty()); + assert!(!p.more); + assert_eq!(p.total, 0); + assert_eq!(p.by_outcome, SecurityOutcomeCounts::default()); + } + } +} diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index 6b914fd6..4e95f725 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -1383,8 +1383,9 @@ mod security_tests { r.on_event(&started(1, "claude-sonnet-4-5")); r.on_event(&secrets(replaced)); r.on_event(&finished(1, None)); - let (got, more) = r.db().security_events(None, 0, i64::MAX, None, 10).unwrap(); - assert!(!more); + let page = r.db().security_events(None, 0, i64::MAX, None, 10).unwrap(); + assert!(!page.more); + let got = page.events; assert_eq!(got.len(), 2, "{got:?}"); assert!( got.iter() @@ -1418,10 +1419,11 @@ mod security_tests { blocked: true, at_ms: 20, }); - let (got, _) = r + let got = r .db() .security_events(Some("inspect_tools"), 0, i64::MAX, None, 10) - .unwrap(); + .unwrap() + .events; assert_eq!(got.len(), 1, "{got:?}"); assert_eq!(got[0].action, tw_api::SecurityOutcome::Cut); assert_eq!(got[0].tool.as_deref(), Some("Bash")); @@ -1472,7 +1474,11 @@ mod security_tests { cut: true, at_ms: 32, }); - let (got, _) = r.db().security_events(None, 0, i64::MAX, None, 10).unwrap(); + let got = r + .db() + .security_events(None, 0, i64::MAX, None, 10) + .unwrap() + .events; assert_eq!(got.len(), 3, "{got:?}"); let [limit, content, hidden] = &got[..] else { unreachable!()