From bf28afb2e01b14b5c4b91ddb1b802b0a157943d5 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Mon, 28 Sep 2026 00:58:26 +0800 Subject: [PATCH] feat(observe): record when the first token arrives and how fast a response is generated Requests now carry the moment the upstream produced its first token and a generation speed measured from there, instead of timing generation from the response headers. - New event `RequestFirstToken { id, ttft_ms }`: the first text, reasoning or tool call in a successful streamed response, read in the upstream's format (opening frames such as `message_start` do not count). - `RequestFinished.tokens_per_sec`: output after the first token divided by the time from the first token to the end. When reasoning was hidden before the first token, the reported reasoning tokens are left out; when the upstream does not report how many there were, there is no rate. Whole (non-streamed) responses, cancelled and failed requests, and generations shorter than half a second have no rate. - The request store keeps `ttft_ms` and `tokens_per_sec` (schema 22), and `HistoryRow` carries both. - New endpoints `/token-rate` and `/token-rate/provider`: the median rate by model and by upstream, with sample counts. - `/latency` and `/latency/provider` now report the first-token time; whole responses have no first token and are left out. - `/live` averages the per-request rates weighted by generation time. It used to divide output by the time after the response headers, so one whole response (headers arrive only when generation is done) could push the figure to tens of thousands of tokens per second. Control-plane protocol version 27. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- README.zh-CN.md | 2 +- crates/tw-api/src/ep.rs | 3 + crates/tw-api/src/lib.rs | 61 +++- crates/tw-control/src/lib.rs | 36 +++ crates/tw-control/tests/bundle.rs | 2 + crates/tw-control/tests/in_flight.rs | 8 +- crates/tw-control/tests/live_state.rs | 1 + crates/tw-control/tests/replay.rs | 2 + crates/tw-control/tests/security.rs | 2 + crates/tw-control/tests/sessions.rs | 2 + crates/tw-control/tests/summary.rs | 2 + crates/tw-gateway/src/ending.rs | 287 +++++++++++++++++- .../tw-gateway/src/server/pipeline/relay.rs | 34 ++- crates/tw-gateway/tests/first_token.rs | 233 ++++++++++++++ crates/tw-observe/src/bus.rs | 109 ++++--- crates/tw-store/src/db.rs | 198 ++++++++++-- crates/tw-store/src/lib.rs | 2 +- crates/tw-store/src/recorder.rs | 102 ++++++- crates/tw-store/tests/m3_acceptance.rs | 12 +- 20 files changed, 1012 insertions(+), 90 deletions(-) create mode 100644 crates/tw-gateway/tests/first_token.rs diff --git a/README.md b/README.md index 5da54f42..355722c3 100644 --- a/README.md +++ b/README.md @@ -69,8 +69,8 @@ Documentation: [configuration reference](docs/config.md) · starts in observe mode except the output limit, which starts off. Built-in rules can be turned off one at a time, and custom rules added. - **Request history and live events.** Every request is stored in a local - SQLite database with the rule it matched, each upstream attempt, its usage and - its cost. The control plane streams events as requests start and finish, and a + SQLite database with the rule it matched, each upstream attempt, its usage, its + cost, the time its first token arrived and its generation speed. The control plane streams events as requests start and finish, and a dry run shows where a request would be routed, and why, without sending it. - **One configuration file.** All settings are kept in `config.yaml`. A change, whether made in an editor, with `twcore config` or through the control plane, diff --git a/README.zh-CN.md b/README.zh-CN.md index 8d44b9d9..d0c4b2a0 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -23,7 +23,7 @@ ThinkWatch Core 是一组 Rust crate,以及由它们构建的网关二进制 ` - **格式转换**。客户端可以使用 Anthropic Messages、OpenAI Chat Completions、OpenAI Responses 或 Gemini 格式,与上游使用的格式无关;两者不同时,请求、响应和流式输出都会转换。上游可以是服务商的 API、OpenRouter 等中转站、本地模型服务或 ChatGPT 账号。 - **费用核算**。每个请求的 token 用量(含缓存读写)按每日刷新的公开价目表计价;收费方式不同的上游可以选用自定义价目表(倍率或逐模型价格),本地模型等上游可以设为不计费。无法计价的用量标为「未知」,不计作零;每个请求保存其费用及价格来源。 - **防护**。五项防护作用于所有请求,不区分上游,各有关闭、观察、拦截三档。在拦截档下:出站脱敏在请求发出前把 API 密钥、私钥、连接串中的口令等凭据替换为占位符,并在响应回显时还原;工具调用审查在上游返回的工具调用命中危险命令规则时可以切断响应;隐藏字符检测拒绝带有 Unicode 标签字符或双向控制符的请求;内容过滤可以拒绝命中关键词或正则规则的请求;输出长度在回答超过设定的字符数时将其切断。在观察档下,防护只记录发现的内容,不改变任何行为。除输出长度出厂为关闭外,其余各项出厂均为观察。内置规则可以逐条停用,也可以添加自定义规则。 -- **请求记录与实时事件**。每个请求连同命中的规则、每次上游尝试、用量和费用保存在本机的 SQLite 数据库中。控制面在请求开始和结束时推送事件;试算可以在不发出请求的情况下说明请求会被路由到哪里及其原因。 +- **请求记录与实时事件**。每个请求连同命中的规则、每次上游尝试、用量、费用、第一个 token 到达的时刻和生成速度保存在本机的 SQLite 数据库中。控制面在请求开始和结束时推送事件;试算可以在不发出请求的情况下说明请求会被路由到哪里及其原因。 - **单一配置文件**。全部设置保存在 `config.yaml` 中。无论改动来自编辑器、`twcore config` 还是控制面,通过校验后都在一秒内生效;未通过校验的改动被拒绝,原配置继续生效。最近五十个版本都会保留,可以恢复其中任一版本。 ## 安装 diff --git a/crates/tw-api/src/ep.rs b/crates/tw-api/src/ep.rs index 50295e17..68c73814 100644 --- a/crates/tw-api/src/ep.rs +++ b/crates/tw-api/src/ep.rs @@ -47,6 +47,9 @@ endpoints! { History: GET "/history", api::ListQuery => Vec; Latency: GET "/latency", api::Window => Vec; LatencyByProvider: GET "/latency/provider", api::Window => Vec; + /// 生成速度的中位数,按模型、按上游 + TokenRate: GET "/token-rate", api::Window => Vec; + TokenRateByProvider: GET "/token-rate/provider", api::Window => Vec; RequestDetail: GET "/request/{id}" [id], () => api::RequestDetail; /// 把一条记录变成回放用例(YAML) Fixture: GET "/request/{id}/fixture" [id], () => String, text; diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 26417cdf..a3424d5f 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -620,7 +620,14 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// 网关填的(含 ThinkWatch 的 User-Agent)、上游配置里写的和各协议要的那几个,客户端 /// 自己的 User-Agent 和身份头只在这一项打开时才发。照 25 写的界面保存时不给这个字段, /// 会把它关掉。 -pub const CONTROL_API_VERSION: u32 = 26; +/// +/// **27 起记第一个 token 到的时刻和生成速度**:新事件 [`Event::RequestFirstToken`], +/// `RequestFinished::tokens_per_sec`,[`HistoryRow`] 的 `ttft_ms` 和 +/// `tokens_per_sec`,按模型、按上游的速度中位数(`/token-rate`、`/token-rate/provider`)。 +/// `/latency` 两个端点和 [`LiveView::tokens_per_sec`] 同版改成从第一个 token 算:以前 +/// 从响应头算,非流式请求的响应头要等整段生成完才到,一条就能把速度顶到几万。照 26 +/// 写的界面不认那个新事件。 +pub const CONTROL_API_VERSION: u32 = 27; #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] @@ -765,6 +772,15 @@ pub enum Event { /// 到结束可能还有好几分钟,UI 要能在这个点就把行画出来并显示 /// 「进行中」,而不是等它结束才出现。 RequestHeaders { id: u64, status: u16, ttfb_ms: u64 }, + /// 上游吐出了第一个 token:文本、推理,或者一个工具调用开了头。 + /// + /// **和响应头是两个时刻。**流式响应的响应头一般一收到请求就回,之后上游还要 + /// 排队、读完整段输入,才开始生成 —— 用户等的是这一刻。`message_start`、 + /// `response.created` 这类开场帧不算:那是上游收到请求就发的。 + /// + /// 只有成功的流式响应有。非流式的整段一起到,没有「第一个」;不带 `alt=sse` 的 + /// Gemini 流和 WebSocket 那条路不在这里解析,也没有。 + RequestFirstToken { id: u64, ttft_ms: u64 }, /// 结束了 RequestFinished { id: u64, @@ -784,6 +800,14 @@ pub enum Event { /// 调用看起来是免费的 #[serde(default, skip_serializing_if = "Option::is_none")] usage: Option, + /// 生成速度:每秒输出多少 token,**从第一个 token 算到结束**。 + /// + /// 分母不含第一个 token 之前的排队和读输入;分子是那之后吐出来的输出。推理 + /// 被隐藏的(第一个 token 之前模型一直在想、一个字都没吐),上游报了其中多少 + /// 是推理就扣掉,没报就没有这个数 —— 那些推理 token 是在分母之外生成的,算进 + /// 来会把速度顶高好几倍。没有第一个 token 的(非流式)、没有输出的,也没有 + #[serde(default, skip_serializing_if = "Option::is_none")] + tokens_per_sec: Option, }, /// 失败了。`source` 和 HTTP 响应里的 `x-thinkwatch-error` 是同一个词表 /// (`auth` / `config` / `upstream` / `request` / `rate_limited` / @@ -1331,6 +1355,7 @@ impl Event { match self { Event::RequestStarted { id, .. } | Event::RequestHeaders { id, .. } + | Event::RequestFirstToken { id, .. } | Event::RequestFinished { id, .. } | Event::RequestFailed { id, .. } | Event::RequestCancelled { id, .. } @@ -1370,8 +1395,10 @@ impl Event { pub struct LiveView { /// 开始了、还没有结局的请求,开始得早的在前。和 `/in-flight` 是同一批 pub running: Vec, - /// 最近一分钟跑完的请求平均每秒生成多少 token:**每个请求的输出除以它生成用的 - /// 时间**(总耗时减去首字节),按 token 加权。这一分钟里没有跑完的是空,不是 0 + /// 最近一分钟跑完的请求平均每秒生成多少 token:每个请求的速度(见 + /// `RequestFinished::tokens_per_sec`)按它生成用的时间加权,也就是这些请求 + /// 吐出的 token 合计除以生成用的时间合计。**只数有速度的**:非流式的不算。这一分钟里 + /// 没有的是空,不是 0 pub tokens_per_sec: Option, } @@ -1431,7 +1458,7 @@ pub struct InFlightRequest { pub id: u64, /// 关于它的事件,**照事件流上的样子、按发生的先后**:第一条是 `RequestStarted`, /// 之后是到目前为止发生了的 —— 响应头、路由、格式转换、防护的记录 - /// (`RequestHeaders`、`RequestRouted`、`Translated`、`SecretsFound`、 + /// (`RequestHeaders`、`RequestFirstToken`、`RequestRouted`、`Translated`、`SecretsFound`、 /// `HiddenTextFound`、`ContentMatched`、`OutputLimited`、`ToolCallFlagged`)。 /// 说的是上游现状的(`QuotaSeen`)不在里面:那是 `/quota` 的事 pub events: Vec, @@ -3047,6 +3074,10 @@ pub struct Summary { pub pricing_date: String, } +/// 第一个 token 到的时刻的分位数(`GET /latency`、`/latency/provider`),毫秒。 +/// +/// **只有流式请求有样本**:非流式的没有第一个 token(见 [`Event::RequestFirstToken`])。 +/// `model` 在按上游分的那个端点里是上游名。 #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct LatencyView { @@ -3057,6 +3088,19 @@ pub struct LatencyView { pub samples: usize, } +/// 生成速度的中位数(`GET /token-rate`、`/token-rate/provider`),token/秒。 +/// +/// 样本是有速度的请求(见 `RequestFinished::tokens_per_sec`)。`model` 在按上游 +/// 分的那个端点里是上游名。 +#[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct TokenRateView { + pub model: String, + pub p50: u32, + /// 和延迟一样:「90 token/秒」是 3 个样本还是 300 个,含义完全不同 + pub samples: usize, +} + /// 一条历史请求。 #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] @@ -3068,8 +3112,14 @@ pub struct HistoryRow { pub model: String, pub path: String, pub status: Option, + /// 响应头到的时刻 pub ttfb_ms: Option, + /// 第一个 token 到的时刻。只有流式请求有,见 [`Event::RequestFirstToken`] + pub ttft_ms: Option, pub duration_ms: Option, + /// 生成速度,token/秒。只有跑完的流式请求有,见 + /// `RequestFinished::tokens_per_sec` + pub tokens_per_sec: Option, pub bytes: Option, pub input_tokens: Option, pub output_tokens: Option, @@ -4263,6 +4313,7 @@ mod tests { bytes: 10, duration_ms: 5, usage: None, + tokens_per_sec: None, }; let v: serde_json::Value = serde_json::to_value(&e).unwrap(); assert_eq!(v["kind"], "request_finished"); @@ -4299,6 +4350,7 @@ mod tests { status: 200, ttfb_ms: 1, }, + Event::RequestFirstToken { id: 7, ttft_ms: 2 }, Event::RequestFinished { id: 7, model: String::new(), @@ -4306,6 +4358,7 @@ mod tests { bytes: 1, duration_ms: 1, usage: None, + tokens_per_sec: None, }, Event::RequestFailed { id: 7, diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 5df1fd29..687266d4 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -112,6 +112,8 @@ pub fn router(state: ControlState) -> Router { .at(ep::History, history) .at(ep::Latency, latency) .at(ep::LatencyByProvider, latency_by_provider) + .at(ep::TokenRate, token_rate) + .at(ep::TokenRateByProvider, token_rate_by_provider) .at(ep::Storage, storage) .at(ep::Quota, quota) .at(ep::SpeedQuote, speed_quote) @@ -1014,6 +1016,38 @@ async fn latency_by_provider( )) } +/// 生成速度的中位数,按模型。**「哪个模型吐得快」** +async fn token_rate( + State(s): State, + axum::extract::Query(q): axum::extract::Query, +) -> Result>, Fail> { + let (from, to) = range(q.from_ms, q.to_ms); + let store = need_store(&s)?; + let g = store.lock().await; + let xs = g.db().token_rate_by_model(from, to).map_err(records)?; + Ok(Json(xs.into_iter().map(token_rate_view).collect())) +} + +/// 按上游分的生成速度。**和按模型分是两个问题**,理由同延迟 +async fn token_rate_by_provider( + State(s): State, + axum::extract::Query(q): axum::extract::Query, +) -> Result>, Fail> { + let (from, to) = range(q.from_ms, q.to_ms); + let store = need_store(&s)?; + let g = store.lock().await; + let xs = g.db().token_rate_by_provider(from, to).map_err(records)?; + Ok(Json(xs.into_iter().map(token_rate_view).collect())) +} + +fn token_rate_view(r: tw_store::TokenRate) -> tw_api::TokenRateView { + tw_api::TokenRateView { + model: r.model, + p50: r.p50, + samples: r.samples, + } +} + async fn storage(State(s): State) -> Json { let Some(store) = &s.store else { return Json(tw_api::StorageStatus { @@ -1060,7 +1094,9 @@ fn history_row( path: r.path, status: r.status, ttfb_ms: r.ttfb_ms, + ttft_ms: r.ttft_ms, duration_ms: r.duration_ms, + tokens_per_sec: r.tokens_per_sec, bytes: r.bytes, input_tokens: r.input_tokens, output_tokens: r.output_tokens, diff --git a/crates/tw-control/tests/bundle.rs b/crates/tw-control/tests/bundle.rs index bccd51d5..9d5161c5 100644 --- a/crates/tw-control/tests/bundle.rs +++ b/crates/tw-control/tests/bundle.rs @@ -95,7 +95,9 @@ async fn replaying_a_truncated_body_is_refused_rather_than_misleading() { path: "/v1/messages".into(), status: Some(200), ttfb_ms: Some(100), + ttft_ms: None, duration_ms: Some(200), + tokens_per_sec: None, bytes: Some(10), input_tokens: Some(50), output_tokens: Some(20), diff --git a/crates/tw-control/tests/in_flight.rs b/crates/tw-control/tests/in_flight.rs index 5e5bec80..87c323fa 100644 --- a/crates/tw-control/tests/in_flight.rs +++ b/crates/tw-control/tests/in_flight.rs @@ -104,6 +104,7 @@ async fn it_gives_every_running_request_with_what_has_happened_to_it_so_far() { bytes: 10, duration_ms: 5, usage: None, + tokens_per_sec: None, }); let got = get(router).await; @@ -167,7 +168,11 @@ async fn live_gives_the_running_requests_and_the_generation_rate() { bus.emit(tw_api::Event::RequestHeaders { id: 1, status: 200, - ttfb_ms: 1_000, + ttfb_ms: 400, + }); + bus.emit(tw_api::Event::RequestFirstToken { + id: 1, + ttft_ms: 1_000, }); bus.emit(tw_api::Event::RequestFinished { id: 1, @@ -179,6 +184,7 @@ async fn live_gives_the_running_requests_and_the_generation_rate() { output: 100, ..Default::default() }), + tokens_per_sec: Some(50), }); bus.emit(started(2, "gpt-5.5")); diff --git a/crates/tw-control/tests/live_state.rs b/crates/tw-control/tests/live_state.rs index 0cc68d12..a1b399ac 100644 --- a/crates/tw-control/tests/live_state.rs +++ b/crates/tw-control/tests/live_state.rs @@ -187,6 +187,7 @@ async fn a_request_still_running_can_be_opened_and_becomes_whole_when_it_ends() bytes: 120, duration_ms: 4_000, usage: None, + tokens_per_sec: None, }); let (st, v) = get(&app, "/request/7").await; assert_eq!(st, StatusCode::OK, "{v}"); diff --git a/crates/tw-control/tests/replay.rs b/crates/tw-control/tests/replay.rs index c6236d02..b5ca929a 100644 --- a/crates/tw-control/tests/replay.rs +++ b/crates/tw-control/tests/replay.rs @@ -100,7 +100,9 @@ fn row(id: i64, provider: &str) -> tw_store::db::RequestRow { path: "/v1/messages".into(), status: Some(200), ttfb_ms: Some(100), + ttft_ms: None, duration_ms: Some(200), + tokens_per_sec: None, bytes: Some(10), input_tokens: Some(5), output_tokens: Some(2), diff --git a/crates/tw-control/tests/security.rs b/crates/tw-control/tests/security.rs index 5008f2d8..f7bdcd5e 100644 --- a/crates/tw-control/tests/security.rs +++ b/crates/tw-control/tests/security.rs @@ -57,7 +57,9 @@ fn request(id: i64, at_ms: i64, provider: &str) -> tw_store::db::RequestRow { path: "/v1/messages".into(), status: Some(200), ttfb_ms: Some(100), + ttft_ms: None, duration_ms: Some(200), + tokens_per_sec: None, bytes: Some(10), input_tokens: Some(50), output_tokens: Some(20), diff --git a/crates/tw-control/tests/sessions.rs b/crates/tw-control/tests/sessions.rs index 2a686933..c058c0d0 100644 --- a/crates/tw-control/tests/sessions.rs +++ b/crates/tw-control/tests/sessions.rs @@ -29,7 +29,9 @@ fn turn(id: i64, billing: &str) -> tw_store::db::RequestRow { path: "/v1/responses".into(), status: Some(200), ttfb_ms: Some(100), + ttft_ms: None, duration_ms: Some(200), + tokens_per_sec: None, bytes: Some(10), input_tokens: Some(50), output_tokens: Some(20), diff --git a/crates/tw-control/tests/summary.rs b/crates/tw-control/tests/summary.rs index e081c4b2..783b924f 100644 --- a/crates/tw-control/tests/summary.rs +++ b/crates/tw-control/tests/summary.rs @@ -28,7 +28,9 @@ fn req(id: i64, model: &str) -> tw_store::db::RequestRow { path: "/v1/messages".into(), status: Some(200), ttfb_ms: Some(100), + ttft_ms: None, duration_ms: Some(200), + tokens_per_sec: None, bytes: Some(10), input_tokens: Some(50), output_tokens: Some(20), diff --git a/crates/tw-gateway/src/ending.rs b/crates/tw-gateway/src/ending.rs index cdf0f087..6fc3b17f 100644 --- a/crates/tw-gateway/src/ending.rs +++ b/crates/tw-gateway/src/ending.rs @@ -23,9 +23,16 @@ use std::time::Instant; use crate::bodies::{BodyKind, BodyRecord, BodySender, ResponseTap}; +use tw_dialect::convert::Reader; +use tw_dialect::ir; use tw_dialect::usage::{Sniffer, Usage}; use tw_types::{Msg, msg}; +/// 生成用时不到这么久的,不给速度。**块太少,量的是上游怎么分块,不是模型多快**: +/// 一段十几个 token 的回答常常一两块就到齐了,两块之间只隔几毫秒,一除就是几千 +/// token/秒。 +const MIN_GENERATION_MS: u64 = 500; + /// 一个还欠着结局的请求。 /// /// **到目前为止对响应知道的一切都在它身上**:状态码、收到多少字节、嗅到 @@ -49,10 +56,33 @@ pub struct Ending { /// 旁路嗅探。客户端走掉那一刻手里有多少用量,靠的就是它 sniffer: Sniffer, tap: ResponseTap, + /// 认第一个 token 的。**只在上游回的是成功的流时才有**(见 [`Ending::streaming`]), + /// 认出来就扔掉 —— 之后的字节不必再解析 + first: Option, + /// 第一个 token 是什么时候、以什么开的头 + opened: Option, /// 报过了。**只能报一次** told: bool, } +/// 还在等第一个 token。 +struct FirstToken { + reader: Reader, + /// 在那之前有过推理块,却一个推理的字都没有:推理被隐藏了 + hidden_thought: bool, +} + +/// 第一个 token 到的那一刻。 +#[derive(Debug, Clone, Copy)] +struct Opened { + /// 从请求进来算,毫秒 + ms: u64, + /// 开头的是推理的字:推理边想边吐,推理 token 都生成在这之后 + with_thought: bool, + /// 开头之前推理被隐藏了:那些推理 token 生成在这之前 + hidden_thought: bool, +} + impl Ending { pub fn new( bus: tw_observe::EventBus, @@ -73,10 +103,24 @@ impl Ending { bytes: 0, sniffer: Sniffer::new(), tap: ResponseTap::new(), + first: None, + opened: None, told: false, } } + /// 上游回的是成功的流:按它的格式认第一个 token(见 `tw_api::Event::RequestFirstToken`)。 + /// + /// **按格式解析,不在字节里找关键字**,和测速(`crate::l3`)同一个读法:`message_start`、 + /// `response.created` 这些开场帧是上游收到请求就发的,认成第一个 token 的话,量到的是 + /// 建连有多快。 + pub fn streaming(&mut self, upstream: ir::Dialect) { + self.first = Some(FirstToken { + reader: Reader::new(upstream), + hidden_thought: false, + }); + } + /// 上游的响应头到了。从这里起,客户端再走掉,报出去的取消带着状态码。 pub fn responded(&mut self, status: u16) { self.status = Some(status); @@ -88,6 +132,39 @@ impl Ending { self.bytes += chunk.len() as u64; self.sniffer.feed(chunk); self.tap.feed(chunk); + self.spot(chunk); + } + + /// 在这一块里找第一个 token。找到就报,之后不再解析。 + fn spot(&mut self, chunk: &[u8]) { + let Some(f) = self.first.as_mut() else { + return; + }; + let mut opened = None; + for e in f.reader.feed(chunk) { + match opening(&e) { + Some(with_thought) => { + opened = Some((with_thought, f.hidden_thought)); + break; + } + None if hides_thought(&e) => f.hidden_thought = true, + None => {} + } + } + let Some((with_thought, hidden_thought)) = opened else { + return; + }; + self.first = None; + let ms = self.duration_ms(); + self.opened = Some(Opened { + ms, + with_thought, + hidden_thought, + }); + self.bus.emit(tw_api::Event::RequestFirstToken { + id: self.id, + ttft_ms: ms, + }); } /// 只数字节,不嗅用量、不留档。 @@ -104,13 +181,16 @@ impl Ending { pub fn finished(mut self, status: u16) { self.status = Some(status); let usage = self.settle(); + let duration_ms = self.duration_ms(); + let tokens_per_sec = rate(self.opened, usage.as_ref(), duration_ms); self.bus.emit(tw_api::Event::RequestFinished { id: self.id, model: std::mem::take(&mut self.model), status, bytes: self.bytes, - duration_ms: self.duration_ms(), - usage, + duration_ms, + usage: usage.map(view), + tokens_per_sec, }); } @@ -127,12 +207,12 @@ impl Ending { message, bytes: self.received(), duration_ms: Some(self.duration_ms()), - usage, + usage: usage.map(view), }); } /// 收尾:先把响应体交出去,再拿走用量。三种结局共用,只走一次。 - fn settle(&mut self) -> Option { + fn settle(&mut self) -> Option { self.told = true; let (recorded, original_len) = std::mem::take(&mut self.tap).finish(); if !recorded.is_empty() { @@ -147,7 +227,7 @@ impl Ending { }, ); } - std::mem::take(&mut self.sniffer).finish().map(view) + std::mem::take(&mut self.sniffer).finish() } fn duration_ms(&self) -> u64 { @@ -169,7 +249,7 @@ impl Drop for Ending { // **这里什么都不能 panic。**Drop 可能正跑在一次 unwind 里,那时 // 再 panic 一次,整个进程就没了。下面每一步都是不会失败的那种: // 往通道里 try_send、往广播里 send、读一下时钟。 - let usage = self.settle(); + let usage = self.settle().map(view); // 是网关自己的代码崩掉了。**记成取消会冤枉客户端** —— 排查的人 // 会去问一个根本没做过这件事的客户端。 if std::thread::panicking() { @@ -197,6 +277,66 @@ impl Drop for Ending { } } +/// 这个事件是不是模型开口了:`Some(true)` 是推理的字,`Some(false)` 是正文或工具调用。 +/// +/// **工具调用一开头就算**:块开头就带着工具名,那已经是模型吐出来的了;参数的第一段 +/// 常常是空的。 +fn opening(e: &ir::Event) -> Option { + match e { + ir::Event::Delta { + delta: ir::Delta::Thinking(t), + .. + } if !t.is_empty() => Some(true), + ir::Event::Delta { + delta: ir::Delta::Text(t) | ir::Delta::ToolInput(t), + .. + } if !t.is_empty() => Some(false), + ir::Event::BlockStart { + kind: ir::BlockKind::ToolCall { .. }, + .. + } => Some(false), + _ => None, + } +} + +/// 推理块开了头、或者只来了推理的签名:推理在进行,却没有字给出来 +fn hides_thought(e: &ir::Event) -> bool { + matches!( + e, + ir::Event::BlockStart { + kind: ir::BlockKind::Thinking, + .. + } | ir::Event::Delta { + delta: ir::Delta::Signature(_), + .. + } + ) +} + +/// 生成速度:第一个 token 之后吐出的输出,除以从那一刻到结束用的时间。 +/// +/// 分子要和分母对得上。推理被隐藏的,推理 token 生成在第一个 token 之前:上游报了其中 +/// 多少是推理就扣掉;没报(Anthropic 不分开报)就给不出,宁可没有也不给一个顶高好几倍 +/// 的数。推理边想边吐的,推理 token 都在分母之内,照数。 +fn rate(opened: Option, usage: Option<&Usage>, duration_ms: u64) -> Option { + let o = opened?; + let u = usage?; + let counted = if o.with_thought { + u.output + } else if u.reasoning > 0 { + u.output.saturating_sub(u.reasoning) + } else if o.hidden_thought { + return None; + } else { + u.output + }; + let gen_ms = duration_ms.saturating_sub(o.ms); + if counted == 0 || gen_ms < MIN_GENERATION_MS { + return None; + } + Some((counted.saturating_mul(1000) / gen_ms).min(u64::from(u32::MAX)) as u32) +} + fn view(u: Usage) -> tw_api::UsageView { tw_api::UsageView { input: u.input, @@ -410,6 +550,141 @@ mod tests { ); } + const TEXT_BLOCK: &[u8] = b"event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n"; + const TEXT_DELTA: &[u8] = b"event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"Hi\"}}\n\n"; + + fn first_tokens(got: &[Event]) -> Vec { + got.iter() + .filter_map(|e| match e { + Event::RequestFirstToken { ttft_ms, .. } => Some(*ttft_ms), + _ => None, + }) + .collect() + } + + /// **开场帧不算。**`message_start` 和空的文本块是上游收到请求就发的;第一个字才是 + /// 模型开口。报一次,之后不再报 + #[test] + fn the_first_token_is_the_first_word_not_the_opening_frames() { + let bus = tw_observe::EventBus::new(); + let mut rx = bus.subscribe(); + let mut e = responding(&bus); + e.streaming(ir::Dialect::Anthropic); + e.feed(MESSAGE_START); + e.feed(TEXT_BLOCK); + assert!(drain(&mut rx).is_empty(), "开场帧被当成了第一个 token"); + e.feed(TEXT_DELTA); + e.feed(TEXT_DELTA); + let got = drain(&mut rx); + assert_eq!(first_tokens(&got).len(), 1, "{got:?}"); + e.finished(200); + assert!(first_tokens(&drain(&mut rx)).is_empty()); + } + + /// 工具调用一开头就算:块开头就带着工具名,参数的第一段常常是空的 + #[test] + fn a_tool_call_opens_the_answer_before_its_arguments() { + let bus = tw_observe::EventBus::new(); + let mut rx = bus.subscribe(); + let mut e = responding(&bus); + e.streaming(ir::Dialect::Anthropic); + e.feed(MESSAGE_START); + e.feed(b"event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"tool_use\",\"id\":\"t1\",\"name\":\"Bash\",\"input\":{}}}\n\n"); + assert_eq!(first_tokens(&drain(&mut rx)).len(), 1); + drop(e); + } + + /// 没说是流的(非流式、上游回了错误)不解析,也就没有第一个 token + #[test] + fn a_response_that_is_not_a_stream_has_no_first_token() { + let bus = tw_observe::EventBus::new(); + let mut rx = bus.subscribe(); + let mut e = responding(&bus); + e.feed(TEXT_DELTA); + e.finished(200); + let got = drain(&mut rx); + assert!(first_tokens(&got).is_empty(), "{got:?}"); + assert!( + matches!( + got.as_slice(), + [Event::RequestFinished { + tokens_per_sec: None, + .. + }] + ), + "{got:?}" + ); + } + + fn usage(output: u64, reasoning: u64) -> Usage { + Usage { + output, + reasoning, + ..Default::default() + } + } + + fn opened(ms: u64, with_thought: bool, hidden_thought: bool) -> Option { + Some(Opened { + ms, + with_thought, + hidden_thought, + }) + } + + /// 从第一个 token 算到结束:第一秒在排队、读输入,之后 5 秒吐了 500 个 + #[test] + fn the_rate_counts_from_the_first_token() { + let u = usage(500, 0); + assert_eq!( + rate(opened(1_000, false, false), Some(&u), 6_000), + Some(100) + ); + } + + /// **推理被隐藏、上游报了其中多少是推理**:那 2000 个推理 token 生成在第一个 token + /// 之前,不扣掉的话是 1100 token/秒 + #[test] + fn hidden_reasoning_is_left_out_when_the_upstream_says_how_much_it_was() { + let u = usage(2_200, 2_000); + assert_eq!( + rate(opened(20_000, false, true), Some(&u), 22_000), + Some(100) + ); + // Chat Completions 的推理模型连推理块都不发,只在用量里报推理 token + assert_eq!( + rate(opened(20_000, false, false), Some(&u), 22_000), + Some(100) + ); + } + + /// 推理被隐藏、上游又不分开报(Anthropic):给不出一个对的数,就不给 + #[test] + fn hidden_reasoning_of_unknown_size_gives_no_rate() { + let u = usage(2_200, 0); + assert_eq!(rate(opened(20_000, false, true), Some(&u), 22_000), None); + } + + /// 推理边想边吐的,推理 token 都生成在第一个 token 之后,照数 + #[test] + fn visible_reasoning_is_counted() { + let u = usage(1_000, 800); + assert_eq!(rate(opened(1_000, true, true), Some(&u), 11_000), Some(100)); + } + + /// 生成不到半秒、没有第一个 token、没有用量、没有输出的,都没有速度 + #[test] + fn a_rate_needs_a_first_token_output_and_enough_time() { + let u = usage(40, 0); + assert_eq!(rate(opened(1_000, false, false), Some(&u), 1_300), None); + assert_eq!(rate(None, Some(&u), 5_000), None); + assert_eq!(rate(opened(1_000, false, false), None, 5_000), None); + assert_eq!( + rate(opened(1_000, false, false), Some(&usage(0, 0)), 5_000), + None + ); + } + /// WebSocket 那条路只数字节。**帧里的 usage 不能被嗅成整条连接的用量** /// —— 那是某一轮的数。 #[test] diff --git a/crates/tw-gateway/src/server/pipeline/relay.rs b/crates/tw-gateway/src/server/pipeline/relay.rs index 6bddbb09..643c6ace 100644 --- a/crates/tw-gateway/src/server/pipeline/relay.rs +++ b/crates/tw-gateway/src/server/pipeline/relay.rs @@ -88,7 +88,21 @@ pub(super) fn respond( &mut out_headers, session.as_ref(), ); - let mut relay = Relay::new(state, rt, req, plan, &ledger, session, provider, id); + let upstream_dialect = upstream_dialect(req, session.as_ref()); + // 成功的流才有「第一个 token」:整包的一起到,错误不是回答 + if generates && plan.is_sse && status.is_success() { + ending.streaming(upstream_dialect); + } + let mut relay = Relay::new( + state, + rt, + plan, + &ledger, + session, + provider, + id, + upstream_dialect, + ); let chunks = upstream.bytes_stream(); let dialect = req.dialect; // 上游静默时补心跳:**只给 Anthropic Messages 的流**。那是客户端按字节计时、 @@ -199,6 +213,17 @@ pub(super) fn respond( resp } +/// 上游说的是哪种格式。转换过的看会话,直通的就是客户端那一种。 +fn upstream_dialect( + req: &Inbound, + session: Option<&tw_dialect::convert::Session>, +) -> tw_dialect::ir::Dialect { + session + .map(|s| s.upstream) + .or_else(|| req.api.map(|a| a.dialect())) + .unwrap_or(tw_dialect::ir::Dialect::Anthropic) +} + /// Anthropic 的心跳帧,和它自己的 API 发的一样。 const PING: &[u8] = b"event: ping\ndata: {\"type\": \"ping\"}\n\n"; @@ -370,19 +395,14 @@ impl Relay { fn new( state: &AppState, rt: &Runtime, - req: &Inbound, plan: Plan, ledger: &tw_guard::redact::replace::Ledger, session: Option, provider: &tw_config::Provider, id: u64, + upstream_dialect: tw_dialect::ir::Dialect, ) -> Self { // 还原看的是**上游的原话**(转换之前),所以按上游的格式认帧 - let upstream_dialect = session - .as_ref() - .map(|s| s.upstream) - .or_else(|| req.api.map(|a| a.dialect())) - .unwrap_or(tw_dialect::ir::Dialect::Anthropic); let restorer = tw_guard::redact::sse::Body::new(ledger, plan.is_sse, upstream_dialect); let back = if plan.convert_stream { session.as_ref().map(|s| s.stream()) diff --git a/crates/tw-gateway/tests/first_token.rs b/crates/tw-gateway/tests/first_token.rs new file mode 100644 index 00000000..711cc81c --- /dev/null +++ b/crates/tw-gateway/tests/first_token.rs @@ -0,0 +1,233 @@ +//! 第一个 token 什么时候到、之后吐得多快。 +//! +//! 起真网关、真上游:要验的是时刻 —— 响应头、第一个 token、结束各在什么时候, +//! 以及速度是从哪一刻算起的。这些在单元测试里只能假装。 + +use std::net::SocketAddr; +use std::time::Duration; + +use axum::Router; +use axum::routing::any; +use bytes::Bytes; +use tokio::sync::broadcast::Receiver; +use tw_api::Event; +use tw_config::{Client, Config, Protocol, Provider}; + +const MESSAGE_START: &[u8] = b"event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":50,\"output_tokens\":1}}}\n\n"; +const TEXT_BLOCK: &[u8] = b"event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n"; +const TEXT_DELTA: &[u8] = b"event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"word \"}}\n\n"; +const MESSAGE_END: &[u8] = b"event: message_delta\ndata: {\"type\":\"message_delta\",\"usage\":{\"output_tokens\":120}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"; + +/// 上游读完输入要多久:响应头早就回了,第一个字在这之后 +const PREFILL: Duration = Duration::from_millis(300); + +async fn listen(app: Router) -> SocketAddr { + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let a = l.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(l, app).await.unwrap() }); + a +} + +/// 一条流:开场帧马上发,读完输入之后一个字一个字地吐,最后报累计输出。 +fn streaming(frames_after_prefill: Vec<&'static [u8]>, first: &'static [u8]) -> Router { + Router::new().fallback(any(move || { + let frames = frames_after_prefill.clone(); + async move { + let body = async_stream::stream! { + yield Ok::<_, std::io::Error>(Bytes::from_static(first)); + tokio::time::sleep(PREFILL).await; + for f in frames { + yield Ok(Bytes::from_static(f)); + tokio::time::sleep(Duration::from_millis(100)).await; + } + }; + axum::response::Response::builder() + .header("content-type", "text/event-stream") + .body(axum::body::Body::from_stream(body)) + .unwrap() + } + })) +} + +fn cfg(upstream: SocketAddr, protocol: Protocol) -> Config { + Config { + clients: vec![Client { + name: "me".into(), + key: "tw-k".into(), + ..Default::default() + }], + providers: vec![Provider { + name: "up".into(), + base_url: format!("http://{upstream}"), + key: Some("sk-x".into()), + protocol: Some(protocol), + ..Default::default() + }], + ..Default::default() + } +} + +async fn serve(cfg: Config) -> (SocketAddr, Receiver) { + let state = tw_gateway::AppState::new(cfg).unwrap(); + let events = state.bus.subscribe(); + let addr = tw_gateway::serve(state, ([127, 0, 0, 1], 0).into()) + .await + .unwrap(); + tokio::time::sleep(Duration::from_millis(50)).await; + (addr, events) +} + +/// 一个请求从开始到结局的全部事件 +async fn until_finished(rx: &mut Receiver) -> Vec { + let mut got = Vec::new(); + let deadline = tokio::time::Instant::now() + Duration::from_secs(10); + while let Ok(Ok(ev)) = tokio::time::timeout_at(deadline, rx.recv()).await { + let end = matches!( + ev, + Event::RequestFinished { .. } + | Event::RequestFailed { .. } + | Event::RequestCancelled { .. } + ); + got.push(ev); + if end { + break; + } + } + got +} + +/// (响应头,第一个 token,总耗时,速度) +fn timings(got: &[Event]) -> (Option, Option, u64, Option) { + let ttfb = got.iter().find_map(|e| match e { + Event::RequestHeaders { ttfb_ms, .. } => Some(*ttfb_ms), + _ => None, + }); + let ttft = got.iter().find_map(|e| match e { + Event::RequestFirstToken { ttft_ms, .. } => Some(*ttft_ms), + _ => None, + }); + let Some(Event::RequestFinished { + duration_ms, + tokens_per_sec, + .. + }) = got.last() + else { + panic!("该以一条结束收尾:{got:?}"); + }; + (ttfb, ttft, *duration_ms, *tokens_per_sec) +} + +/// **响应头和第一个 token 是两个时刻。**流式的响应头一收到请求就回,第一个字要等上游 +/// 读完输入;速度从第一个字算到结束 —— 从响应头算的话,读输入的那 300 毫秒会被当成 +/// 生成的时间 +#[tokio::test] +async fn a_stream_opens_after_its_headers_and_its_rate_counts_from_there() { + let mut frames = vec![TEXT_BLOCK, TEXT_DELTA]; + frames.extend([TEXT_DELTA; 5]); + frames.push(MESSAGE_END); + let up = listen(streaming(frames, MESSAGE_START)).await; + let (gw, mut rx) = serve(cfg(up, Protocol::Anthropic)).await; + let text = reqwest::Client::new() + .post(format!("http://{gw}/v1/messages")) + .header("x-api-key", "tw-k") + .body(r#"{"model":"claude-sonnet-5","stream":true,"messages":[]}"#) + .send() + .await + .unwrap() + .text() + .await + .unwrap(); + assert!(text.contains("message_stop"), "{text}"); + + let got = until_finished(&mut rx).await; + let (ttfb, ttft, duration, rate) = timings(&got); + let (ttfb, ttft) = (ttfb.expect("没有响应头"), ttft.expect("没有第一个 token")); + assert!( + ttfb < PREFILL.as_millis() as u64, + "响应头该在读输入之前:{ttfb}" + ); + assert!( + ttft >= PREFILL.as_millis() as u64, + "第一个 token 早于第一个字:{ttft}" + ); + assert_eq!( + got.iter() + .filter(|e| matches!(e, Event::RequestFirstToken { .. })) + .count(), + 1, + "{got:?}" + ); + assert_eq!( + rate, + Some((120 * 1000 / (duration - ttft)) as u32), + "{got:?}" + ); +} + +/// 整段一起到的:响应头要等生成完才回,没有「第一个」。**不给速度** —— 以前从响应头 +/// 算,总耗时减去响应头只剩几毫秒,这一条就是几万 token/秒 +#[tokio::test] +async fn a_whole_response_has_no_first_token_and_no_rate() { + let up = listen(Router::new().fallback(any(|| async { + tokio::time::sleep(PREFILL).await; + axum::response::Response::builder() + .header("content-type", "application/json") + .body(axum::body::Body::from( + r#"{"type":"message","role":"assistant","content":[{"type":"text","text":"hi"}],"usage":{"input_tokens":50,"output_tokens":500}}"#, + )) + .unwrap() + }))) + .await; + let (gw, mut rx) = serve(cfg(up, Protocol::Anthropic)).await; + reqwest::Client::new() + .post(format!("http://{gw}/v1/messages")) + .header("x-api-key", "tw-k") + .body(r#"{"model":"claude-sonnet-5","messages":[]}"#) + .send() + .await + .unwrap() + .text() + .await + .unwrap(); + + let got = until_finished(&mut rx).await; + let (ttfb, ttft, _, rate) = timings(&got); + assert!(ttfb.is_some(), "{got:?}"); + assert_eq!((ttft, rate), (None, None), "{got:?}"); +} + +/// **推理被隐藏的**(Chat Completions 的推理模型):第一个字之前模型想了半天,一个字 +/// 都没吐,用量里的 2000 个推理 token 生成在分母之外。扣掉它们,剩下 20 个是在第一个字 +/// 之后吐的 +#[tokio::test] +async fn hidden_reasoning_is_left_out_of_the_rate() { + const DELTA: &[u8] = + b"data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"word \"}}]}\n\n"; + const START: &[u8] = + b"data: {\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\"}}]}\n\n"; + const END: &[u8] = b"data: {\"choices\":[],\"usage\":{\"prompt_tokens\":10,\"completion_tokens\":2020,\"completion_tokens_details\":{\"reasoning_tokens\":2000}}}\n\ndata: [DONE]\n\n"; + let mut frames = vec![DELTA; 6]; + frames.push(END); + let up = listen(streaming(frames, START)).await; + let (gw, mut rx) = serve(cfg(up, Protocol::OpenaiChat)).await; + reqwest::Client::new() + .post(format!("http://{gw}/v1/chat/completions")) + .bearer_auth("tw-k") + .body(r#"{"model":"o5","stream":true,"messages":[{"role":"user","content":"hi"}]}"#) + .send() + .await + .unwrap() + .text() + .await + .unwrap(); + + let got = until_finished(&mut rx).await; + let (_, ttft, duration, rate) = timings(&got); + let ttft = ttft.expect("没有第一个 token"); + assert!(ttft >= PREFILL.as_millis() as u64, "{ttft}"); + assert_eq!( + rate, + Some((20 * 1000 / (duration - ttft)) as u32), + "{got:?}" + ); +} diff --git a/crates/tw-observe/src/bus.rs b/crates/tw-observe/src/bus.rs index 34865766..7807cec8 100644 --- a/crates/tw-observe/src/bus.rs +++ b/crates/tw-observe/src/bus.rs @@ -33,9 +33,9 @@ pub struct EventBus { struct Tally { /// 开始了、还没有结局的请求,按 id open: BTreeMap, - /// 在跑的请求首字节用了多久,毫秒。生成用时要从总耗时里减掉它 - ttfb: HashMap, - /// 最近跑完的:(什么时候结束的,输出了多少 token,生成用了多少毫秒) + /// 在跑的请求第一个 token 用了多久,毫秒。生成用时要从总耗时里减掉它 + ttft: HashMap, + /// 最近跑完的:(什么时候结束的,第一个 token 之后吐了多少 token,生成用了多少毫秒) done: VecDeque<(Instant, u64, u64)>, } @@ -57,6 +57,7 @@ fn about_the_request(ev: &tw_api::Event) -> bool { use tw_api::Event as E; match ev { E::RequestHeaders { .. } + | E::RequestFirstToken { .. } | E::RequestRouted { .. } | E::Translated { .. } | E::SecretsFound { .. } @@ -182,33 +183,35 @@ impl EventBus { }, ); } - E::RequestHeaders { id, ttfb_ms, .. } => { + E::RequestFirstToken { id, ttft_ms } => { if let Some(o) = t.open.get_mut(id) { o.events.push(ev.clone()); - t.ttfb.insert(*id, *ttfb_ms); + t.ttft.insert(*id, *ttft_ms); } } E::RequestFinished { id, duration_ms, - usage, + tokens_per_sec, .. } => { t.open.remove(id); - let ttfb = t.ttfb.remove(id); - // **只数跑完了的。**取消的、断掉的输出不全,拿来算速率只会偏低; - // 没有响应头的(WebSocket)不知道生成用了多久,不瞎算 - if let (Some(u), Some(ttfb)) = (usage, ttfb) { - let gen_ms = duration_ms.saturating_sub(ttfb); - if u.output > 0 && gen_ms > 0 { - t.done.push_back((now, u.output, gen_ms)); + let ttft = t.ttft.remove(id); + // **只数有速度的。**速度怎么算、什么时候没有,由网关在结局里定(见 + // `RequestFinished::tokens_per_sec`):非流式的没有第一个 token,取消的、 + // 断掉的输出不全。这里只按生成用的时间把它们合起来 + if let (Some(rate), Some(ttft)) = (tokens_per_sec, ttft) { + let gen_ms = duration_ms.saturating_sub(ttft); + if *rate > 0 && gen_ms > 0 { + t.done + .push_back((now, u64::from(*rate) * gen_ms / 1000, gen_ms)); } } t.forget(now); } E::RequestFailed { id, .. } | E::RequestCancelled { id, .. } => { t.open.remove(id); - t.ttfb.remove(id); + t.ttft.remove(id); } // 别的事件挂着的 id 要么是一个请求的,要么是它自己取的号 —— 号从同一个 // 计数器里取,不会和一个在跑的请求撞上 @@ -253,8 +256,8 @@ impl EventBus { /// 此刻的实时读数:在跑的请求(和 [`EventBus::in_flight`] 同一批),和最近 /// 一分钟跑完的请求平均每秒生成多少 token。 /// - /// **量的是生成的快慢**:每个请求的输出除以它生成用的时间(总耗时减去首字节), - /// 按 token 加权。拿「一分钟里输出了多少」去除以六十的话,一个跑了一分钟才 + /// **量的是生成的快慢**:每个请求的速度按它生成用的时间(总耗时减去第一个 token 的 + /// 时刻)加权,也就是吐出的 token 合计除以生成用的时间合计。拿「一分钟里输出了多少」去除以六十的话,一个跑了一分钟才 /// 结束的长请求,要等它结束之后才把速率一次性摊进来,数字跟着请求的长短忽高 /// 忽低。 pub fn live(&self) -> tw_api::LiveView { @@ -371,6 +374,7 @@ mod tests { bytes: 0, duration_ms: 0, usage: None, + tokens_per_sec: None, }); b.emit(tw_api::Event::RequestFailed { id: 2, @@ -436,7 +440,7 @@ mod tests { } } - /// 半路才来的一方要的是**每个在跑的请求到目前为止的全部**:开始、响应头、路由、 + /// 半路才来的一方要的是**每个在跑的请求到目前为止的全部**:开始、响应头、第一个 token、路由、 /// 防护的记录,按发生的先后 —— 只给开始的话,那一行没有状态码、画不到上游。 /// 说上游现状的额度不跟着请求走;结束了的整条不在 #[test] @@ -444,7 +448,12 @@ mod tests { let b = EventBus::new(); b.emit(started(1)); b.emit(started(2)); - b.emit(headers(1, 30)); + b.emit(tw_api::Event::RequestHeaders { + id: 1, + status: 200, + ttfb_ms: 30, + }); + b.emit(first_token(1, 45)); b.emit(tw_api::Event::QuotaSeen { id: 1, provider: "p".into(), @@ -468,7 +477,7 @@ mod tests { state: tw_api::BreakerState::Open, at_ms: 0, }); - b.emit(finished(2, 10, 1)); + b.emit(finished(2, 10, None)); let snap = b.in_flight(); assert!( @@ -483,12 +492,16 @@ mod tests { .map(|e| match e { tw_api::Event::RequestStarted { .. } => "started", tw_api::Event::RequestHeaders { .. } => "headers", + tw_api::Event::RequestFirstToken { .. } => "first token", tw_api::Event::RequestRouted { .. } => "routed", tw_api::Event::Translated { .. } => "translated", _ => "other", }) .collect(); - assert_eq!(kinds, ["started", "headers", "routed", "translated"]); + assert_eq!( + kinds, + ["started", "headers", "first token", "routed", "translated"] + ); } /// 没有订阅者的时候照样记 —— 这份快照就是给还没来的订阅者准备的。 @@ -511,15 +524,11 @@ mod tests { ); } - fn headers(id: u64, ttfb_ms: u64) -> tw_api::Event { - tw_api::Event::RequestHeaders { - id, - status: 200, - ttfb_ms, - } + fn first_token(id: u64, ttft_ms: u64) -> tw_api::Event { + tw_api::Event::RequestFirstToken { id, ttft_ms } } - fn finished(id: u64, duration_ms: u64, output: u64) -> tw_api::Event { + fn finished(id: u64, duration_ms: u64, tokens_per_sec: Option) -> tw_api::Event { tw_api::Event::RequestFinished { id, model: "m".into(), @@ -528,27 +537,28 @@ mod tests { duration_ms, usage: Some(tw_api::UsageView { input: 10, - output, + output: 100, ..Default::default() }), + tokens_per_sec, } } - /// **量的是生成的快慢**:首字节之前那一段不算,几个请求按 token 加权。 + /// **几个请求按生成用的时间加权**:吐出的 token 合计除以生成用的时间合计。 #[test] - fn the_rate_is_output_over_generation_time() { + fn the_rate_weighs_each_request_by_its_generation_time() { let b = EventBus::new(); let now = Instant::now(); - // 首字节 1 秒,之后 2 秒生成了 100 个 + // 第一个 token 在 1 秒,之后 2 秒、每秒 50 个 b.track_at(&started(1), now); - b.track_at(&headers(1, 1_000), now); - b.track_at(&finished(1, 3_000, 100), now); + b.track_at(&first_token(1, 1_000), now); + b.track_at(&finished(1, 3_000, Some(50)), now); assert_eq!(b.live_at(now).tokens_per_sec, Some(50)); - // 又一个:1 秒生成了 50 个。合起来 150 个 / 3 秒 + // 又一个:1 秒、每秒 200 个。合起来 300 个 / 3 秒,不是两个速度的平均 125 b.track_at(&started(2), now); - b.track_at(&headers(2, 500), now); - b.track_at(&finished(2, 1_500, 50), now); - assert_eq!(b.live_at(now).tokens_per_sec, Some(50)); + b.track_at(&first_token(2, 500), now); + b.track_at(&finished(2, 1_500, Some(200)), now); + assert_eq!(b.live_at(now).tokens_per_sec, Some(100)); } /// 一分钟之前跑完的不算;**没有就是没有**,不是 0 @@ -558,22 +568,31 @@ mod tests { let then = Instant::now(); assert_eq!(b.live_at(then).tokens_per_sec, None); b.track_at(&started(1), then); - b.track_at(&headers(1, 100), then); - b.track_at(&finished(1, 1_100, 40), then); + b.track_at(&first_token(1, 100), then); + b.track_at(&finished(1, 1_100, Some(40)), then); assert_eq!(b.live_at(then).tokens_per_sec, Some(40)); let later = then + RATE_WINDOW + Duration::from_secs(1); assert_eq!(b.live_at(later).tokens_per_sec, None); } - /// 没有响应头的(WebSocket)、失败和取消的,都不拿来算速率 + /// 没有速度的(非流式:响应头要等整段生成完才到,没有第一个 token)、取消的,都不 + /// 拿来算。**非流式的混进来会把数顶上天**:总耗时减去响应头只剩读 body 的几毫秒 #[test] - fn only_finished_requests_with_their_headers_make_a_rate() { + fn only_requests_with_a_rate_make_the_rate() { let b = EventBus::new(); let now = Instant::now(); b.track_at(&started(1), now); - b.track_at(&finished(1, 2_000, 100), now); + b.track_at( + &tw_api::Event::RequestHeaders { + id: 1, + status: 200, + ttfb_ms: 1_995, + }, + now, + ); + b.track_at(&finished(1, 2_000, None), now); b.track_at(&started(2), now); - b.track_at(&headers(2, 100), now); + b.track_at(&first_token(2, 100), now); b.track_at( &tw_api::Event::RequestCancelled { id: 2, @@ -682,6 +701,7 @@ mod tests { bytes: 0, duration_ms: 0, usage: None, + tokens_per_sec: None, }); assert_eq!(b.subscriber_count(), 0); } @@ -697,6 +717,7 @@ mod tests { bytes: 1, duration_ms: 2, usage: None, + tokens_per_sec: None, }); assert_eq!(rx.recv().await.unwrap().id(), 42); } @@ -722,6 +743,7 @@ mod tests { bytes: 0, duration_ms: 0, usage: None, + tokens_per_sec: None, }); } // 生产端全程没阻塞;消费端会收到一个 Lagged @@ -744,6 +766,7 @@ mod tests { bytes: 0, duration_ms: 0, usage: None, + tokens_per_sec: None, }); assert_eq!(a.recv().await.unwrap().id(), 9); assert_eq!(c.recv().await.unwrap().id(), 9); diff --git a/crates/tw-store/src/db.rs b/crates/tw-store/src/db.rs index 55427fcc..375992e2 100644 --- a/crates/tw-store/src/db.rs +++ b/crates/tw-store/src/db.rs @@ -22,7 +22,7 @@ use tw_api::Msg; /// /// **一列 JSON 的样子变了也算**(比如 `routing` 多了必有的字段):旧的那些行 /// 读出来是坏的,而读的一方会把「解不开」当成「没有」。 -const SCHEMA: i64 = 21; +const SCHEMA: i64 = 22; /// 这一行算不出钱,**因为价目表里没有这个模型**:用量是有的,缺的是单价。 /// @@ -84,8 +84,14 @@ pub struct RequestRow { pub path: String, /// 没走到上游就失败时是 None pub status: Option, + /// 响应头到的时刻 pub ttfb_ms: Option, + /// 第一个 token 到的时刻。只有流式的有(`tw_api::Event::RequestFirstToken`) + pub ttft_ms: Option, pub duration_ms: Option, + /// 生成速度,token/秒。网关在结局里算好的(`RequestFinished::tokens_per_sec`), + /// 只有跑完的流式请求有 + pub tokens_per_sec: Option, pub bytes: Option, pub input_tokens: Option, pub output_tokens: Option, @@ -230,7 +236,13 @@ impl Db { path TEXT NOT NULL, status INTEGER, ttfb_ms INTEGER, + -- 第一个 token 到的时刻。**和响应头是两个时刻**:流式响应的响应头一般 + -- 一收到请求就回,用户等的是这一个。非流式的没有 + ttft_ms INTEGER, duration_ms INTEGER, + -- 生成速度,token/秒。**在记录的时候就定下**:推理被隐藏时要扣掉推理 + -- token,而那只有看着流的网关知道,事后从这几列推不回来 + tokens_per_sec INTEGER, bytes INTEGER, input_tokens INTEGER, output_tokens INTEGER, @@ -301,8 +313,9 @@ impl Db { input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost_micros, cost_estimated, error, local, routing, billing, cache_saved_micros, client_hint, session, cancelled, price_source, translated, - error_code, error_args, peer, key_masked, session_log_bytes) - 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,?27,?28,?29,?30,?31)", + error_code, error_args, peer, key_masked, session_log_bytes, + ttft_ms, tokens_per_sec) + 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,?27,?28,?29,?30,?31,?32,?33)", params![ r.id, r.at_ms, @@ -338,6 +351,8 @@ impl Db { r.peer, r.key_masked, r.session_log_bytes, + r.ttft_ms, + r.tokens_per_sec, ], )?; Ok(()) @@ -670,16 +685,19 @@ impl Db { }) } - /// 某段时间内每个模型的延迟分位数。 + /// 某段时间内每个模型第一个 token 到的时刻的分位数。 /// /// **用分位数不用平均值**:AI 延迟是长尾分布,平均值会被极端 /// 值拉偏。**样本数一起返回** —— 「800ms」是 3 个样本还是 300 个, /// 含义完全不同。 + /// + /// **只有流式的有样本。**非流式的整段一起到:它的「第一个 token」就是总耗时,混进来 + /// 的话,一个跑了三十秒的长回答会让这个模型看起来要等三十秒才开口。 pub fn latency_by_model(&self, since_ms: i64, until_ms: i64) -> Result, DbError> { let mut st = self.conn.prepare( - "SELECT model, ttfb_ms FROM requests - WHERE at_ms >= ?1 AND at_ms < ?2 AND local = 0 AND ttfb_ms IS NOT NULL - ORDER BY model, ttfb_ms", + "SELECT model, ttft_ms FROM requests + WHERE at_ms >= ?1 AND at_ms < ?2 AND local = 0 AND ttft_ms IS NOT NULL + ORDER BY model, ttft_ms", )?; let rows = st.query_map(params![since_ms, until_ms], |r| { Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)) @@ -846,7 +864,7 @@ impl Db { )?) } - /// 按上游分的延迟分位数。 + /// 按上游分的延迟分位数。样本和按模型分的一样,只有流式的。 /// /// **和按模型分是两个问题。**「哪个模型慢」和「哪家上游慢」的下一步 /// 完全不同:前者换模型,后者换上游。合成一张表的话两个问题都答不好 @@ -857,10 +875,10 @@ impl Db { until_ms: i64, ) -> Result, DbError> { let mut st = self.conn.prepare( - "SELECT provider, ttfb_ms FROM requests - WHERE at_ms >= ?1 AND at_ms < ?2 AND local = 0 AND ttfb_ms IS NOT NULL + "SELECT provider, ttft_ms FROM requests + WHERE at_ms >= ?1 AND at_ms < ?2 AND local = 0 AND ttft_ms IS NOT NULL AND provider <> '' - ORDER BY provider, ttfb_ms", + ORDER BY provider, ttft_ms", )?; let rows = st.query_map(params![since_ms, until_ms], |r| { Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)) @@ -881,6 +899,58 @@ impl Db { .collect()) } + /// 某段时间内每个模型的生成速度中位数,token/秒。 + /// + /// 和延迟一样用分位数、带样本数。样本是有速度的请求:跑完的流式请求(见 + /// `tokens_per_sec` 那一列)。 + pub fn token_rate_by_model( + &self, + since_ms: i64, + until_ms: i64, + ) -> Result, DbError> { + self.token_rate("model", since_ms, until_ms) + } + + /// 按上游分的生成速度中位数。**和按模型分是两个问题**,理由同延迟。 + pub fn token_rate_by_provider( + &self, + since_ms: i64, + until_ms: i64, + ) -> Result, DbError> { + self.token_rate("provider", since_ms, until_ms) + } + + /// `by` 只会是上面两个调用方给的列名,不来自外面 + fn token_rate( + &self, + by: &str, + since_ms: i64, + until_ms: i64, + ) -> Result, DbError> { + let mut st = self.conn.prepare(&format!( + "SELECT {by}, tokens_per_sec FROM requests + WHERE at_ms >= ?1 AND at_ms < ?2 AND local = 0 AND tokens_per_sec IS NOT NULL + AND {by} <> '' + ORDER BY {by}, tokens_per_sec" + ))?; + let rows = st.query_map(params![since_ms, until_ms], |r| { + Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)) + })?; + let mut by: std::collections::BTreeMap> = Default::default(); + for row in rows { + let (m, t) = row?; + by.entry(m).or_default().push(t); + } + Ok(by + .into_iter() + .map(|(model, xs)| TokenRate { + p50: percentile(&xs, 50).clamp(0, i64::from(u32::MAX)) as u32, + samples: xs.len(), + model, + }) + .collect()) + } + /// 按时间分桶的花费与请求数(概览的趋势图)。 /// /// **桶宽由调用方给,不在这里猜。**同一段数据,看「今天每小时」和 @@ -1190,7 +1260,9 @@ fn row_from(r: &rusqlite::Row) -> rusqlite::Result { path: r.get("path")?, status: r.get::<_, Option>("status")?.map(|s| s as u16), ttfb_ms: r.get("ttfb_ms")?, + ttft_ms: r.get("ttft_ms")?, duration_ms: r.get("duration_ms")?, + tokens_per_sec: r.get("tokens_per_sec")?, bytes: r.get("bytes")?, input_tokens: r.get("input_tokens")?, output_tokens: r.get("output_tokens")?, @@ -1319,6 +1391,14 @@ pub struct Latency { pub samples: usize, } +/// 生成速度的中位数。`model` 在按上游分的那个查询里是上游名 +#[derive(Debug, Clone, PartialEq)] +pub struct TokenRate { + pub model: String, + pub p50: u32, + pub samples: usize, +} + #[cfg(test)] pub(crate) mod tests { use super::*; @@ -1345,8 +1425,10 @@ pub(crate) mod tests { model: "claude-sonnet-4-5".into(), path: "/v1/messages".into(), status: Some(200), - ttfb_ms: Some(800), + ttfb_ms: Some(300), + ttft_ms: Some(800), duration_ms: Some(4000), + tokens_per_sec: Some(156), bytes: Some(12345), input_tokens: Some(1000), output_tokens: Some(500), @@ -1595,12 +1677,16 @@ pub(crate) mod tests { let mut r = row(1, 1); r.status = None; r.ttfb_ms = None; + r.ttft_ms = None; + r.tokens_per_sec = None; r.cost_micros = None; r.input_tokens = None; db.insert(&r).unwrap(); let got = db.get(1).unwrap().unwrap(); assert_eq!(got.status, None); assert_eq!(got.ttfb_ms, None); + assert_eq!(got.ttft_ms, None); + assert_eq!(got.tokens_per_sec, None); assert_eq!(got.cost_micros, None); assert_eq!(got.input_tokens, None); } @@ -1660,6 +1746,7 @@ pub(crate) mod tests { let mut probe = row(2, 200); probe.local = true; probe.ttfb_ms = Some(0); + probe.ttft_ms = Some(0); probe.cost_micros = Some(0); probe.input_tokens = Some(0); db.insert(&probe).unwrap(); @@ -1680,7 +1767,7 @@ pub(crate) mod tests { let db = Db::in_memory().unwrap(); for (i, t) in (1..=100).enumerate() { let mut r = row(i as i64 + 1, 1000); - r.ttfb_ms = Some(t * 10); + r.ttft_ms = Some(t * 10); db.insert(&r).unwrap(); } let lat = db.latency_by_model(0, 10_000).unwrap(); @@ -1698,11 +1785,11 @@ pub(crate) mod tests { let db = Db::in_memory().unwrap(); for i in 1..=99 { let mut r = row(i, 1000); - r.ttfb_ms = Some(500); + r.ttft_ms = Some(500); db.insert(&r).unwrap(); } let mut slow = row(100, 1000); - slow.ttfb_ms = Some(60_000); + slow.ttft_ms = Some(60_000); db.insert(&slow).unwrap(); let lat = db.latency_by_model(0, 10_000).unwrap(); assert_eq!(lat[0].p50, 500, "一个慢请求不该动 p50"); @@ -1713,10 +1800,10 @@ pub(crate) mod tests { let db = Db::in_memory().unwrap(); let mut a = row(1, 1000); a.model = "claude-opus-4".into(); - a.ttfb_ms = Some(3000); + a.ttft_ms = Some(3000); let mut b = row(2, 1000); b.model = "claude-3-5-haiku".into(); - b.ttfb_ms = Some(300); + b.ttft_ms = Some(300); db.insert(&a).unwrap(); db.insert(&b).unwrap(); let lat = db.latency_by_model(0, 10_000).unwrap(); @@ -1725,6 +1812,83 @@ pub(crate) mod tests { assert_eq!(opus.p50, 3000); } + /// **延迟看第一个 token,不看响应头。**非流式的没有第一个 token,不进样本:它的 + /// 响应头要等整段生成完才到,混进来的话这个模型看起来要等几十秒才开口 + #[test] + fn latency_is_the_first_token_and_leaves_non_streaming_requests_out() { + let db = Db::in_memory().unwrap(); + let mut streamed = row(1, 1000); + streamed.ttfb_ms = Some(200); + streamed.ttft_ms = Some(1_200); + let mut whole = row(2, 1000); + whole.ttfb_ms = Some(30_000); + whole.ttft_ms = None; + whole.tokens_per_sec = None; + db.insert(&streamed).unwrap(); + db.insert(&whole).unwrap(); + let lat = db.latency_by_model(0, 10_000).unwrap(); + assert_eq!((lat[0].p50, lat[0].samples), (1_200, 1), "{lat:?}"); + let by_provider = db.latency_by_provider(0, 10_000).unwrap(); + assert_eq!((by_provider[0].p50, by_provider[0].samples), (1_200, 1)); + } + + /// 生成速度按模型、按上游各给中位数和样本数;没有速度的请求(非流式、本地应答) + /// 不进样本 + #[test] + fn token_rate_is_the_median_by_model_and_by_upstream() { + let db = Db::in_memory().unwrap(); + for (id, model, provider, rate) in [ + (1, "sonnet", "anthropic", Some(80)), + (2, "sonnet", "anthropic", Some(90)), + (3, "sonnet", "openrouter", Some(120)), + (4, "haiku", "anthropic", Some(200)), + (5, "haiku", "anthropic", None), + ] { + let mut r = row(id, 1000); + r.model = model.into(); + r.provider = provider.into(); + r.tokens_per_sec = rate; + db.insert(&r).unwrap(); + } + let mut probe = row(6, 1000); + probe.local = true; + probe.tokens_per_sec = Some(9_999); + db.insert(&probe).unwrap(); + + let by_model = db.token_rate_by_model(0, 10_000).unwrap(); + assert_eq!( + by_model, + vec![ + TokenRate { + model: "haiku".into(), + p50: 200, + samples: 1 + }, + TokenRate { + model: "sonnet".into(), + p50: 90, + samples: 3 + }, + ] + ); + let by_provider = db.token_rate_by_provider(0, 10_000).unwrap(); + assert_eq!( + by_provider, + vec![ + TokenRate { + model: "anthropic".into(), + p50: 90, + samples: 3 + }, + TokenRate { + model: "openrouter".into(), + p50: 120, + samples: 1 + }, + ] + ); + } + #[test] fn a_time_window_excludes_what_is_outside_it() { let db = Db::in_memory().unwrap(); diff --git a/crates/tw-store/src/lib.rs b/crates/tw-store/src/lib.rs index e16c7043..8c038230 100644 --- a/crates/tw-store/src/lib.rs +++ b/crates/tw-store/src/lib.rs @@ -14,7 +14,7 @@ pub mod recorder; pub mod task; pub use blobs::{Blobs, Which}; -pub use db::{Db, DbError, Latency, RequestRow, SecurityEvent, Summary}; +pub use db::{Db, DbError, Latency, RequestRow, SecurityEvent, Summary, TokenRate}; pub use recorder::{Recorder, price_source}; pub use task::StoredBody; diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index 916462d8..23022bff 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -28,6 +28,8 @@ struct Partial { path: String, status: Option, ttfb_ms: Option, + /// 第一个 token 到的时刻。流式的才有 + ttft_ms: Option, /// 路由决策。**开始事件就带着第一阶段的结论**(路由、规则、策略组、改写), /// 尝试链走完之后路由事件换成终稿 —— 等不到路由事件的请求(上游应答之前 /// 客户端就走了)也说得出它走的是哪条路由、哪条规则 @@ -54,7 +56,10 @@ const MAX_INFLIGHT: usize = 4096; /// 一个请求是怎么结束的。**三种结局落同一张表、走同一条算钱的路**,只在 /// 这几处不同:失败有 `error`,取消有 `cancelled`,没跑完的金额是估算。 enum Ending<'a> { - Finished, + /// 跑完了,带着网关算好的生成速度 + Finished { + tokens_per_sec: Option, + }, Cancelled, Failed(&'a tw_api::Msg), } @@ -142,7 +147,9 @@ impl Recorder { path: p.path.clone(), status: p.status, ttfb_ms: p.ttfb_ms, + ttft_ms: p.ttft_ms, duration_ms: None, + tokens_per_sec: None, bytes: None, input_tokens: None, output_tokens: None, @@ -216,6 +223,7 @@ impl Recorder { path: path.clone(), status: None, ttfb_ms: None, + ttft_ms: None, routing: tw_api::RoutingView { route: route.clone(), rule: rule.clone(), @@ -447,6 +455,11 @@ impl Recorder { p.ttfb_ms = Some(*ttfb_ms as i64); } } + Event::RequestFirstToken { id, ttft_ms } => { + if let Some(p) = self.inflight.get_mut(id) { + p.ttft_ms = Some(*ttft_ms as i64); + } + } // 结局里的模型名不用:开始事件已经给过,这一行从那时就在 `inflight` 里 Event::RequestFinished { id, @@ -454,6 +467,7 @@ impl Recorder { bytes, duration_ms, usage, + tokens_per_sec, .. } => self.settle( *id, @@ -461,7 +475,9 @@ impl Recorder { Some(*bytes), Some(*duration_ms), *usage, - Ending::Finished, + Ending::Finished { + tokens_per_sec: *tokens_per_sec, + }, ), /* 客户端没等到响应结束就走了。 @@ -534,7 +550,9 @@ impl Recorder { path: probe.slug().to_string(), status: Some(200), ttfb_ms: Some(0), + ttft_ms: None, duration_ms: Some(0), + tokens_per_sec: None, bytes: None, input_tokens: None, output_tokens: None, @@ -617,7 +635,7 @@ impl Recorder { // **没跑完的一律按估算记**(取消、失败)。输出只算到断开那一刻,而 // Anthropic 在流的末尾才报累计输出 —— 断在中间时手里那个数是个 // 占位。按它算出来的钱只会偏低,当成实测会让「今日花费」悄悄少一截。 - let partial = !matches!(how, Ending::Finished); + let partial = !matches!(how, Ending::Finished { .. }); let book = self.pricing.load(); // **按这个请求实际走的上游查价** —— 同一个模型在不同上游不是同一个价 let resolved = if free { @@ -674,7 +692,12 @@ impl Recorder { path: p.path, status: status.or(p.status), ttfb_ms: p.ttfb_ms, + ttft_ms: p.ttft_ms, duration_ms: duration_ms.map(|d| d as i64), + tokens_per_sec: match how { + Ending::Finished { tokens_per_sec } => tokens_per_sec, + _ => None, + }, bytes: bytes.map(|b| b as i64), input_tokens: u.map(|u| u.input as i64), output_tokens: u.map(|u| u.output as i64), @@ -768,6 +791,7 @@ mod tests { bytes: 1234, duration_ms: 4000, usage, + tokens_per_sec: None, } } @@ -958,6 +982,71 @@ mod tests { assert_eq!(row.input_tokens, Some(1000)); } + /// 第一个 token 的时刻和网关算好的速度都落进这一行;非流式的两个都没有 + #[test] + fn the_first_token_and_the_rate_are_recorded() { + let (_d, mut r) = rec(); + r.on_event(&started(1, "claude-sonnet-4-5")); + r.on_event(&Event::RequestHeaders { + id: 1, + status: 200, + ttfb_ms: 300, + }); + r.on_event(&Event::RequestFirstToken { + id: 1, + ttft_ms: 1_200, + }); + let running = r.in_flight_row(1).unwrap(); + assert_eq!( + running.ttft_ms, + Some(1_200), + "在跑的那一行也该有第一个 token 的时刻" + ); + r.on_event(&Event::RequestFinished { + id: 1, + model: String::new(), + status: 200, + bytes: 1234, + duration_ms: 4000, + usage: None, + tokens_per_sec: Some(180), + }); + let row = r.db().get(1).unwrap().unwrap(); + assert_eq!((row.ttfb_ms, row.ttft_ms), (Some(300), Some(1_200))); + assert_eq!(row.tokens_per_sec, Some(180)); + + r.on_event(&started(2, "claude-sonnet-4-5")); + r.on_event(&Event::RequestHeaders { + id: 2, + status: 200, + ttfb_ms: 3_900, + }); + r.on_event(&finished(2, None)); + let row = r.db().get(2).unwrap().unwrap(); + assert_eq!((row.ttft_ms, row.tokens_per_sec), (None, None)); + } + + /// 取消的:第一个 token 确实到过,照记;输出不全,没有速度 + #[test] + fn a_cancelled_stream_keeps_its_first_token_but_has_no_rate() { + let (_d, mut r) = rec(); + r.on_event(&started(1, "claude-sonnet-4-5")); + r.on_event(&Event::RequestFirstToken { + id: 1, + ttft_ms: 900, + }); + r.on_event(&Event::RequestCancelled { + id: 1, + model: String::new(), + status: Some(200), + bytes: 10, + duration_ms: 3_000, + usage: None, + }); + let row = r.db().get(1).unwrap().unwrap(); + assert_eq!((row.ttft_ms, row.tokens_per_sec), (Some(900), None)); + } + #[test] fn a_real_model_gets_a_real_cost() { let (_d, mut r) = rec(); @@ -1284,6 +1373,7 @@ mod billing_tests { bytes: 2048, duration_ms: 600_000, usage: None, + tokens_per_sec: None, } } @@ -1748,7 +1838,11 @@ mod cache_saving_tests { r.on_event(&tw_api::Event::RequestHeaders { id, status: 200, - ttfb_ms: if id == 1 { 3000 } else { 300 }, + ttfb_ms: 100, + }); + r.on_event(&tw_api::Event::RequestFirstToken { + id, + ttft_ms: if id == 1 { 3000 } else { 300 }, }); r.on_event(&finished(id, None)); } diff --git a/crates/tw-store/tests/m3_acceptance.rs b/crates/tw-store/tests/m3_acceptance.rs index 5a803774..6af6f383 100644 --- a/crates/tw-store/tests/m3_acceptance.rs +++ b/crates/tw-store/tests/m3_acceptance.rs @@ -37,8 +37,10 @@ fn req(id: i64, at_ms: i64) -> RequestRow { model: "claude-sonnet-4-5".into(), path: "/v1/messages".into(), status: Some(200), - ttfb_ms: Some(800), + ttfb_ms: Some(300), + ttft_ms: Some(800), duration_ms: Some(4000), + tokens_per_sec: Some(156), bytes: Some(1000), input_tokens: Some(1000), output_tokens: Some(500), @@ -77,11 +79,12 @@ fn one_you_can_ask_what_yesterday_cost() { ); } -/// 验收二:**哪家 TTFT 最差。** +/// 验收二:**哪家 TTFT 最差。**看的是第一个 token,不是响应头:响应头一样快的两家, +/// 开口可以差好几秒 #[test] fn two_you_can_ask_which_upstream_has_the_worst_ttft() { let (_d, db) = open(); - for (i, p, ttfb) in [ + for (i, p, ttft) in [ (1i64, "官方", 300i64), (2, "官方", 320), (3, "中转", 2500), @@ -89,7 +92,8 @@ fn two_you_can_ask_which_upstream_has_the_worst_ttft() { ] { let mut r = req(i, NOW); r.provider = p.into(); - r.ttfb_ms = Some(ttfb); + r.ttfb_ms = Some(200); + r.ttft_ms = Some(ttft); db.insert(&r).unwrap(); } let mut by = db.latency_by_provider(0, NOW + 1).unwrap();