diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index c6f4511d..df2c4c9e 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -77,12 +77,34 @@ pub enum Event { #[serde(default, skip_serializing_if = "Option::is_none")] usage: Option, }, - /// 失败了。`source` 和 HTTP 响应里的 `x-thinkwatch-error` 是同一个词表。 + /// 失败了。`source` 和 HTTP 响应里的 `x-thinkwatch-error` 是同一个词表, + /// 另外多一个 `internal`:流在网关自己的代码里崩掉了。它只出现在这里 + /// —— 那时响应头早就发出去了,没有哪个 HTTP 头还能带上它。 RequestFailed { id: u64, source: String, message: String, }, + /// 客户端没等到响应结束就走了(Claude Code 里按一下 Esc)。 + /// + /// **不是失败,也不是正常结束,所以单独一个事件。**上游那时已经在计费 + /// 了 —— 输入全额,输出算到断开为止 —— 所以它带着到那一刻为止看到的 + /// 用量,存储层照样算钱。而它不能算进失败:上游什么都没做错,记成失败 + /// 会让一个常按 Esc 的用户看到一家「经常出错」的上游。 + /// + /// **用量停在断开那一刻。**输入通常是齐的(`message_start` 在流的最 + /// 前面),输出多半不是 —— Anthropic 只在流的末尾报累计输出,之前手里 + /// 那个数是个占位。按它算出来的钱只能是估算,而且只会偏低。 + RequestCancelled { + id: u64, + status: u16, + /// 断开之前从上游收到了多少字节 + bytes: u64, + duration_ms: u64, + /// **没嗅到就是 None,不是零** —— 客户端可能在第一帧之前就走了 + #[serde(default, skip_serializing_if = "Option::is_none")] + usage: Option, + }, /// 路由决定完了,尝试链也走完了。 /// /// **单独一个事件,因为成功和失败两条路都要发它。**挂在 @@ -358,6 +380,7 @@ impl Event { | Event::RequestHeaders { id, .. } | Event::RequestFinished { id, .. } | Event::RequestFailed { id, .. } + | Event::RequestCancelled { id, .. } | Event::LocallyAnswered { id, .. } | Event::ConfigReloaded { id, .. } | Event::ConfigRejected { id, .. } @@ -1013,6 +1036,10 @@ pub struct HistoryRow { pub error: Option, /// 本地应答的 pub local: bool, + /// 客户端没等到响应结束就走了。**不是失败**(`error` 是空的);用量 + /// 只算到断开那一刻,所以有金额的话一定是估算 + #[serde(default)] + pub cancelled: bool, /// 服务它的那家怎么收钱:`per-token` / `subscription` / `unknown` #[serde(default)] pub billing: String, @@ -1208,6 +1235,9 @@ pub struct TurnView { pub cost_micros: Option, pub duration_ms: Option, pub error: Option, + /// 客户端没等到这一轮结束就走了(见 `HistoryRow::cancelled`) + #[serde(default)] + pub cancelled: bool, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -1646,11 +1676,53 @@ mod tests { source: "upstream".into(), message: "x".into(), }, + Event::RequestCancelled { + id: 7, + status: 200, + bytes: 1, + duration_ms: 1, + usage: None, + }, ] { assert_eq!(e.id(), 7); } } + /// 取消带着用量走 —— **存储层要拿它算钱**。而客户端在第一帧之前就走了 + /// 的那种,字段整个不出现,不是一组零。 + #[test] + fn a_cancellation_carries_the_usage_seen_so_far() { + let e = Event::RequestCancelled { + id: 3, + status: 200, + bytes: 512, + duration_ms: 2400, + usage: Some(UsageView { + input: 5000, + output: 1, + ..Default::default() + }), + }; + let v = serde_json::to_value(&e).unwrap(); + assert_eq!(v["kind"], "request_cancelled"); + assert_eq!(v["usage"]["input"], 5000); + let back: Event = serde_json::from_value(v).unwrap(); + assert!(matches!( + back, + Event::RequestCancelled { usage: Some(u), .. } if u.input == 5000 + )); + + let none = Event::RequestCancelled { + id: 4, + status: 200, + bytes: 0, + duration_ms: 10, + usage: None, + }; + let v = serde_json::to_value(&none).unwrap(); + assert!(v.get("usage").is_none(), "{v}"); + } + #[test] fn status_round_trips() { let s = Status { diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index c050aa08..fed23485 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -1196,6 +1196,7 @@ fn history_row(r: tw_store::RequestRow) -> tw_api::HistoryRow { cost_estimated: r.cost_estimated, error: r.error, local: r.local, + cancelled: r.cancelled, // 解不开就当没有。**一条坏掉的路由记录不该让整条请求记录读不出来** // —— 那是详情页上的一栏,不是这一行存在的理由。 routing: r @@ -1493,6 +1494,7 @@ fn turn_view(t: &tw_store::db::TurnRow) -> tw_api::TurnView { cost_micros: t.cost_micros, duration_ms: t.duration_ms, error: t.error.clone(), + cancelled: t.cancelled, } } diff --git a/crates/tw-control/tests/adopt.rs b/crates/tw-control/tests/adopt.rs index 175c1c4e..11d8fd40 100644 --- a/crates/tw-control/tests/adopt.rs +++ b/crates/tw-control/tests/adopt.rs @@ -450,6 +450,7 @@ async fn replaying_a_truncated_body_is_refused_rather_than_misleading() { cost_estimated: false, error: None, local: false, + cancelled: false, routing: None, billing: String::new(), cache_saved_micros: None, diff --git a/crates/tw-gateway/src/ending.rs b/crates/tw-gateway/src/ending.rs new file mode 100644 index 00000000..6d191c41 --- /dev/null +++ b/crates/tw-gateway/src/ending.rs @@ -0,0 +1,311 @@ +//! 一个响应体怎么收场。 +//! +//! 流式响应的结局只能由流自己来报 —— handler 在第一个字节发出去之前就 +//! 已经返回了。跑完了报 `RequestFinished`,上游断了或者被防火墙切断报 +//! `RequestFailed`,这两种都走得到流的末尾。 +//! +//! **第三种走不到。**客户端先走了(Claude Code 里按一下 Esc),hyper 丢掉 +//! 响应体,流停在它当时等着的那个 await 上被整个丢掉,末尾的代码一行都 +//! 不会执行。可那一刻上游已经在计费了:输入全额,输出算到断开为止。什么 +//! 都不报的话,存储层永远等不到这个请求的结局 —— 它不落库,那笔钱就从账 +//! 上消失了,界面上那一行也永远停在「进行中」。 +//! +//! 所以结局挂在一个跟着流走的对象上(和 [`crate::live::Pass`] 同一个 +//! 做法):正常收尾时显式地报,没报就被丢掉的,由 Drop 替它报「客户端 +//! 取消」。一个请求因此**恰好有一个结局** —— 少一个是一条永远不落库的 +//! 记录,多一个是同一行被写两遍。 + +use std::time::Instant; + +use crate::bodies::{BodyKind, BodyRecord, BodySender, ResponseTap}; +use crate::usage::{Sniffer, Usage}; + +/// 一个还欠着结局的请求。 +/// +/// **到目前为止对响应知道的一切都在它身上**:收到多少字节、嗅到多少用量、 +/// 攒下的响应体。放在一处是因为结局要用的正是这些 —— 不管这个结局是走到 +/// 流的末尾报的,还是在 Drop 里报的。 +#[must_use = "丢掉它就等于报告客户端已经走了"] +pub struct Ending { + bus: tw_observe::EventBus, + id: u64, + status: u16, + started: Instant, + /// 请求开始的时刻。响应体按它归档,和请求体那一份对得上 + at_ms: i64, + sink: Option, + /// 从上游收到多少字节。**数的是上游原话**,不是还原、翻译之后的那版 + bytes: u64, + /// 旁路嗅探。客户端走掉那一刻手里有多少用量,靠的就是它 + sniffer: Sniffer, + tap: ResponseTap, + /// 报过了。**只能报一次** + told: bool, +} + +impl Ending { + pub fn new( + bus: tw_observe::EventBus, + id: u64, + status: u16, + started: Instant, + at_ms: i64, + sink: Option, + ) -> Self { + Self { + bus, + id, + status, + started, + at_ms, + sink, + bytes: 0, + sniffer: Sniffer::new(), + tap: ResponseTap::new(), + told: false, + } + } + + /// 上游来了一块。**这里看的是上游原话**(带占位符的那一版):usage + /// 数字不受影响,而请求详情里存的正是「发出去的和收回来的」。 + pub fn feed(&mut self, chunk: &[u8]) { + self.bytes += chunk.len() as u64; + self.sniffer.feed(chunk); + self.tap.feed(chunk); + } + + /// 流走到了末尾。 + pub fn finished(mut self) { + let usage = self.settle(); + self.bus.emit(tw_api::Event::RequestFinished { + id: self.id, + status: self.status, + bytes: self.bytes, + duration_ms: self.duration_ms(), + usage, + }); + } + + /// 流断了,或者被切断了。**响应头早就发出去了**,这条事件是界面上 + /// 那一行唯一能知道它失败了的途径。 + pub fn failed(mut self, source: &str, message: String) { + self.settle(); + self.bus.emit(tw_api::Event::RequestFailed { + id: self.id, + source: source.to_string(), + message, + }); + } + + /// 收尾:先把响应体交出去,再拿走用量。三种结局共用,只走一次。 + fn settle(&mut self) -> Option { + self.told = true; + let (recorded, original_len) = std::mem::take(&mut self.tap).finish(); + if !recorded.is_empty() { + crate::bodies::offer( + &self.sink, + BodyRecord { + id: self.id, + at_ms: self.at_ms, + kind: BodyKind::Response, + body: recorded, + original_len, + }, + ); + } + std::mem::take(&mut self.sniffer).finish().map(view) + } + + fn duration_ms(&self) -> u64 { + self.started.elapsed().as_millis() as u64 + } +} + +impl Drop for Ending { + fn drop(&mut self) { + if self.told { + return; + } + // **这里什么都不能 panic。**Drop 可能正跑在一次 unwind 里,那时 + // 再 panic 一次,整个进程就没了。下面每一步都是不会失败的那种: + // 往通道里 try_send、往广播里 send、读一下时钟。 + let usage = self.settle(); + // 流是在网关自己的代码里崩掉的。**记成取消会冤枉客户端** —— + // 排查的人会去问一个根本没做过这件事的客户端。 + if std::thread::panicking() { + self.bus.emit(tw_api::Event::RequestFailed { + id: self.id, + source: "internal".to_string(), + message: "流中断:网关内部出错".to_string(), + }); + return; + } + self.bus.emit(tw_api::Event::RequestCancelled { + id: self.id, + status: self.status, + bytes: self.bytes, + duration_ms: self.duration_ms(), + usage, + }); + } +} + +fn view(u: Usage) -> tw_api::UsageView { + tw_api::UsageView { + input: u.input, + output: u.output, + cache_read: u.cache_read, + cache_write: u.cache_write, + cache_1h: u.cache_1h, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use futures::StreamExt; + use tw_api::Event; + + /// 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"; + + fn ending(bus: &tw_observe::EventBus) -> Ending { + Ending::new(bus.clone(), 7, 200, Instant::now(), 1_000, None) + } + + /// 总线上此刻有的全部事件。 + fn drain(rx: &mut tokio::sync::broadcast::Receiver) -> Vec { + std::iter::from_fn(|| rx.try_recv().ok()).collect() + } + + /// 走到末尾的流报一次结束,**Drop 时不再补一个取消**。补了的话,每一个 + /// 正常跑完的请求都会被写成两行。 + #[test] + fn a_stream_that_reaches_its_end_is_finished_and_nothing_else() { + let bus = tw_observe::EventBus::new(); + let mut rx = bus.subscribe(); + let mut e = ending(&bus); + e.feed(MESSAGE_START); + e.feed(MESSAGE_DELTA); + e.finished(); + + let got = drain(&mut rx); + assert_eq!(got.len(), 1, "{got:?}"); + match &got[0] { + Event::RequestFinished { + id: 7, + status: 200, + bytes, + usage: Some(u), + .. + } => { + assert_eq!(*bytes, (MESSAGE_START.len() + MESSAGE_DELTA.len()) as u64); + assert_eq!((u.input, u.output, u.cache_read), (5000, 777, 4000)); + } + other => panic!("该是一条结束,实际 {other:?}"), + } + } + + #[test] + fn a_stream_that_broke_is_failed_and_nothing_else() { + let bus = tw_observe::EventBus::new(); + let mut rx = bus.subscribe(); + let mut e = ending(&bus); + e.feed(MESSAGE_START); + e.failed("upstream", "流中断:上游断开了".into()); + + let got = drain(&mut rx); + assert_eq!(got.len(), 1, "{got:?}"); + assert!( + matches!(&got[0], Event::RequestFailed { source, .. } if source == "upstream"), + "{got:?}" + ); + } + + /// **这条是这个类型存在的理由。**没有人报结局就被丢掉的流,是客户端 + /// 先走了 —— 而上游已经为它看到的那些 token 计了费。 + #[test] + fn dropped_before_its_end_it_reports_a_cancellation_with_what_it_saw() { + 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, 200, Instant::now(), 1_000, Some(tx)); + e.feed(MESSAGE_START); + drop(e); + + let got = drain(&mut rx); + assert_eq!(got.len(), 1, "{got:?}"); + match &got[0] { + Event::RequestCancelled { + id: 7, + status: 200, + bytes, + usage: Some(u), + .. + } => { + assert_eq!(*bytes, MESSAGE_START.len() as u64); + // 输入和缓存读在第一帧里就是齐的,那正是账单上最大的一块 + assert_eq!((u.input, u.cache_read), (5000, 4000)); + } + other => panic!("该是一条取消,实际 {other:?}"), + } + // 收到的那一截响应也要留档 —— 详情里要能看到客户端走之前拿到了什么 + let body = bodies.try_recv().expect("取消的请求没有留下响应体"); + assert_eq!(body.kind, BodyKind::Response); + assert_eq!(&body.body[..], MESSAGE_START); + assert_eq!(body.at_ms, 1_000); + } + + /// 客户端在第一帧之前就走了。**没有用量就是 None,不是零** —— 零会让 + /// 一次真实的调用看起来是免费的。 + #[test] + fn dropped_before_the_first_chunk_it_reports_no_usage_rather_than_zero() { + let bus = tw_observe::EventBus::new(); + let mut rx = bus.subscribe(); + drop(ending(&bus)); + + let got = drain(&mut rx); + assert!( + matches!( + got.as_slice(), + [Event::RequestCancelled { + bytes: 0, + usage: None, + .. + }] + ), + "{got:?}" + ); + } + + /// 流在网关自己的代码里崩掉了。**Drop 同样会跑**(unwind 会丢掉流里的 + /// 局部变量),而这时报「客户端取消」是在冤枉客户端。 + /// + /// 这里用的是真的 `stream!`,因为要验的正是生成器被 unwind 时,Drop + /// 看得见那次 panic。 + #[test] + fn a_stream_that_panics_is_not_blamed_on_the_client() { + let bus = tw_observe::EventBus::new(); + let mut rx = bus.subscribe(); + let e = ending(&bus); + let s = async_stream::stream! { + let mut e = e; + e.feed(MESSAGE_START); + yield 1u8; + panic!("流里的一个 bug"); + }; + let mut s = Box::pin(s); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + futures::executor::block_on(async { while s.next().await.is_some() {} }) + })); + assert!(r.is_err(), "流该 panic"); + drop(s); + + let got = drain(&mut rx); + assert!( + matches!(got.as_slice(), [Event::RequestFailed { source, .. }] if source == "internal"), + "{got:?}" + ); + } +} diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index 1e7de7ca..b0880dee 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -9,6 +9,7 @@ pub mod access; pub mod auth; pub mod bodies; pub mod clientprobe; +pub mod ending; pub mod error; pub mod fixture; pub mod forward; diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index 4e7191b2..66ca3bcf 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -9,7 +9,7 @@ use axum::http::{HeaderMap, StatusCode}; use axum::response::{IntoResponse, Response}; use axum::routing::{any, get}; use bytes::Bytes; -use futures::{StreamExt, TryStreamExt}; +use futures::StreamExt; use crate::auth::key_eq; use crate::error::GatewayError; @@ -1378,17 +1378,13 @@ async fn pipeline( // 流式:**不缓冲**。整块缓冲会把 SSE 变成一次性交付,客户端那边 // 看起来就是「卡住很久然后一下全出来」。 let bus = state.bus.clone(); - let bytes_seen = Arc::new(std::sync::atomic::AtomicU64::new(0)); - let counted = { - let bytes_seen = bytes_seen.clone(); - upstream.bytes_stream().map_ok(move |chunk| { - bytes_seen.fetch_add(chunk.len() as u64, std::sync::atomic::Ordering::Relaxed); - chunk - }) - }; // 流结束时才知道总字节数和真实耗时 —— 对一个跑了六分钟的任务, // 这两个数字在响应头那一刻都还不存在。 // + // **结局跟着流走,而不是只写在流的末尾。**客户端中途走掉时,末尾的 + // 代码一行都不会执行,而上游已经为这次请求计了费(见 `crate::ending`)。 + let ending = crate::ending::Ending::new(bus.clone(), id, status.as_u16(), started, at_ms, sink); + let chunks = upstream.bytes_stream(); // **中途断掉不能只是让流消失。**首字节已经发出去了,状态码和响应头 // 都改不了,而一个戛然而止的 SSE 流和一个正常结束的流在客户端看来 // 长得一模一样 —— 用户会以为模型就答了这么多。唯一还能说话的地方 @@ -1432,23 +1428,21 @@ async fn pipeline( // 发完是一种,客户端中途断开、hyper 丢掉响应体是另一种 —— 两种 // 都算这个请求结束了。 let _live = live; - let mut counted = std::pin::pin!(counted); + // 结局也一样:流被丢掉的时候,它替流报「客户端取消」。 + let mut ending = ending; + let mut chunks = std::pin::pin!(chunks); let mut broke: Option = None; - // **旁路嗅探,不缓冲**:字节照常流向客户端,同时喂它 - // 一份。上游返回的 usage 是真相,而拿不到它就只能估。 - let mut sniffer = crate::usage::Sniffer::new(); - // 响应体也攒一份,**攒到上限就停**。和 usage 嗅探走同一个循环 —— - // 两个各自遍历一遍是白白多走一趟。 - let mut tap = crate::bodies::ResponseTap::new(); let mut whole: Vec = Vec::new(); - while let Some(item) = counted.next().await { + while let Some(item) = chunks.next().await { match item { Ok(chunk) => { - // **嗅探和留档看的是上游原话**(带占位符的那一版): - // usage 数字不受影响,而请求详情里存的正是「我们发出去 - // 的和收回来的」,把还原后的存进去会让那一页说谎。 - sniffer.feed(&chunk); - tap.feed(&chunk); + // **旁路嗅探和留档,不缓冲**:字节照常流向客户端,同时 + // 喂它一份。上游返回的 usage 是真相,而拿不到它就只能估。 + // + // 看的是上游原话(带占位符的那一版):usage 数字不受 + // 影响,而请求详情里存的正是「我们发出去的和收回来的」, + // 把还原后的存进去会让那一页说谎。 + ending.feed(&chunk); let out = restorer.process(&chunk); // 翻译在还原之后、审查之前:**审查看的必须是客户端 // 将要拿到的那一版**,而那一版是翻译过的 @@ -1555,41 +1549,17 @@ async fn pipeline( bus.emit(tw_api::Event::ResponseInspected { id, tool_calls, flagged }); } } - let (recorded, original_len) = tap.finish(); - if !recorded.is_empty() { - crate::bodies::offer( - &sink, - crate::bodies::BodyRecord { - id, - at_ms, - kind: crate::bodies::BodyKind::Response, - body: recorded, - original_len, - }, - ); - } + // 响应体留档和结束事件都在 `ending` 里:三种结局要交出去的是同一份 + // 东西,分开写就会有一种漏掉 match broke { - None => bus.emit(tw_api::Event::RequestFinished { - id, - status: status.as_u16(), - bytes: bytes_seen.load(std::sync::atomic::Ordering::Relaxed), - duration_ms: started.elapsed().as_millis() as u64, - usage: sniffer.finish().map(|u| tw_api::UsageView { - input: u.input, - output: u.output, - cache_read: u.cache_read, - cache_write: u.cache_write, - cache_1h: u.cache_1h, - }), - }), + None => ending.finished(), Some(err) => { // 少了这个事件,UI 上那一行会永远停在「进行中」—— // 而「一直转圈」比「明确失败」更让人怀疑是我们卡住了。 - bus.emit(tw_api::Event::RequestFailed { - id, - source: "upstream".to_string(), - message: format!("流中断:{}", err.message), - }); + // + // **先报再发错误帧**:客户端恰好在最后这一帧上走掉的话, + // 结局已经报过了,不会再被记成一次取消。 + ending.failed("upstream", format!("流中断:{}", err.message)); if is_sse { yield Ok(Bytes::from(err.sse_frame())); } diff --git a/crates/tw-gateway/tests/live.rs b/crates/tw-gateway/tests/live.rs index e0cc60fa..14cbce73 100644 --- a/crates/tw-gateway/tests/live.rs +++ b/crates/tw-gateway/tests/live.rs @@ -13,13 +13,15 @@ use axum::routing::any; use futures::StreamExt; use tw_config::{Client, Config, Provider}; +/// 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"; + /// 先吐一帧,然后很久不吐下一帧 —— 一个正在思考的模型。 async fn slow_stream_upstream() -> SocketAddr { let app = Router::new().fallback(any(|| async { let body = async_stream::stream! { - yield Ok::<_, std::io::Error>(bytes::Bytes::from_static( - b"event: message_start\ndata: {}\n\n", - )); + yield Ok::<_, std::io::Error>(bytes::Bytes::from_static(MESSAGE_START)); tokio::time::sleep(Duration::from_secs(60)).await; yield Ok(bytes::Bytes::from_static(b"event: message_stop\ndata: {}\n\n")); }; @@ -34,6 +36,54 @@ async fn slow_stream_upstream() -> SocketAddr { a } +/// 一条完整的流:开头报输入,末尾报累计输出。 +async fn complete_stream_upstream() -> SocketAddr { + let app = Router::new().fallback(any(|| async { + let mut frames = MESSAGE_START.to_vec(); + frames.extend_from_slice( + b"event: message_delta\ndata: {\"type\":\"message_delta\",\"usage\":{\"output_tokens\":777}}\n\n\ + event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n", + ); + axum::response::Response::builder() + .header("content-type", "text/event-stream") + .body(axum::body::Body::from(frames)) + .unwrap() + })); + 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 +} + +/// 说好 900 字节,发完第一帧就挂断 —— 上游中途没了。 +/// +/// **用裸 TCP 写**:框架替我们把响应收尾得好好的,而要模拟的恰恰是一个 +/// 没收尾的响应。 +async fn breaking_upstream() -> SocketAddr { + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let a = l.local_addr().unwrap(); + tokio::spawn(async move { + loop { + let Ok((mut s, _)) = l.accept().await else { + return; + }; + tokio::spawn(async move { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let mut buf = [0u8; 4096]; + let _ = s.read(&mut buf).await; + let mut head = b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\ + content-length: 900\r\n\r\n" + .to_vec(); + head.extend_from_slice(MESSAGE_START); + let _ = s.write_all(&head).await; + let _ = s.flush().await; + drop(s); + }); + } + }); + a +} + async fn fast_upstream() -> SocketAddr { let app = Router::new().fallback(any(|| async { axum::response::Response::builder() @@ -50,6 +100,19 @@ async fn fast_upstream() -> SocketAddr { /// 起一个网关,**把计数器留一份在外面** —— 状态被 move 进服务之后就 /// 摸不到了,而克隆出来的计数器数的是同一个数。 async fn serve(upstream: SocketAddr) -> (SocketAddr, tw_gateway::live::Live) { + let (addr, live, _) = serve_watched(upstream).await; + (addr, live) +} + +/// 同上,再把事件流也留一份。**在服务起来之前订阅** —— 之后才订的话, +/// 早到的事件就看不见了。 +async fn serve_watched( + upstream: SocketAddr, +) -> ( + SocketAddr, + tw_gateway::live::Live, + tokio::sync::broadcast::Receiver, +) { let cfg = Config { clients: vec![Client { name: "claude-code".into(), @@ -67,13 +130,14 @@ async fn serve(upstream: SocketAddr) -> (SocketAddr, tw_gateway::live::Live) { }; let state = tw_gateway::AppState::new(cfg).unwrap(); let live = state.live.clone(); + let events = state.bus.subscribe(); let addr = { let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); l.local_addr().unwrap() }; tokio::spawn(async move { tw_gateway::serve(state, addr).await.unwrap() }); tokio::time::sleep(Duration::from_millis(50)).await; - (addr, live) + (addr, live, events) } fn post(gw: SocketAddr) -> reqwest::RequestBuilder { @@ -135,6 +199,104 @@ async fn a_client_that_walks_away_mid_stream_stops_counting() { settles_at(&live, 0).await; } +/// 这个网关报出来的所有结局(结束、失败、取消)。 +/// +/// **等到第一个之后再多等一会儿**:要验的是「恰好一个」,而多出来的那个 +/// 如果存在,会紧跟着第一个到 —— 它们出自同一次收尾。 +async fn endings(rx: &mut tokio::sync::broadcast::Receiver) -> Vec { + let mut got = Vec::new(); + let mut deadline = tokio::time::Instant::now() + Duration::from_secs(5); + while let Ok(Ok(ev)) = tokio::time::timeout_at(deadline, rx.recv()).await { + if matches!( + ev, + tw_api::Event::RequestFinished { .. } + | tw_api::Event::RequestFailed { .. } + | tw_api::Event::RequestCancelled { .. } + ) { + if got.is_empty() { + deadline = tokio::time::Instant::now() + Duration::from_millis(500); + } + got.push(ev); + } + } + got +} + +/// 同一个按 Esc 的客户端,**这回看它有没有留下记录**。 +/// +/// 流末尾报结局的那几行在这条路径上一行都不会执行。什么都不报的话,存储层 +/// 永远等不到这个请求:上游已经为五千个输入 token 计了费,这一行却永远 +/// 不落库。 +#[tokio::test] +async fn a_client_that_walks_away_mid_stream_is_reported_once_as_cancelled() { + let (gw, live, mut events) = serve_watched(slow_stream_upstream().await).await; + + let resp = post(gw).send().await.unwrap(); + let mut body = resp.bytes_stream(); + body.next().await.unwrap().unwrap(); + drop(body); + settles_at(&live, 0).await; + + let got = endings(&mut events).await; + assert_eq!(got.len(), 1, "该恰好有一个结局:{got:?}"); + match &got[0] { + tw_api::Event::RequestCancelled { + status, + bytes, + usage, + .. + } => { + assert_eq!(*status, 200); + assert_eq!( + *bytes, + MESSAGE_START.len() as u64, + "断开之前从上游收到的就是第一帧" + ); + let u = usage.expect("第一帧里的用量没有带上"); + assert_eq!((u.input, u.cache_read), (5000, 4000)); + } + other => panic!("该是一次取消,实际 {other:?}"), + } +} + +/// 跑完的流**只报结束**。Drop 那一侧不知道「已经报过了」的话,每一个正常 +/// 跑完的请求都会再被记一次取消 —— 同一行写两遍,第二遍还是估算的金额。 +#[tokio::test] +async fn a_stream_that_runs_to_its_end_is_not_also_reported_as_cancelled() { + let (gw, _live, mut events) = serve_watched(complete_stream_upstream().await).await; + let text = post(gw).send().await.unwrap().text().await.unwrap(); + assert!(text.contains("message_stop"), "{text}"); + + let got = endings(&mut events).await; + assert_eq!(got.len(), 1, "该恰好有一个结局:{got:?}"); + assert!( + matches!(&got[0], tw_api::Event::RequestFinished { usage: Some(u), .. } if u.output == 777), + "该是带着累计输出的结束:{got:?}" + ); +} + +/// 上游中途断了:**报失败,不报取消**。网关随后往客户端补的那个错误帧, +/// 在它发出去之前结局就已经报过了。 +#[tokio::test] +async fn a_stream_the_upstream_breaks_is_failed_and_not_also_cancelled() { + let (gw, _live, mut events) = serve_watched(breaking_upstream().await).await; + let text = post(gw) + .send() + .await + .unwrap() + .text() + .await + .unwrap_or_default(); + assert!(text.contains("event: error"), "{text:?}"); + + let got = endings(&mut events).await; + assert_eq!(got.len(), 1, "该恰好有一个结局:{got:?}"); + assert!( + matches!(&got[0], tw_api::Event::RequestFailed { .. }), + "该是一次失败:{got:?}" + ); +} + #[tokio::test] async fn a_finished_request_stops_counting() { let (gw, live) = serve(fast_upstream().await).await; diff --git a/crates/tw-gateway/tests/passthrough.rs b/crates/tw-gateway/tests/passthrough.rs index e8111f71..02d68a6c 100644 --- a/crates/tw-gateway/tests/passthrough.rs +++ b/crates/tw-gateway/tests/passthrough.rs @@ -310,7 +310,7 @@ async fn next_billing(rx: &mut tokio::sync::broadcast::Receiver) panic!("没等到路由事件"); } -/// 下一条**生命周期**事件(开始 / 响应头 / 结束 / 失败)。 +/// 下一条**生命周期**事件(开始 / 响应头 / 结束 / 失败 / 取消)。 /// /// 观测类的事件(路由链、订阅额度、密钥发现、配置变更)会插在它们中间, /// 而且**以后还会更多** —— 每加一个就去改一遍这些测试是错的做法:那些 @@ -327,6 +327,7 @@ async fn next_lifecycle(rx: &mut tokio::sync::broadcast::Receiver | tw_api::Event::RequestHeaders { .. } | tw_api::Event::RequestFinished { .. } | tw_api::Event::RequestFailed { .. } + | tw_api::Event::RequestCancelled { .. } ) { return ev; } diff --git a/crates/tw-store/src/db.rs b/crates/tw-store/src/db.rs index d7f67c5f..c476b8e7 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 = 9; +const SCHEMA: i64 = 10; #[derive(Debug, thiserror::Error)] pub enum DbError { @@ -83,6 +83,9 @@ pub struct RequestRow { pub error: Option, /// 客户端的辅助请求被本地应答了。**不进成本和延迟统计** pub local: bool, + /// 客户端没等到响应结束就走了。**和 `error` 是两件事**:它不算失败, + /// 用量只算到断开那一刻,所以金额是估算 + pub cancelled: bool, /// 路由决策与尝试链,JSON。老记录是 None pub routing: Option, /// 服务它的那家怎么收钱:`per-token` / `subscription` / `unknown` @@ -270,6 +273,19 @@ impl Db { self.conn .execute_batch("ALTER TABLE requests ADD COLUMN redacted INTEGER;")?; } + if from < 10 { + // 客户端没等到响应结束就走了的那些(Claude Code 里按 Esc)。 + // + // **不能写进 `error`。**那一列决定失败数、失败率,还有上游行为 + // 画像里的错误率 —— 用户按了 Esc,不该让上游看起来在出错。可它 + // 也不是正常结束:用量只算到断开那一刻,界面要能把这一点说出来。 + // + // 老记录是 0。那时候这类请求根本不落库,所以没有一条老记录 + // 该是 1。 + self.conn.execute_batch( + "ALTER TABLE requests ADD COLUMN cancelled INTEGER NOT NULL DEFAULT 0;", + )?; + } self.conn.pragma_update(None, "user_version", SCHEMA)?; Ok(()) } @@ -281,8 +297,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, 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)", + client_hint, session, tool_calls, flagged, redacted, cancelled) + 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)", params![ r.id, r.at_ms, @@ -310,6 +326,7 @@ impl Db { r.tool_calls, r.flagged, r.redacted, + r.cancelled as i64, ], )?; Ok(()) @@ -362,6 +379,7 @@ pub struct TurnRow { pub cost_micros: Option, pub duration_ms: Option, pub error: Option, + pub cancelled: bool, } impl Db { @@ -416,7 +434,7 @@ impl Db { pub fn turns(&self, session: &str) -> Result, DbError> { let mut st = self.conn.prepare( "SELECT id, at_ms, model, provider, input_tokens, output_tokens, - cache_read_tokens, cost_micros, duration_ms, error + cache_read_tokens, cost_micros, duration_ms, error, cancelled FROM requests WHERE session = ?1 AND local = 0 ORDER BY at_ms, id", )?; let rows = st.query_map([session], |r| { @@ -431,6 +449,7 @@ impl Db { cost_micros: r.get(7)?, duration_ms: r.get(8)?, error: r.get(9)?, + cancelled: r.get::<_, i64>(10)? != 0, }) })?; Ok(rows.collect::, _>>()?) @@ -980,6 +999,7 @@ fn row_from(r: &rusqlite::Row) -> rusqlite::Result { cost_estimated: r.get::<_, i64>("cost_estimated")? != 0, error: r.get("error")?, local: r.get::<_, i64>("local")? != 0, + cancelled: r.get::<_, i64>("cancelled")? != 0, routing: r.get("routing")?, billing: r.get("billing")?, cache_saved_micros: r.get("cache_saved_micros")?, @@ -1079,6 +1099,7 @@ mod tests { cost_estimated: false, error: None, local: false, + cancelled: false, routing: None, billing: "per-token".into(), cache_saved_micros: None, @@ -1595,6 +1616,7 @@ mod tests { db.conn .execute_batch( "DROP INDEX requests_session; + ALTER TABLE requests DROP COLUMN cancelled; ALTER TABLE requests DROP COLUMN redacted; ALTER TABLE requests DROP COLUMN flagged; ALTER TABLE requests DROP COLUMN tool_calls; @@ -1609,6 +1631,8 @@ mod tests { let got = db.recent(10).unwrap(); // 老记录没有旁证,那就是 None —— 不是空字符串 assert!(got.iter().all(|r| r.client_hint.is_none())); + // 升级之前取消的请求根本不落库,所以老记录一条都不该是「已取消」 + assert!(got.iter().all(|r| !r.cancelled)); let mut fresh = row(3, 300); fresh.client_hint = Some("codex".into()); fresh.session = Some("abc-100".into()); diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index 30a371b5..bcc0d26d 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -3,8 +3,8 @@ //! **它跑在数据面之外。**观测挂了,代理照跑 —— 所以这里的每一个 //! 错误都只记一行日志,一个都不往回抛。 //! -//! 一次请求由四类事件描述(开始、响应头、结束、失败),它们分别到达, -//! 中间可能隔着几分钟。这里攒着它们,齐了就写一条。 +//! 一次请求由几类事件描述(开始、响应头,以及结束、失败、客户端取消三者 +//! 之一),它们分别到达,中间可能隔着几分钟。这里攒着它们,齐了就写一条。 use std::collections::HashMap; @@ -41,8 +41,9 @@ struct Partial { /// 在飞的请求最多攒多少条。 /// /// **一个只发了 `RequestStarted` 就再也没有下文的请求会永远占着位置** -/// —— 客户端 Ctrl+C、进程被杀、上游把连接挂着不放,都会造成它。超了从 -/// 最老的开始丢:丢掉的是一条观测记录,而留着它们会慢慢吃掉内存。 +/// —— 进程被杀、上游把连接挂着不放、客户端在响应头到达之前就走了,都会 +/// 造成它。(响应头之后才走的那些会报 `RequestCancelled`,不在此列。)超了 +/// 从最老的开始丢:丢掉的是一条观测记录,而留着它们会慢慢吃掉内存。 const MAX_INFLIGHT: usize = 4096; pub struct Recorder { @@ -253,86 +254,23 @@ impl Recorder { bytes, duration_ms, usage, - } => { - let Some(p) = self.inflight.remove(id) else { - return; - }; - let u = usage.map(|u| Usage { - input: u.input, - output: u.output, - cache_read: u.cache_read, - cache_write: u.cache_write, - cache_1h: u.cache_1h, - }); - // **上游没给 usage 就没有成本。**估算是 M3 后面的事 - // (tiktoken / count_tokens),而在那之前记一笔 0 是在 - // 撒谎。 - // **不引 tw-config** —— 存储层不该知道配置的形状。这个 - // 字符串是事件契约的一部分,比较它就够了。 - let counts_toward_money = p.billing.is_empty() || p.billing == "per-token"; - // **订阅型不按价目表算钱。**订阅制的边际成本是零,按 API - // 价目表乘出来的数字是纯虚构的 —— 而它会混进 - // 「今日花费」里,把一个诚实的面板变成一个编出来的。 - let cost = if counts_toward_money { - u.map(|u| self.prices.cost(&p.model, &u, false)) - } else { - None - }; - let (cost_micros, estimated) = match cost { - Some(Cost::Known(m)) => (Some(m), false), - Some(Cost::Estimated(m)) => (Some(m), true), - // 没有价格 / 没有 usage / 不按 token 计费, - // 三种都是「这笔账不在这个维度上」 - Some(Cost::Unpriced { .. }) | None => (None, false), - }; - // 缓存命中省下了多少。**在这里算,不在查询时算** - // —— 查询时算意味着要把价目表带进 SQL,而价目表会变, - // 那样「上周省了多少」会随着一次价格更新悄悄改变。 - let cache_saved_micros = if counts_toward_money { - u.and_then(|u| self.prices.cache_saving(&p.model, &u)) - } 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, - client: p.client, - client_hint: p.client_hint, - session: p.session, - tool_calls: p.tool_calls, - flagged: p.flagged, - redacted: p.redacted, - provider: p.provider, - model: p.model, - path: p.path, - status: Some(*status), - ttfb_ms: p.ttfb_ms, - duration_ms: Some(*duration_ms as i64), - bytes: Some(*bytes as i64), - input_tokens: u.map(|u| u.input as i64), - output_tokens: u.map(|u| u.output as i64), - cache_read_tokens: u.map(|u| u.cache_read as i64), - cache_write_tokens: u.map(|u| u.cache_write as i64), - cost_micros, - cost_estimated: estimated, - error: None, - local: false, - routing: p.routing, - billing: p.billing, - cache_saved_micros, - }); - } + } => self.settle(*id, *status, *bytes, *duration_ms, *usage, false), + /* + 客户端没等到响应结束就走了。 + + **照样落库,照样算钱。**上游那边已经计了费:输入全额,输出 + 算到断开为止。以前这类请求只在内存里挂着,从来不写 —— 那笔 + 钱就从账上消失了。 + + 它和正常结束只差一个标记,所以走同一条路。 + */ + Event::RequestCancelled { + id, + status, + bytes, + duration_ms, + usage, + } => self.settle(*id, *status, *bytes, *duration_ms, *usage, true), Event::RequestFailed { id, message, .. } => { let Some(p) = self.inflight.remove(id) else { return; @@ -363,6 +301,7 @@ impl Recorder { cost_estimated: false, error: Some(message.clone()), local: false, + cancelled: false, routing: p.routing, billing: p.billing, cache_saved_micros: None, @@ -401,6 +340,7 @@ impl Recorder { cost_estimated: false, error: None, local: true, + cancelled: false, // 本地应答没走路由 —— 它根本没到上游 routing: None, billing: String::new(), @@ -457,6 +397,101 @@ impl Recorder { } } + /// 一个拿到了用量的结局:跑完了,或者客户端中途走了。算钱,落库。 + fn settle( + &mut self, + id: u64, + status: u16, + bytes: u64, + duration_ms: u64, + usage: Option, + cancelled: bool, + ) { + let Some(p) = self.inflight.remove(&id) else { + return; + }; + let u = usage.map(|u| Usage { + input: u.input, + output: u.output, + cache_read: u.cache_read, + cache_write: u.cache_write, + cache_1h: u.cache_1h, + }); + // **上游没给 usage 就没有成本。**估算是 M3 后面的事 + // (tiktoken / count_tokens),而在那之前记一笔 0 是在 + // 撒谎。 + // **不引 tw-config** —— 存储层不该知道配置的形状。这个 + // 字符串是事件契约的一部分,比较它就够了。 + let counts_toward_money = p.billing.is_empty() || p.billing == "per-token"; + // **订阅型不按价目表算钱。**订阅制的边际成本是零,按 API + // 价目表乘出来的数字是纯虚构的 —— 而它会混进 + // 「今日花费」里,把一个诚实的面板变成一个编出来的。 + // + // **取消的一律按估算记。**输出只算到断开那一刻,而 Anthropic 在流的 + // 末尾才报累计输出 —— 断在中间时手里那个数是个占位。按它算出来的钱 + // 只会偏低,当成实测会让「今日花费」悄悄少一截。 + let cost = if counts_toward_money { + u.map(|u| self.prices.cost(&p.model, &u, cancelled)) + } else { + None + }; + let (cost_micros, estimated) = match cost { + Some(Cost::Known(m)) => (Some(m), false), + Some(Cost::Estimated(m)) => (Some(m), true), + // 没有价格 / 没有 usage / 不按 token 计费, + // 三种都是「这笔账不在这个维度上」 + Some(Cost::Unpriced { .. }) | None => (None, false), + }; + // 缓存命中省下了多少。**在这里算,不在查询时算** + // —— 查询时算意味着要把价目表带进 SQL,而价目表会变, + // 那样「上周省了多少」会随着一次价格更新悄悄改变。 + let cache_saved_micros = if counts_toward_money { + u.and_then(|u| self.prices.cache_saving(&p.model, &u)) + } else { + None + }; + // **算完就报,不等人来问。**这是整条链上唯一知道价钱的 + // 地方,而界面上那一列金额在它到达之前只能是「—」。 + if let Some(bus) = &self.bus { + bus.emit(Event::RequestPriced { + 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, + client: p.client, + client_hint: p.client_hint, + session: p.session, + tool_calls: p.tool_calls, + flagged: p.flagged, + redacted: p.redacted, + provider: p.provider, + model: p.model, + path: p.path, + status: Some(status), + ttfb_ms: p.ttfb_ms, + duration_ms: Some(duration_ms as i64), + bytes: Some(bytes as i64), + input_tokens: u.map(|u| u.input as i64), + output_tokens: u.map(|u| u.output as i64), + cache_read_tokens: u.map(|u| u.cache_read as i64), + cache_write_tokens: u.map(|u| u.cache_write as i64), + cost_micros, + cost_estimated: estimated, + error: None, + local: false, + cancelled, + routing: p.routing, + billing: p.billing, + cache_saved_micros, + }); + } + fn write(&self, r: RequestRow) { if let Err(e) = self.db.insert(&r) { // **不往回抛。**观测挂了,代理照跑。 @@ -748,7 +783,7 @@ mod tests { #[test] fn requests_that_never_finish_do_not_grow_the_map_without_bound() { - // 客户端 Ctrl+C、进程被杀、上游把连接挂着不放,都会造成它。 + // 进程被杀、上游把连接挂着不放、客户端在响应头之前就走了,都会造成它。 let (_d, mut r) = rec(); for i in 0..(MAX_INFLIGHT + 100) as u64 { r.on_event(&started(i, "m")); @@ -1073,3 +1108,155 @@ mod cache_saving_tests { assert_eq!(by_provider[0].samples, 2); } } + +#[cfg(test)] +mod cancellation_tests { + use super::tests::{finished, rec, started}; + use super::*; + use tw_api::UsageView; + + fn cancelled(id: u64, usage: Option) -> Event { + Event::RequestCancelled { + id, + status: 200, + bytes: 312, + duration_ms: 2_500, + usage, + } + } + + /// 按 Esc 那一刻手里的用量:输入是齐的,输出是 `message_start` 里那个 + /// 占位的 1。 + fn partial() -> Option { + Some(UsageView { + input: 100_000, + output: 1, + ..Default::default() + }) + } + + /// **这一行以前根本不存在。**客户端中途走掉的请求只在内存里挂着,从来 + /// 不写 —— 而上游已经为那十万个输入 token 计了费。 + #[test] + fn a_request_the_client_walked_away_from_is_written_and_priced() { + 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: 900, + }); + r.on_event(&cancelled(1, partial())); + + let row = r.db().get(1).unwrap().expect("取消的请求没有落库"); + assert!(row.cancelled); + assert_eq!(row.error, None, "取消不是失败"); + assert_eq!(row.status, Some(200)); + assert_eq!(row.ttfb_ms, Some(900)); + assert_eq!(row.duration_ms, Some(2_500)); + assert_eq!(row.bytes, Some(312)); + assert_eq!(row.input_tokens, Some(100_000)); + assert_eq!(row.output_tokens, Some(1)); + // Sonnet 4.5:输入 $3/M、输出 $15/M —— 十万个输入加一个输出 + assert_eq!(row.cost_micros, Some(300_015)); + assert!(row.cost_estimated, "输出只算到断开那一刻,这个数只能是估算"); + } + + /// 取消不进失败数。**进了的话,一个常按 Esc 的人会看到一个失败率很高 + /// 的面板**,而上游什么都没做错。钱照算,只是算在估算那一栏。 + #[test] + fn a_cancellation_is_not_a_failure_but_its_money_still_counts() { + let (_d, mut r) = rec(); + r.on_event(&started(1, "claude-sonnet-4-5")); + r.on_event(&cancelled(1, partial())); + r.on_event(&started(2, "claude-sonnet-4-5")); + r.on_event(&finished( + 2, + Some(UsageView { + input: 100_000, + ..Default::default() + }), + )); + + let s = r.db().summary(0, i64::MAX).unwrap(); + assert_eq!(s.requests, 2); + assert_eq!(s.failed, 0, "取消被算成了失败"); + assert_eq!(s.cost_micros_exact, 300_000); + assert_eq!(s.cost_micros_estimated, 300_015); + } + + /// 算出来的价钱照样报回总线,**而且标着估算** —— 界面上那一列金额 + /// 要带着 `~` 出现。 + #[test] + fn the_price_of_a_cancellation_goes_back_onto_the_bus_as_an_estimate() { + 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(&cancelled(1, partial())); + + let priced = std::iter::from_fn(|| rx.try_recv().ok()).find_map(|ev| match ev { + Event::RequestPriced { + id, + cost_micros, + cost_estimated, + .. + } => Some((id, cost_micros, cost_estimated)), + _ => None, + }); + assert_eq!(priced, Some((1, Some(300_015), true))); + } + + /// 客户端在第一帧之前就走了。**没有用量就没有金额,不是零** —— 而这 + /// 一行还是要写:这个请求发生过,本身就是事实。 + #[test] + fn a_cancellation_before_any_usage_is_written_without_a_price_rather_than_as_free() { + let (_d, mut r) = rec(); + r.on_event(&started(1, "claude-sonnet-4-5")); + r.on_event(&cancelled(1, None)); + + let row = r.db().get(1).unwrap().expect("没有用量的取消也该落库"); + assert!(row.cancelled); + assert_eq!(row.input_tokens, None); + assert_eq!(row.cost_micros, None); + } + + /// 会话里的那一轮也要看得出是取消的。否则在每轮花费里,它就是一轮 + /// 花了钱、输出却只有一个 token 的「正常」请求。 + #[test] + fn a_cancelled_turn_says_so_in_its_session() { + let (_d, mut r) = rec(); + r.on_event(&Event::RequestStarted { + id: 1, + client: "claude-code".into(), + client_hint: None, + session_fp: Some("fp".into()), + provider: "官方".into(), + model: "claude-sonnet-4-5".into(), + method: "POST".into(), + path: "/v1/messages".into(), + at_ms: 1_000_000, + }); + r.on_event(&cancelled(1, partial())); + + let sessions = r.db().sessions(10).unwrap(); + assert_eq!(sessions.len(), 1); + assert_eq!(sessions[0].errors, 0, "取消被算成了会话里的失败"); + let turns = r.db().turns(&sessions[0].id).unwrap(); + assert!(turns[0].cancelled); + } + + /// 结局只认第一个。同一个 id 后面再来一个结束,**不该把已经写下的那一行 + /// 盖掉** —— 写库用的是 INSERT OR REPLACE,第二次写就是覆盖。 + #[test] + fn a_second_ending_for_the_same_request_does_not_overwrite_the_first() { + let (_d, mut r) = rec(); + r.on_event(&started(1, "claude-sonnet-4-5")); + r.on_event(&cancelled(1, partial())); + r.on_event(&finished(1, None)); + + assert_eq!(r.db().count().unwrap(), 1); + assert!(r.db().get(1).unwrap().unwrap().cancelled); + } +} diff --git a/crates/tw-store/tests/m3_acceptance.rs b/crates/tw-store/tests/m3_acceptance.rs index 2d20ddc0..d478f5d1 100644 --- a/crates/tw-store/tests/m3_acceptance.rs +++ b/crates/tw-store/tests/m3_acceptance.rs @@ -47,6 +47,7 @@ fn req(id: i64, at_ms: i64) -> RequestRow { cost_estimated: false, error: None, local: false, + cancelled: false, routing: None, billing: "per-token".into(), cache_saved_micros: Some(1_500), diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 11d53b38..a03d98d0 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -43,7 +43,7 @@ trap cleanup EXIT # ---------------------------------------------------------------- 假上游 cat > "$TMP/upstream.py" <<'PY' -import http.server, json, sys +import http.server, json, sys, time class H(http.server.BaseHTTPRequestHandler): # **默认是 HTTP/1.0,每条响应之后关连接。**core 那边是带连接池的 # 客户端,会拿一条它以为还活着的连接去发下一个请求。配上 1.1 才是 @@ -59,6 +59,16 @@ class H(http.server.BaseHTTPRequestHandler): n = int(self.headers.get('content-length', 0) or 0) body = self.rfile.read(n) saw = "yes" if b"sk-ant-api03-SMOKEKEY" in body else "no" + if b"SLOWSTREAM" in body: + # 先吐第一帧(输入用量就在里面),然后长时间「思考」—— 客户端 + # 会在这期间走掉。不给 content-length,读到连接关闭为止。 + self.send_response(200); self.send_header('content-type','text/event-stream') + self.send_header('connection','close'); self.end_headers() + self.wfile.write(b'event: message_start\ndata: {"type":"message_start",' + b'"message":{"usage":{"input_tokens":4321,"output_tokens":1}}}\n\n') + self.wfile.flush() + time.sleep(30) + return if b'"stream":true' in body: frames = ( 'event: message_start\ndata: {"type":"message_start","message":{"id":"m"}}\n\n' @@ -250,6 +260,36 @@ S=$(curl -s -XPOST "http://127.0.0.1:$PORT/v1/messages" -H 'x-api-key: tw-smoket echo "$S" | grep -q 'event: error' && ok "高危工具调用被切断了" || bad "没切断" "$S" echo "$S" | grep -q 'content_block_stop' && bad "切断之后还发了 content_block_stop" || ok "客户端拿到的工具调用是残的" +# 客户端中途走掉(Claude Code 里按 Esc)。 +# +# **这一行以前不落库。**流末尾报结局的代码在这条路径上一行都不执行,而 +# 上游已经为输入计了费。网关的测试里那个服务是测试自己起的;这里验的是 +# 真二进制上「客户端断开 → 事件 → 落库 → /history」整条链通不通。 +curl -s -N -m 2 -XPOST "http://127.0.0.1:$PORT/v1/messages" -H 'x-api-key: tw-smoketestkey0123456789' \ + -H 'content-type: application/json' \ + -d '{"model":"claude-sonnet-4-5","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"SLOWSTREAM"}]}' \ + > "$TMP/cancelled.out" 2>/dev/null +if ! grep -q 'message_start' "$TMP/cancelled.out"; then + bad "断开之前连第一帧都没收到 —— 这一条测的不是「中途」走掉" "$(head -c 300 "$TMP/cancelled.out")" +else + GOT="" + # 落库是异步的:事件先过广播,再由存储层的任务写进去 + for _ in $(seq 1 20); do + GOT=$(curl -s --unix-socket "$SOCK" "http://localhost/history?limit=1" 2>/dev/null \ + | python3 -c 'import sys, json +rows = json.load(sys.stdin) +r = rows[0] if rows else {} +good = (r.get("cancelled") is True and r.get("error") is None + and r.get("input_tokens") == 4321 + and r.get("cost_micros") is not None and r.get("cost_estimated") is True) +print("ok" if good else json.dumps(r, ensure_ascii=False, sort_keys=True))' 2>/dev/null) + [ "$GOT" = "ok" ] && break + sleep 0.25 + done + [ "$GOT" = "ok" ] && ok "客户端中途走掉的请求落了库:标着取消,带着输入用量和估算金额" \ + || bad "客户端中途走掉的请求没有按取消落库" "$GOT" +fi + # ---------------------------------------------------------------- 控制面 step "控制面(每个端点)" sleep 1