diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 74ecb822..9a1ac8c9 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -87,6 +87,16 @@ pub enum Event { /// 结束了 RequestFinished { id: u64, + /// 客户端要的模型名,和 `RequestStarted` 里的是同一个。 + /// + /// **三种结局都自己带着它。**听事件的一方不一定从请求开始时就在听 + /// —— 界面的窗口开着才订阅,概览打开时才挂上实时曲线 —— 而用量是 + /// 在结局里才到的。模型名只在开始事件里的话,一个开始时没人在听、 + /// 结束时有人在听的请求,它的用量就不知道该记在哪个模型上。 + /// + /// WebSocket 那条路是空串:升级请求里没有模型名(和开始事件一样)。 + #[serde(default)] + model: String, status: u16, bytes: u64, duration_ms: u64, @@ -101,6 +111,9 @@ pub enum Event { /// 崩掉了。它只出现在这里 —— 那时往往已经没有一个 HTTP 响应能带上它。 RequestFailed { id: u64, + /// 模型名。理由见 `RequestFinished::model` + #[serde(default)] + model: String, source: String, message: Msg, /// 失败之前从上游收到了多少字节。**响应头都没到的没有** @@ -133,6 +146,9 @@ pub enum Event { /// 没有状态码、没有字节、也没有用量。 RequestCancelled { id: u64, + /// 模型名。理由见 `RequestFinished::model` + #[serde(default)] + model: String, /// 上游的响应头还没到就走了的,**没有状态码** —— 不是 0 #[serde(default, skip_serializing_if = "Option::is_none")] status: Option, @@ -2782,6 +2798,7 @@ mod tests { // 前端按 `kind` 分派。少了它,TypeScript 那边只能靠字段有无来猜。 let e = Event::RequestFinished { id: 1, + model: "claude-sonnet-5".into(), status: 200, bytes: 10, duration_ms: 5, @@ -2790,6 +2807,8 @@ mod tests { let v: serde_json::Value = serde_json::to_value(&e).unwrap(); assert_eq!(v["kind"], "request_finished"); assert_eq!(v["id"], 1); + // 结局自己带着模型名:开始之后才来听的一方只有它 + assert_eq!(v["model"], "claude-sonnet-5"); } #[test] @@ -2814,6 +2833,7 @@ mod tests { }, Event::RequestFinished { id: 7, + model: String::new(), status: 200, bytes: 1, duration_ms: 1, @@ -2821,6 +2841,7 @@ mod tests { }, Event::RequestFailed { id: 7, + model: String::new(), source: "upstream".into(), message: tw_types::msg!("t.x" => "x"), bytes: None, @@ -2829,6 +2850,7 @@ mod tests { }, Event::RequestCancelled { id: 7, + model: String::new(), status: Some(200), bytes: 1, duration_ms: 1, @@ -2845,6 +2867,7 @@ mod tests { fn a_cancellation_carries_the_usage_seen_so_far() { let e = Event::RequestCancelled { id: 3, + model: String::new(), status: Some(200), bytes: 512, duration_ms: 2400, @@ -2866,6 +2889,7 @@ mod tests { // 响应头之前就走了的:状态码和用量都不出现,不是 0 let none = Event::RequestCancelled { id: 4, + model: String::new(), status: None, bytes: 0, duration_ms: 10, diff --git a/crates/tw-gateway/src/ending.rs b/crates/tw-gateway/src/ending.rs index e8592ad6..69f57cbe 100644 --- a/crates/tw-gateway/src/ending.rs +++ b/crates/tw-gateway/src/ending.rs @@ -35,6 +35,8 @@ use tw_types::{Msg, msg}; pub struct Ending { bus: tw_observe::EventBus, id: u64, + /// 客户端要的模型名。**结局带着它走**(理由见 `tw_api::Event::RequestFinished`) + model: String, started: Instant, /// 请求开始的时刻。响应体按它归档,和请求体那一份对得上 at_ms: i64, @@ -55,6 +57,7 @@ impl Ending { pub fn new( bus: tw_observe::EventBus, id: u64, + model: String, started: Instant, at_ms: i64, sink: Option, @@ -62,6 +65,7 @@ impl Ending { Self { bus, id, + model, started, at_ms, sink, @@ -102,6 +106,7 @@ impl Ending { let usage = self.settle(); 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(), @@ -117,6 +122,7 @@ impl Ending { let usage = self.settle(); self.bus.emit(tw_api::Event::RequestFailed { id: self.id, + model: std::mem::take(&mut self.model), source: source.to_string(), message, bytes: self.received(), @@ -169,6 +175,7 @@ impl Drop for Ending { if std::thread::panicking() { self.bus.emit(tw_api::Event::RequestFailed { id: self.id, + model: std::mem::take(&mut self.model), source: "internal".to_string(), message: msg!( "gw.internal" => "The request was interrupted by an error inside the gateway." @@ -181,6 +188,7 @@ impl Drop for Ending { } self.bus.emit(tw_api::Event::RequestCancelled { id: self.id, + model: std::mem::take(&mut self.model), status: self.status, bytes: self.bytes, duration_ms: self.duration_ms(), @@ -208,10 +216,11 @@ mod tests { /// Anthropic 流的第一帧:输入和缓存读是齐的,输出是个占位的 1。 const MESSAGE_START: &[u8] = b"event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":5000,\"cache_read_input_tokens\":4000,\"output_tokens\":1}}}\n\n"; const MESSAGE_DELTA: &[u8] = b"event: message_delta\ndata: {\"type\":\"message_delta\",\"usage\":{\"output_tokens\":777}}\n\n"; + const MODEL: &str = "claude-sonnet-5"; /// 一个响应头已经到了的请求。 fn responding(bus: &tw_observe::EventBus) -> Ending { - let mut e = Ending::new(bus.clone(), 7, Instant::now(), 1_000, None); + let mut e = Ending::new(bus.clone(), 7, MODEL.into(), Instant::now(), 1_000, None); e.responded(200); e } @@ -279,13 +288,37 @@ mod tests { } } + /// **三种结局都带着模型名。**听事件的一方可能是请求开始之后才来的(界面 + /// 的实时曲线就是这样),它手上只有结局 —— 这笔用量记在哪个模型上,只能 + /// 看结局里写的。 + #[test] + fn every_ending_carries_the_model() { + let bus = tw_observe::EventBus::new(); + let mut rx = bus.subscribe(); + responding(&bus).finished(200); + responding(&bus).failed("upstream", msg!("t.x" => "x")); + drop(responding(&bus)); + + let got = drain(&mut rx); + assert_eq!(got.len(), 3, "{got:?}"); + for e in &got { + let model = match e { + Event::RequestFinished { model, .. } + | Event::RequestFailed { model, .. } + | Event::RequestCancelled { model, .. } => model, + other => panic!("该是一个结局,实际 {other:?}"), + }; + assert_eq!(model, MODEL, "{e:?}"); + } + } + /// 响应头之前就失败了(每家上游都拒绝、策略不让)。**没有字节、没有 /// 用量,但有耗时** —— 「试了二十秒才放弃」本身就是排查的线索。 #[test] fn a_failure_before_the_response_headers_has_a_duration_but_no_bytes_or_usage() { let bus = tw_observe::EventBus::new(); let mut rx = bus.subscribe(); - Ending::new(bus.clone(), 7, Instant::now(), 1_000, None) + Ending::new(bus.clone(), 7, MODEL.into(), Instant::now(), 1_000, None) .failed("rate_limited", msg!("t.limited" => "`up` rate-limited us")); let got = drain(&mut rx); @@ -310,7 +343,14 @@ mod tests { let bus = tw_observe::EventBus::new(); let mut rx = bus.subscribe(); let (tx, mut bodies) = tokio::sync::mpsc::channel(4); - let mut e = Ending::new(bus.clone(), 7, Instant::now(), 1_000, Some(tx)); + let mut e = Ending::new( + bus.clone(), + 7, + MODEL.into(), + Instant::now(), + 1_000, + Some(tx), + ); e.responded(200); e.feed(MESSAGE_START); drop(e); @@ -344,7 +384,14 @@ mod tests { fn dropped_before_the_response_headers_it_reports_neither_a_status_nor_usage() { let bus = tw_observe::EventBus::new(); let mut rx = bus.subscribe(); - drop(Ending::new(bus.clone(), 7, Instant::now(), 1_000, None)); + drop(Ending::new( + bus.clone(), + 7, + MODEL.into(), + Instant::now(), + 1_000, + None, + )); let got = drain(&mut rx); assert!( @@ -367,7 +414,8 @@ mod tests { fn counting_bytes_does_not_turn_frames_into_usage() { let bus = tw_observe::EventBus::new(); let mut rx = bus.subscribe(); - let mut e = Ending::new(bus.clone(), 7, Instant::now(), 1_000, None); + // WebSocket 那条路不知道模型名 + let mut e = Ending::new(bus.clone(), 7, String::new(), Instant::now(), 1_000, None); e.responded(101); e.count(MESSAGE_START.len()); e.finished(101); @@ -408,7 +456,10 @@ mod tests { let got = drain(&mut rx); assert!( - matches!(got.as_slice(), [Event::RequestFailed { source, .. }] if source == "internal"), + matches!( + got.as_slice(), + [Event::RequestFailed { source, model, .. }] if source == "internal" && model == MODEL + ), "{got:?}" ); } diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index 383b51e2..7f2ba38b 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -1071,7 +1071,14 @@ async fn ws_upgrade( // 这条连接怎么断的,就是这个请求的结局。**跟着连接走**:升级没完成 // 就被丢掉的 —— 客户端没等到 101 就走了 —— 由 Drop 报成取消。WS 帧 // 不留档,所以没有 body 的去处 - let ending = crate::ending::Ending::new(state.bus.clone(), id, started, now_ms() as i64, None); + let ending = crate::ending::Ending::new( + state.bus.clone(), + id, + String::new(), + started, + now_ms() as i64, + None, + ); let provider = provider.clone(); let guard = decision.guard.clone(); let rules = rt.rules.clone(); @@ -1635,6 +1642,7 @@ async fn pipeline( *ending = Some(crate::ending::Ending::new( state.bus.clone(), id, + facts.model.clone(), started, at_ms, sink.clone(), diff --git a/crates/tw-gateway/tests/endings.rs b/crates/tw-gateway/tests/endings.rs index cc69b072..80515237 100644 --- a/crates/tw-gateway/tests/endings.rs +++ b/crates/tw-gateway/tests/endings.rs @@ -22,6 +22,9 @@ use tw_config::{Client, Config, Provider, Security, SecurityMode}; /// Anthropic 流的第一帧。**输入和缓存读在这里就是齐的**,输出是个占位的 /// 1 —— 累计输出要等流的末尾才报。 +/// 客户端要的模型名。**每一种结局都要带着它**(见 `model_of`) +const MODEL: &str = "claude-sonnet-4-5"; + const MESSAGE_START: &[u8] = b"event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":5000,\"cache_read_input_tokens\":4000,\"output_tokens\":1}}}\n\n"; async fn listen(app: Router) -> SocketAddr { @@ -212,7 +215,9 @@ fn post(gw: SocketAddr) -> reqwest::RequestBuilder { reqwest::Client::new() .post(format!("http://{gw}/v1/messages")) .header("x-api-key", "tw-k") - .body(r#"{"model":"claude-sonnet-4-5","stream":true,"messages":[]}"#) + .body(format!( + r#"{{"model":"{MODEL}","stream":true,"messages":[]}}"# + )) } async fn ws_connect( @@ -250,6 +255,20 @@ async fn endings(rx: &mut Receiver) -> Vec { got } +/// 结局上写的模型名。 +/// +/// **每一种结局都要带着它**:听事件的一方可能是请求开始之后才来的(界面的 +/// 实时曲线就是这样),它手上只有结局 —— 这笔用量记在哪个模型上,只能看 +/// 结局里写的。 +fn model_of(e: &Event) -> &str { + match e { + Event::RequestFinished { model, .. } + | Event::RequestFailed { model, .. } + | Event::RequestCancelled { model, .. } => model, + other => panic!("该是一个结局,实际 {other:?}"), + } +} + // ---------------------------------------------------------------- 流式响应开始之后 /// 跑完的流**只报结束**。Drop 那一侧不知道「已经报过了」的话,每一个正常 @@ -266,6 +285,7 @@ async fn a_stream_that_runs_to_its_end_is_finished_and_nothing_else() { matches!(&got[0], Event::RequestFinished { usage: Some(u), .. } if u.output == 777), "该是带着累计输出的结束:{got:?}" ); + assert_eq!(model_of(&got[0]), MODEL); } /// 客户端中途走了(Claude Code 里按一下 Esc)。 @@ -302,6 +322,7 @@ async fn a_client_that_walks_away_mid_stream_is_reported_once_as_cancelled() { } other => panic!("该是一次取消,实际 {other:?}"), } + assert_eq!(model_of(&got[0]), MODEL); } /// 上游中途断了:**报失败,不报取消**。网关随后往客户端补的那个错误帧, @@ -335,6 +356,7 @@ async fn a_stream_the_upstream_breaks_is_failed_and_not_also_cancelled() { } other => panic!("该是一次上游失败,实际 {other:?}"), } + assert_eq!(model_of(&got[0]), MODEL); } /// 防火墙切断了一个高危工具调用。**这是策略拦下来的,不是上游坏了**,而 @@ -400,6 +422,7 @@ async fn a_client_that_leaves_before_the_response_headers_is_reported_once_as_ca ), "该是一次没有状态码、没有用量的取消:{got:?}" ); + assert_eq!(model_of(&got[0]), MODEL); } /// 选中上游之后才生效的规则拒绝了这次请求(阶段二)。 @@ -442,6 +465,7 @@ async fn a_phase_two_deny_after_the_request_started_is_reported_as_denied() { ), "该是一次带着理由的拒绝:{got:?}" ); + assert_eq!(model_of(&got[0]), MODEL); } /// 每一家上游都没接住。**只报一次失败,`source` 是它真正的原因** —— 被限流 @@ -474,6 +498,7 @@ async fn a_request_every_upstream_refused_is_failed_once_for_the_reason_it_was_r } other => panic!("该是一次失败,实际 {other:?}"), } + assert_eq!(model_of(&got[0]), MODEL); } // ---------------------------------------------------------------- WebSocket @@ -511,6 +536,7 @@ async fn a_websocket_session_the_client_closes_is_finished() { ), "该是一次带着回帧字节数、没有用量的结束:{got:?}" ); + assert_eq!(model_of(&got[0]), "", "升级请求里没有模型名,不该编一个"); } #[tokio::test] diff --git a/crates/tw-observe/src/bus.rs b/crates/tw-observe/src/bus.rs index d6b80810..14a245cb 100644 --- a/crates/tw-observe/src/bus.rs +++ b/crates/tw-observe/src/bus.rs @@ -108,6 +108,7 @@ mod tests { let b = EventBus::new(); b.emit(tw_api::Event::RequestFinished { id: 1, + model: String::new(), status: 200, bytes: 0, duration_ms: 0, @@ -122,6 +123,7 @@ mod tests { let mut rx = b.subscribe(); b.emit(tw_api::Event::RequestFinished { id: 42, + model: String::new(), status: 200, bytes: 1, duration_ms: 2, @@ -146,6 +148,7 @@ mod tests { for i in 0..(CAPACITY as u64 + 100) { b.emit(tw_api::Event::RequestFinished { id: i, + model: String::new(), status: 200, bytes: 0, duration_ms: 0, @@ -167,6 +170,7 @@ mod tests { let mut c = b.subscribe(); b.emit(tw_api::Event::RequestFinished { id: 9, + model: String::new(), status: 200, bytes: 0, duration_ms: 0, diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index e5d449b6..c4c1a89c 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -288,12 +288,14 @@ impl Recorder { p.ttfb_ms = Some(*ttfb_ms as i64); } } + // 结局里的模型名不用:开始事件已经给过,这一行从那时就在 `inflight` 里 Event::RequestFinished { id, status, bytes, duration_ms, usage, + .. } => self.settle( *id, Some(*status), @@ -317,6 +319,7 @@ impl Recorder { bytes, duration_ms, usage, + .. } => self.settle( *id, *status, @@ -621,6 +624,7 @@ mod tests { pub(super) fn finished(id: u64, usage: Option) -> Event { Event::RequestFinished { id, + model: String::new(), status: 200, bytes: 1234, duration_ms: 4000, @@ -861,6 +865,7 @@ mod tests { r.on_event(&started(1, "claude-sonnet-4-5")); r.on_event(&Event::RequestFailed { id: 1, + model: String::new(), source: "upstream".into(), message: tw_api::Msg { code: "t.unreachable".into(), @@ -1290,6 +1295,7 @@ mod cancellation_tests { fn cancelled(id: u64, usage: Option) -> Event { Event::RequestCancelled { id, + model: String::new(), status: Some(200), bytes: 312, duration_ms: 2_500, @@ -1402,6 +1408,7 @@ mod cancellation_tests { r.on_event(&started(1, "claude-sonnet-4-5")); r.on_event(&Event::RequestCancelled { id: 1, + model: String::new(), status: None, bytes: 0, duration_ms: 12_000, @@ -1515,6 +1522,7 @@ mod failure_tests { fn failed(id: u64, usage: Option) -> Event { Event::RequestFailed { id, + model: String::new(), source: "upstream".into(), message: tw_api::Msg { code: "t.broke".into(), @@ -1592,6 +1600,7 @@ mod failure_tests { r.on_event(&started(1, "claude-sonnet-4-5")); r.on_event(&Event::RequestFailed { id: 1, + model: String::new(), source: "rate_limited".into(), message: tw_api::Msg { code: "t.limited".into(),