From 535c298ee73bdae82ca5c20bbf511f1dbb39ff4d Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Wed, 16 Sep 2026 13:17:53 +0800 Subject: [PATCH] feat: report the price back onto the bus MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The store is the only place in the chain that knows what a request cost — the gateway knows how many tokens went by, the per-token rate is looked up here when the row is written. So the price arrives a moment after the request finishes, and nothing announced it. Anything wanting to show a figure had to go back and query for it after the fact. In the desktop client that is a re-read of the last two hundred rows a couple of seconds after every batch of requests, kept alive purely because this one number was missing from the stream. A live chart cannot use that at all. `RequestPriced` is a separate event rather than a field on `RequestFinished` on purpose: putting it there would make the gateway depend on the price table, which files "forwarding" under "billing". The recorder gets an optional bus handle and reports what it computed; twcore does the wiring, being the one place that sees both sides. All three values stay optional. Upstream returned no usage, the model is absent from the table, the provider bills by subscription — none of those is zero, and a zero would be drawn as "free". Co-Authored-By: Claude Opus 5 --- Cargo.lock | 2 + bin/twcore/Cargo.toml | 1 + bin/twcore/src/main.rs | 11 ++-- crates/tw-api/src/lib.rs | 22 ++++++++ crates/tw-store/Cargo.toml | 1 + crates/tw-store/src/recorder.rs | 94 ++++++++++++++++++++++++++++++++- 6 files changed, 127 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8fa7c42b..f71305f8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3042,6 +3042,7 @@ dependencies = [ "tokio", "tracing", "tw-api", + "tw-observe", "tw-pricing", ] @@ -3081,6 +3082,7 @@ dependencies = [ "tw-config", "tw-control", "tw-gateway", + "tw-observe", "tw-pricing", "tw-scan", "tw-secret", diff --git a/bin/twcore/Cargo.toml b/bin/twcore/Cargo.toml index 364cf35c..ee2279cb 100644 --- a/bin/twcore/Cargo.toml +++ b/bin/twcore/Cargo.toml @@ -13,6 +13,7 @@ tw-control = { workspace = true } tw-gateway = { workspace = true } tw-yaml = { workspace = true } tw-api = { workspace = true } +tw-observe = { workspace = true } tw-store = { workspace = true } tw-pricing = { workspace = true } chrono = { workspace = true } diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index 013e6eba..abb11af4 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -668,7 +668,7 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> // body 的通道在这里建:**它是唯一同时看得见网关和存储的地方**, // 而两边各有各的同形结构,是为了不让「观测」挂到「转发」下面。 let (body_tx, body_rx) = tokio::sync::mpsc::channel(tw_gateway::bodies::CHANNEL_CAP); - let store = build_store(&dir, state.bus.subscribe(), body_rx); + let store = build_store(&dir, state.bus.clone(), body_rx); if store.is_some() { state.set_body_sink(body_tx); } @@ -795,9 +795,12 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> /// 处理方式是「不转发了」。 fn build_store( dir: &Path, - events: tokio::sync::broadcast::Receiver, + // **收整条总线,不只是一个订阅端。**存储层算完价钱要往回报一条 + // (见 `Event::RequestPriced`)—— 它是这条链上唯一知道单价的地方。 + bus: tw_observe::EventBus, bodies: tokio::sync::mpsc::Receiver, ) -> Option>> { + let events = bus.subscribe(); let db = match tw_store::Db::open(&dir.join("data.db")) { Ok(db) => db, Err(e) => { @@ -839,7 +842,9 @@ fn build_store( } }); Some(tw_store::task::spawn( - tw_store::Recorder::new(db, blobs, prices), + // 算完价钱往回报一条 —— 见 `Event::RequestPriced`。这里是唯一 + // 同时看得见总线和存储层的地方,所以接线在这儿完成。 + tw_store::Recorder::new(db, blobs, prices).reporting_to(bus), events, rx, )) diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 214ad1a2..47f08aca 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -205,6 +205,27 @@ pub enum Event { alerts: Vec, at_ms: u64, }, + /// 这次请求花了多少钱 —— **在它跑完之后一小会儿才知道**。 + /// + /// 价钱不在数据面的职责里:网关知道用了多少 token,而单价在存储层 + /// 落库时才查价目表算出来。所以它是一条独立事件,而不是 + /// `RequestFinished` 上的一个字段 —— 后者会要求网关依赖价目表,把 + /// 「转发」挂到「计价」下面。 + /// + /// 没有这条的话,界面想知道价钱就只能在请求结束之后回库里再查一遍。 + /// + /// 三个值都可能是「算不出来」:上游没报用量、模型不在价目表里、 + /// 或者那家是订阅计费 —— **那都不是零**。 + RequestPriced { + id: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + cost_micros: Option, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + cost_estimated: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + cache_saved_micros: Option, + at_ms: u64, + }, /// 客户端配置面上的文件动了 —— **不管改了什么**。 /// /// 和 `ScanAlert` 是两件事。那条说的是「出现了可疑内容」,值得打断 @@ -338,6 +359,7 @@ impl Event { | Event::QuotaSeen { id, .. } | Event::LeakSeen { id, .. } | Event::ScanAlert { id, .. } + | Event::RequestPriced { id, .. } | Event::ClientsChanged { id, .. } | Event::HealthChanged { id, .. } | Event::Redacted { id, .. } diff --git a/crates/tw-store/Cargo.toml b/crates/tw-store/Cargo.toml index 340eb1cd..3c838ed5 100644 --- a/crates/tw-store/Cargo.toml +++ b/crates/tw-store/Cargo.toml @@ -9,6 +9,7 @@ description = "Request history and runtime state on SQLite and the filesystem" [dependencies] tw-api = { workspace = true } +tw-observe = { workspace = true } tw-pricing = { workspace = true } bytes = { workspace = true } rusqlite = { workspace = true } diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index e9fe4f8e..30a371b5 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -60,6 +60,14 @@ pub struct Recorder { /// 那不理想,但比把它持久化成第四份状态好:会话是个观测概念,不是 /// 事实来源。 sessions: HashMap, + /// 算完价钱之后往回报一条。 + /// + /// **这一层是唯一知道价钱的地方** —— 网关只知道用了多少 token, + /// 单价在这里查价目表。不报的话,界面想知道花了多少就只能在请求 + /// 结束之后回库里再查一遍。 + /// + /// `None` 表示没人要听(测试、以及不带总线的调用方)。 + bus: Option, } /// 多久查一次磁盘。 @@ -82,9 +90,16 @@ impl Recorder { sessions: HashMap::new(), level: DiskLevel::Ok, last_check_ms: 0, + bus: None, } } + /// 把算出来的价钱报回总线上。 + pub fn reporting_to(mut self, bus: tw_observe::EventBus) -> Self { + self.bus = Some(bus); + self + } + pub fn level(&self) -> DiskLevel { self.level } @@ -278,6 +293,17 @@ impl Recorder { } else { None }; + // **算完就报,不等人来问。**这是整条链上唯一知道价钱的 + // 地方,而界面上那一列金额在它到达之前只能是「—」。 + if let Some(bus) = &self.bus { + bus.emit(Event::RequestPriced { + id: *id, + cost_micros, + cost_estimated: estimated, + cache_saved_micros, + at_ms: p.at_ms as u64, + }); + } self.write(RequestRow { id: *id as i64, at_ms: p.at_ms, @@ -415,7 +441,9 @@ impl Recorder { // 客户端配置面变了、某家上游熔断了 —— 都是「现在什么情况」, // 不是「刚才发生过什么」。这张表只装后者。 | Event::ClientsChanged { .. } - | Event::HealthChanged { .. } => {} + | Event::HealthChanged { .. } + // 自己刚报出去的那条。**不能再处理一遍** —— 那是一个回路 + | Event::RequestPriced { .. } => {} Event::ResponseInspected { id, tool_calls, @@ -858,6 +886,70 @@ mod billing_tests { } } +#[cfg(test)] +mod pricing_report_tests { + use super::tests::{finished, rec, started}; + use tw_api::UsageView; + + /// **算完的价钱要报回去,不能等界面回头来问。**这一层是整条链上 + /// 唯一知道单价的地方:网关只知道用了多少 token。不报的话,界面上 + /// 那一列金额在请求结束之后只能靠再查一次库才填得上。 + #[test] + fn the_price_goes_back_onto_the_bus() { + let (_d, mut r) = rec(); + let bus = tw_observe::EventBus::new(); + let mut rx = bus.subscribe(); + r = r.reporting_to(bus); + r.on_event(&started(1, "claude-sonnet-4-5")); + r.on_event(&finished( + 1, + Some(UsageView { + // 压在 200k 以下:超过之后走的是长上下文那档单价 + input: 100_000, + output: 0, + ..Default::default() + }), + )); + let mut priced = None; + while let Ok(ev) = rx.try_recv() { + if let tw_api::Event::RequestPriced { + id, cost_micros, .. + } = ev + { + priced = Some((id, cost_micros)); + } + } + // Sonnet 4.5 输入 $3/M —— 十万 token 是 $0.30 + assert_eq!(priced, Some((1, Some(300_000)))); + } + + /// **「算不出来」要原样报出去,不能报成零。**订阅制上游、价目表里 + /// 没有的模型,都是这一档 —— 报 0 的话界面会画一个「免费」。 + #[test] + fn an_unpriceable_request_reports_nothing_not_zero() { + let (_d, mut r) = rec(); + let bus = tw_observe::EventBus::new(); + let mut rx = bus.subscribe(); + r = r.reporting_to(bus); + r.on_event(&started(1, "某个中转站的模型")); + r.on_event(&finished( + 1, + Some(UsageView { + input: 1000, + output: 10, + ..Default::default() + }), + )); + let mut priced = None; + while let Ok(ev) = rx.try_recv() { + if let tw_api::Event::RequestPriced { cost_micros, .. } = ev { + priced = Some(cost_micros); + } + } + assert_eq!(priced, Some(None)); + } +} + #[cfg(test)] mod redaction_tests { use super::tests::{finished, rec, started};