From 7999f6019b4d84b88b68a5ec8e6bc753f7e0c348 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Wed, 16 Sep 2026 11:20:06 +0800 Subject: [PATCH] feat: token volume per bucket, and the two security counts a window can report MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three additions the overview needs. **Grouped cost buckets carry token volume too.** The overview's trend chart is about to become switchable between money and usage, and those two have different shapes: one opus burst dominates a cost chart and flattens the week around it, while in token terms the same burst sits in proportion. All four token classes are returned separately — their unit prices differ by more than tenfold, so a single sum neither adds back up to the money nor says whether the time was spent writing new context or reading cache. **Redactions are recorded.** They were deliberately dropped before, as "request detail, not another row" — except the detail was not stored either. The consequence only shows up after a user switches outbound redaction from observe to enforce: observe mode leaves evidence behind in /leaks, enforce mode replaced the secrets in place and left nothing, so the panel goes quiet exactly when protection is at its strongest. The column is nullable, like tool_calls: "redaction was off" and "redaction was on and replaced nothing" are different facts. Only the count is stored — what was replaced is precisely what must not be written down. **Summary reports flagged and redacted request counts** for the window, so a security panel can say what each defence actually saw rather than only which mode it is in. Co-Authored-By: Claude Opus 5 --- crates/tw-api/src/lib.rs | 29 +++++++++-- crates/tw-control/src/lib.rs | 2 + crates/tw-control/tests/adopt.rs | 1 + crates/tw-store/src/db.rs | 65 +++++++++++++++++++++--- crates/tw-store/src/recorder.rs | 69 ++++++++++++++++++++++++-- crates/tw-store/tests/m3_acceptance.rs | 1 + 6 files changed, 155 insertions(+), 12 deletions(-) diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 3a8f8242..214ad1a2 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -876,6 +876,18 @@ pub struct CostBucketGroup { pub failed: i64, pub cost_micros_exact: i64, pub cost_micros_estimated: i64, + /// 这一格里这一项用掉的 token。 + /// + /// **四类分开给。**它们的单价差十倍以上,加成一个数之后既算不回 + /// 钱,也说不清「这段时间是在写新上下文还是在吃缓存」。 + #[serde(default)] + pub input_tokens: i64, + #[serde(default)] + pub output_tokens: i64, + #[serde(default)] + pub cache_read_tokens: i64, + #[serde(default)] + pub cache_write_tokens: i64, } /// 按模型或上游分组的花费(钱花在哪儿)。 @@ -920,12 +932,23 @@ pub struct Summary { /// 那些请求用掉的 token。**它才是订阅用户该看的量** #[serde(default)] pub subscription_tokens: i64, - /// 缓存命中一共省下了多少微分。 + /// 用了缓存之后净省下多少微分。 /// - /// **算的是差额,不是「缓存读花了多少」** —— 用户想知道的是「如果 - /// 没命中要多花多少」 + /// **净额:命中节省的部分,减去写入产生的溢价。**用户想知道的是 + /// 「如果完全不用缓存,这段时间要多花还是少花」—— 而缓存写入按 + /// 1.25 倍单价计费,所以这个数可以是负的。 #[serde(default)] pub cache_saved_micros: i64, + /// 本区间有多少个请求带回了可疑工具调用(防线三) + #[serde(default)] + pub flagged_requests: i64, + /// 本区间有多少个请求在出站时被脱敏换过内容(防线一的拦截档) + /// + /// **观察档不产生这个数**,它产生的是 `/leaks` 里那些证据。两档 + /// 各有各的痕迹,界面上要分别说明 —— 否则切到拦截之后看起来像 + /// 什么都没发生,而那是防护更强的一档。 + #[serde(default)] + pub redacted_requests: i64, /// 价目表的快照日期。**成本旁边要标它** —— 一个两个月前 /// 的价目表算出来的数字,可信度和昨天的完全不同 pub pricing_date: String, diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 05347b7b..2c9ebd87 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -617,6 +617,8 @@ async fn summary( subscription_requests: x.subscription_requests, subscription_tokens: x.subscription_tokens, cache_saved_micros: x.cache_saved_micros, + flagged_requests: x.flagged_requests, + redacted_requests: x.redacted_requests, pricing_date: tw_pricing::SNAPSHOT_DATE.to_string(), })) } diff --git a/crates/tw-control/tests/adopt.rs b/crates/tw-control/tests/adopt.rs index 2180107e..175c1c4e 100644 --- a/crates/tw-control/tests/adopt.rs +++ b/crates/tw-control/tests/adopt.rs @@ -434,6 +434,7 @@ async fn replaying_a_truncated_body_is_refused_rather_than_misleading() { session: None, tool_calls: None, flagged: None, + redacted: None, provider: "relay".into(), model: "claude-sonnet-4-5".into(), path: "/v1/messages".into(), diff --git a/crates/tw-store/src/db.rs b/crates/tw-store/src/db.rs index ee7ea4ec..d7f67c5f 100644 --- a/crates/tw-store/src/db.rs +++ b/crates/tw-store/src/db.rs @@ -16,7 +16,7 @@ use std::path::Path; use rusqlite::{Connection, OptionalExtension, params}; /// 当前 schema 版本。**加字段就加一,并在 `migrate` 里补一步。** -const SCHEMA: i64 = 8; +const SCHEMA: i64 = 9; #[derive(Debug, thiserror::Error)] pub enum DbError { @@ -58,6 +58,8 @@ pub struct RequestRow { pub tool_calls: Option, /// 命中了几条危险规则 pub flagged: Option, + /// 出站脱敏换掉了几处。`None` = 那次没开脱敏,**不是 0** + pub redacted: Option, pub provider: String, pub model: String, pub path: String, @@ -256,6 +258,18 @@ impl Db { ALTER TABLE requests ADD COLUMN flagged INTEGER;", )?; } + if from < 9 { + // 出站脱敏换掉了几处(防线一的拦截档)。 + // + // **不记的话,切到「拦截」之后面板反而没数字了** —— 观察档 + // 产出的是「检测到的外泄」,而拦截档把它们就地换掉了,于是 + // 那条证据链在防护最强的时候断掉,读起来像「什么都没发生」。 + // + // 和 `tool_calls` 同一条理由用可空列:「没开脱敏」和 + // 「开了但这次没换」是两件事。 + self.conn + .execute_batch("ALTER TABLE requests ADD COLUMN redacted INTEGER;")?; + } self.conn.pragma_update(None, "user_version", SCHEMA)?; Ok(()) } @@ -267,8 +281,8 @@ impl Db { (id, at_ms, client, provider, model, path, status, ttfb_ms, duration_ms, bytes, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost_micros, cost_estimated, error, local, routing, billing, cache_saved_micros, - client_hint, session, tool_calls, flagged) - VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18,?19,?20,?21,?22,?23,?24,?25)", + client_hint, session, tool_calls, flagged, redacted) + VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18,?19,?20,?21,?22,?23,?24,?25,?26)", params![ r.id, r.at_ms, @@ -295,6 +309,7 @@ impl Db { r.session, r.tool_calls, r.flagged, + r.redacted, ], )?; Ok(()) @@ -590,7 +605,24 @@ impl Db { sub_reqs, sub_tokens, cache_saved, - ): (i64, i64, i64, i64, i64, i64, i64, i64, i64, i64, i64, i64) = self.conn.query_row( + flagged_requests, + redacted_requests, + ): ( + i64, + i64, + i64, + i64, + i64, + i64, + i64, + i64, + i64, + i64, + i64, + i64, + i64, + i64, + ) = self.conn.query_row( "SELECT COUNT(*), COALESCE(SUM(error IS NOT NULL), 0), @@ -605,7 +637,9 @@ impl Db { COALESCE(SUM(CASE WHEN billing = 'subscription' THEN COALESCE(input_tokens,0) + COALESCE(output_tokens,0) ELSE 0 END), 0), - COALESCE(SUM(cache_saved_micros), 0) + COALESCE(SUM(cache_saved_micros), 0), + COALESCE(SUM(flagged > 0), 0), + COALESCE(SUM(redacted > 0), 0) FROM requests WHERE at_ms >= ?1 AND at_ms < ?2 AND local = 0", params![since_ms, until_ms], @@ -623,6 +657,8 @@ impl Db { r.get(9)?, r.get(10)?, r.get(11)?, + r.get(12)?, + r.get(13)?, )) }, )?; @@ -644,6 +680,8 @@ impl Db { unpriced_requests: unpriced, subscription_requests: sub_reqs, subscription_tokens: sub_tokens, + flagged_requests, + redacted_requests, cache_saved_micros: cache_saved, }) } @@ -827,7 +865,11 @@ impl Db { 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(CASE WHEN cost_estimated = 1 THEN cost_micros ELSE 0 END), 0), + COALESCE(SUM(input_tokens), 0), + COALESCE(SUM(output_tokens), 0), + COALESCE(SUM(cache_read_tokens), 0), + COALESCE(SUM(cache_write_tokens), 0) FROM requests WHERE at_ms >= ?1 AND at_ms < ?2 AND local = 0 GROUP BY b, {col} ORDER BY b" @@ -841,6 +883,10 @@ 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)?, }) })?; rows.collect::, _>>().map_err(Into::into) @@ -918,6 +964,7 @@ fn row_from(r: &rusqlite::Row) -> rusqlite::Result { session: r.get("session")?, tool_calls: r.get("tool_calls")?, flagged: r.get("flagged")?, + redacted: r.get("redacted")?, provider: r.get("provider")?, model: r.get("model")?, path: r.get("path")?, @@ -965,6 +1012,10 @@ pub struct Summary { pub subscription_requests: i64, /// 那些请求用掉的 token。**它才是订阅用户该看的量** pub subscription_tokens: i64, + /// 本区间有多少个请求带回了可疑工具调用(防线三) + pub flagged_requests: i64, + /// 本区间有多少个请求在出站时被脱敏换过内容(防线一的拦截档) + pub redacted_requests: i64, /// 缓存命中一共省下了多少微分 pub cache_saved_micros: i64, } @@ -1009,6 +1060,7 @@ mod tests { session: None, tool_calls: None, flagged: None, + redacted: None, id, at_ms, client: "claude-code".into(), @@ -1543,6 +1595,7 @@ mod tests { db.conn .execute_batch( "DROP INDEX requests_session; + ALTER TABLE requests DROP COLUMN redacted; ALTER TABLE requests DROP COLUMN flagged; ALTER TABLE requests DROP COLUMN tool_calls; ALTER TABLE requests DROP COLUMN session; diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index 374b4bd9..e9fe4f8e 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -22,6 +22,8 @@ struct Partial { /// 响应里有几个工具调用、命中几条规则(防线三) tool_calls: Option, flagged: Option, + /// 出站脱敏换掉了几处(防线一)。`None` = 那次没开脱敏 + redacted: Option, client: String, client_hint: Option, session: Option, @@ -160,6 +162,7 @@ impl Recorder { session, tool_calls: None, flagged: None, + redacted: None, provider: provider.clone(), model: model.clone(), path: path.clone(), @@ -202,6 +205,23 @@ impl Recorder { p.billing = billing.clone(); } } + /* + 这次请求里换掉了几处。 + + **只记条数,不记内容。**换掉的正是不能落盘的东西 —— + 记下来等于把外泄搬了个家。 + + 以前这条事件整个不落表,理由是「它属于请求详情」。但 + 请求详情本身也没存它,于是切到「拦截」档之后,面板上 + 那条证据链断了:观察档看得见「检测到 12 处外泄」,拦截 + 档反而什么都没有,而后者是防护更强的一档。 + */ + Event::Redacted { id, items, .. } => { + if let Some(p) = self.inflight.get_mut(id) { + let n: i64 = items.iter().map(|x| x.count as i64).sum(); + p.redacted = Some(p.redacted.unwrap_or(0) + n); + } + } Event::RequestHeaders { id, status, @@ -266,6 +286,7 @@ impl Recorder { session: p.session, tool_calls: p.tool_calls, flagged: p.flagged, + redacted: p.redacted, provider: p.provider, model: p.model, path: p.path, @@ -300,6 +321,7 @@ impl Recorder { session: p.session, tool_calls: p.tool_calls, flagged: p.flagged, + redacted: p.redacted, provider: p.provider, model: p.model, path: p.path, @@ -337,6 +359,7 @@ impl Recorder { session: None, tool_calls: None, flagged: None, + redacted: None, provider: String::new(), model: String::new(), path: probe.clone(), @@ -385,9 +408,6 @@ impl Recorder { | Event::ConfigRejected { .. } | Event::QuotaSeen { .. } | Event::ScanAlert { .. } - // 脱敏事件也不落这张表:它说的是「这次请求里换掉了什么」, - // 而那属于请求详情,不是另一行记录 - | Event::Redacted { .. } | Event::ToolCallFlagged { .. } | Event::Translated { .. } // 凭据轮换说的是配置文件该改了,跟哪一次请求无关 @@ -838,6 +858,49 @@ mod billing_tests { } } +#[cfg(test)] +mod redaction_tests { + use super::tests::{finished, rec, started}; + + /// **拦截档也要留下痕迹。**观察档产出的是「检测到的外泄」证据, + /// 而拦截档把它们就地换掉了 —— 那一刻如果什么都不记,面板在防护 + /// 最强的一档上反而是空的,读起来像什么都没发生。 + #[test] + fn a_redaction_is_counted_on_the_row_it_happened_to() { + let (_d, mut r) = rec(); + r.on_event(&started(1, "claude-sonnet-4-5")); + r.on_event(&tw_api::Event::Redacted { + id: 1, + provider: "relay".into(), + items: vec![ + tw_api::RedactedItem { + kind: "api_key".into(), + what: "sk-…".into(), + count: 2, + }, + tw_api::RedactedItem { + kind: "token".into(), + what: "ghp_…".into(), + count: 1, + }, + ], + at_ms: 0, + }); + r.on_event(&finished(1, None)); + assert_eq!(r.db().get(1).unwrap().unwrap().redacted, Some(3)); + } + + /// **「没开脱敏」和「开了但这次没换」是两件事。**记成 0 的话, + /// 关掉脱敏的那段时间在统计里会变成「一处都没换过」—— 那是假的。 + #[test] + fn no_redaction_event_means_unknown_not_zero() { + let (_d, mut r) = rec(); + r.on_event(&started(1, "claude-sonnet-4-5")); + r.on_event(&finished(1, None)); + assert_eq!(r.db().get(1).unwrap().unwrap().redacted, None); + } +} + #[cfg(test)] mod cache_saving_tests { use super::tests::{finished, rec, started}; diff --git a/crates/tw-store/tests/m3_acceptance.rs b/crates/tw-store/tests/m3_acceptance.rs index ecde95cf..2d20ddc0 100644 --- a/crates/tw-store/tests/m3_acceptance.rs +++ b/crates/tw-store/tests/m3_acceptance.rs @@ -31,6 +31,7 @@ fn req(id: i64, at_ms: i64) -> RequestRow { session: None, tool_calls: None, flagged: None, + redacted: None, provider: "官方".into(), model: "claude-sonnet-4-5".into(), path: "/v1/messages".into(),