From 4a7433a2ce1df463bd89c259e3f0ddb4d6c5682d Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 17 Sep 2026 10:45:26 +0800 Subject: [PATCH] fix(speed): send the inference speed test the way the upstream expects The L3 speed test built one request for every upstream: an Anthropic body posted to /v1/messages, without anthropic-version, through the default HTTP client. Three things went wrong with that, and each was reported to the user as "this upstream does not work": - Upstreams behind a proxy were unreachable. Only the OAuth token refresh used the upstream's own client; the probe itself went out directly. - The official Anthropic API rejects a request without anthropic-version with a 400. - OpenAI chat upstreams got a 404, since /v1/messages is not their route. The probe now picks its path, body and headers from the protocol, and runs through the upstream's own client. Protocols without a probe yet (Responses, Gemini) say so and send nothing, rather than sending a request that is bound to fail. The quote's total also stops treating a subscription upstream like an unpriced one. Both have no amount, but only "per-token and unknown" makes a total untrustworthy; selecting a subscription upstream used to hide the cost of every other upstream in the batch. A subscription is also taken from the config's `billing`, not only from quota headers seen so far. Co-Authored-By: Claude Opus 5 --- crates/tw-api/src/lib.rs | 9 +- crates/tw-control/src/lib.rs | 18 ++-- crates/tw-control/tests/speed.rs | 174 +++++++++++++++++++++++++++++++ crates/tw-gateway/src/l3.rs | 139 +++++++++++++++++++++++- 4 files changed, 326 insertions(+), 14 deletions(-) create mode 100644 crates/tw-control/tests/speed.rs diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index ddb2a9a9..ddc556e0 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -1129,6 +1129,10 @@ pub struct SpeedEstimate { pub max_output_tokens: u64, #[serde(default, skip_serializing_if = "Option::is_none")] pub cost_micros: Option, + /// 订阅制上游:不按 token 收钱,消耗的是额度。它没有金额,但**不让 + /// 合计变成空** —— 空只留给「按量计费却算不出来」 + #[serde(default)] + pub subscription: bool, /// 给人看的那一句 pub note: String, } @@ -1137,8 +1141,9 @@ pub struct SpeedEstimate { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SpeedQuote { pub items: Vec, - /// 总计。**有一项算不出来就是 None** —— 给一个看起来完整的数字, - /// 用户会以为那就是全部代价 + /// 总计,**不含订阅制那几项**(它们消耗额度,单独说)。按量计费的 + /// 有一项算不出来就是 None —— 给一个看起来完整的数字,用户会以为 + /// 那就是全部代价 #[serde(default, skip_serializing_if = "Option::is_none")] pub total_micros: Option, pub pricing_date: String, diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index bc974857..7d5d603d 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -679,12 +679,13 @@ async fn speed_quote( &prices, &p.name, &req.model, - // 订阅型上游的判据:最近一次响应里报过额度。 - // **不是一个用户要填的字段** —— 那个数字一直在我们手上。 - s.gateway - .quotas() - .get(&p.name) - .is_some_and(|q| !q.is_empty()), + // 订阅型上游的判据:配置里写明了,或者最近一次响应里报过 + // 额度(不写时自动判,和成本栏同一个口径)。 + p.billing == Some(tw_config::Billing::Subscription) + || s.gateway + .quotas() + .get(&p.name) + .is_some_and(|q| !q.is_empty()), ) }) .collect(); @@ -725,8 +726,10 @@ async fn speed_run( continue; } }; + // **发请求也用这一家的 client。**以前只有换 token 走它、真正的测速 + // 请求走默认 client —— 要走代理的上游在这里连不上,而转发时它是通的 let r = tw_gateway::l3::run( - s.http(), + &pk_http, &p.base_url, &key, p.effective_protocol(), @@ -756,6 +759,7 @@ fn quote_item(e: tw_gateway::Estimate) -> tw_api::SpeedEstimate { input_tokens: e.input_tokens, max_output_tokens: e.max_output_tokens, cost_micros: e.cost_micros, + subscription: e.subscription, note: e.note, } } diff --git a/crates/tw-control/tests/speed.rs b/crates/tw-control/tests/speed.rs new file mode 100644 index 00000000..8916149d --- /dev/null +++ b/crates/tw-control/tests/speed.rs @@ -0,0 +1,174 @@ +//! 推理测速(L3)走控制面的那一段。 +//! +//! 这一层花钱,所以两件事必须和转发时完全一致:**请求经过哪条出站路径**、 +//! **请求长什么样**。任何一处不一致,测出来的结论就是关于另一条路的 —— +//! 而用户会据此去换一个其实没问题的上游。 + +use std::sync::{Arc, Mutex}; + +use axum::body::Body; +use axum::http::{HeaderMap, Request, StatusCode, Uri}; +use tower::ServiceExt; +use tw_control::{ConfigManager, ControlState}; + +struct Bed { + _dir: tempfile::TempDir, + app: axum::Router, +} + +fn bed(yaml: &str) -> Bed { + let d = tempfile::tempdir().unwrap(); + let p = d.path().join("config.yaml"); + std::fs::write(&p, yaml).unwrap(); + let cfg: tw_config::Config = serde_yaml_ng::from_str(yaml).unwrap(); + let gw = tw_gateway::AppState::new(cfg).unwrap(); + let bus = gw.bus.clone(); + let state = ControlState { + cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), + gateway: gw, + gateway_addr: None, + store: None, + started: std::time::Instant::now(), + // **测试里绝不能碰开发者自己的配置** + home: d.path().join("home"), + }; + Bed { + app: tw_control::router(state), + _dir: d, + } +} + +async fn post(app: &axum::Router, path: &str, body: &str) -> (StatusCode, serde_json::Value) { + let r = app + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri(path) + .header("content-type", "application/json") + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap(); + let st = r.status(); + let b = axum::body::to_bytes(r.into_body(), 1 << 20).await.unwrap(); + ( + st, + serde_json::from_slice(&b).unwrap_or(serde_json::Value::Null), + ) +} + +/// 收到了什么请求。 +#[derive(Default, Clone)] +struct Seen { + path: String, + host: String, + anthropic_version: Option, +} + +/// 一个假的 HTTP 代理,同时扮演上游。 +/// +/// **上游地址故意写成解析不了的域名**:请求只有真的经过代理才能到达这里。 +/// 走默认 client 的话,它会在 DNS 那一步失败 —— 测试要抓的正是这个。 +async fn proxy_that_answers(seen: Arc>>) -> std::net::SocketAddr { + let app = axum::Router::new().fallback(move |uri: Uri, headers: HeaderMap| { + let seen = seen.clone(); + async move { + *seen.lock().unwrap() = Some(Seen { + path: uri.path().to_string(), + host: headers + .get("host") + .and_then(|v| v.to_str().ok()) + .unwrap_or_default() + .to_string(), + anthropic_version: headers + .get("anthropic-version") + .and_then(|v| v.to_str().ok()) + .map(String::from), + }); + let sse = concat!( + "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":10,\"output_tokens\":1}}}\n\n", + "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"delta\":{\"type\":\"text_delta\",\"text\":\"Hi\"}}\n\n", + "event: message_delta\ndata: {\"type\":\"message_delta\",\"usage\":{\"output_tokens\":2}}\n\n", + "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n", + ); + ([("content-type", "text/event-stream")], sse) + } + }); + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = l.local_addr().unwrap(); + tokio::spawn(async move { + axum::serve(l, app).await.unwrap(); + }); + addr +} + +#[tokio::test] +async fn the_speed_run_goes_out_through_the_upstreams_own_proxy() { + let seen = Arc::new(Mutex::new(None)); + let proxy = proxy_that_answers(seen.clone()).await; + let yaml = format!( + "version: 1 +clients: + - name: c + key: tw-k +proxies: + - name: corp + type: http + addr: {proxy} +providers: + - name: relay + base_url: http://relay.speed-test.invalid + key: sk-x + protocol: anthropic + proxy: corp +" + ); + let b = bed(&yaml); + let (st, v) = post( + &b.app, + "/speed/run", + r#"{"provider":"relay","model":"claude-sonnet-4-5"}"#, + ) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + let r = &v[0]; + assert_eq!(r["ok"], true, "没有经过代理,请求到不了上游:{v}"); + + let seen = seen.lock().unwrap().clone().expect("代理没收到请求"); + assert_eq!(seen.path, "/v1/messages"); + assert_eq!(seen.host, "relay.speed-test.invalid"); + // 官方端点没有它就回 400,而那会被报成「这家不通」 + assert_eq!(seen.anthropic_version.as_deref(), Some("2023-06-01")); +} + +#[tokio::test] +async fn a_subscription_upstream_does_not_void_the_quote_total() { + // 以前只要勾上一家订阅制上游,合计就是空的 —— 用户再也看不到这批 + // 测速要花多少钱。 + let b = bed("version: 1 +clients: + - name: c + key: tw-k +providers: + - name: official + base_url: https://api.anthropic.com + key: sk-x + - name: max + base_url: https://api.anthropic.com + key: sk-y + billing: subscription +"); + let (st, v) = post(&b.app, "/speed/quote", r#"{"model":"claude-sonnet-4-5"}"#).await; + assert_eq!(st, StatusCode::OK, "{v}"); + let items = v["items"].as_array().unwrap(); + let official = items.iter().find(|i| i["provider"] == "official").unwrap(); + let max = items.iter().find(|i| i["provider"] == "max").unwrap(); + assert_eq!(max["subscription"], true, "{v}"); + assert!(max.get("cost_micros").is_none(), "订阅制不该给金额:{v}"); + assert_eq!( + v["total_micros"], official["cost_micros"], + "合计应当只算按量计费的那一家:{v}" + ); +} diff --git a/crates/tw-gateway/src/l3.rs b/crates/tw-gateway/src/l3.rs index c04f1f6b..9e8ebe38 100644 --- a/crates/tw-gateway/src/l3.rs +++ b/crates/tw-gateway/src/l3.rs @@ -33,9 +33,13 @@ pub struct Estimate { pub input_tokens: u64, /// 输出上限 pub max_output_tokens: u64, - /// 微分。`None` 表示价目表里没有这个模型 + /// 微分。`None` 表示价目表里没有这个模型,或者这家是订阅制 #[serde(default, skip_serializing_if = "Option::is_none")] pub cost_micros: Option, + /// 订阅制上游。**没有金额不等于算不出来** —— 它消耗的是额度,不该 + /// 让一批测速的合计因为它变成「算不出来」 + #[serde(default)] + pub subscription: bool, /// 给人看的那一句。**金额再小也要显示** —— 用户按下按钮时有权知道 /// 自己在花什么 pub note: String, @@ -95,10 +99,53 @@ pub fn probe_body(model: &str) -> serde_json::Value { }) } +/// 这家上游说什么方言,测速请求就发成什么样。 +/// +/// **以前一律发 Anthropic 的 `/v1/messages`**,于是 OpenAI 协议的上游 +/// 必然 404;而且没带 `anthropic-version`,官方 Anthropic 端点直接 400 —— +/// 两种情况都被报成「这家不通」,用户会去换一个其实没问题的上游。 +/// +/// 返回 `None` 的协议是**还没写**,不是「这家不支持测速」。说清是哪一种, +/// 比发一个注定失败的请求、再把失败算到上游头上要好。 +pub struct ProbeRequest { + pub path: &'static str, + pub body: serde_json::Value, + pub headers: &'static [(&'static str, &'static str)], +} + +pub fn probe_request(protocol: Option, model: &str) -> Option { + use tw_config::Protocol::*; + match protocol { + // 猜不出协议时按 Anthropic 走 —— 和转发时 `credential_header` 的 + // 默认一致,两处不一致会让「转发正常、测速失败」成为可能 + Some(Anthropic) | None => Some(ProbeRequest { + path: "/v1/messages", + body: probe_body(model), + headers: &[("anthropic-version", "2023-06-01")], + }), + Some(OpenaiChat) => Some(ProbeRequest { + path: "/v1/chat/completions", + body: serde_json::json!({ + "model": model, + "max_tokens": MAX_TOKENS, + "stream": true, + // 不要这一项,流式响应里没有 usage,「实际消耗」一栏就是空的 + "stream_options": { "include_usage": true }, + "messages": [{ "role": "user", "content": PROMPT }], + }), + headers: &[], + }), + Some(OpenaiResponses) | Some(Gemini) => None, + } +} + /// 真的跑一次。 /// /// 调用方**必须**先把 `Estimate` 摆给用户看过。这个函数不检查那件事 —— /// 它检查不了 —— 但它是这一层唯一花钱的入口,所以这条注释写在这里。 +/// +/// `http` 必须是**这家上游自己的** client:它带着该走的代理。用默认 +/// client 的话,要走代理的上游在这里连不上,而转发时它是通的。 pub async fn run( http: &reqwest::Client, base_url: &str, @@ -108,13 +155,32 @@ pub async fn run( model: &str, ) -> L3Result { let started = Instant::now(); - let url = crate::forward::upstream_url(base_url, "/v1/messages", None); + let Some(probe) = probe_request(protocol, model) else { + return L3Result { + provider: provider.to_string(), + model: model.to_string(), + ok: false, + connect_ms: 0, + ttft_ms: None, + total_ms: 0, + output_tokens: None, + input_tokens: None, + error: Some(format!( + "推理测速暂不支持 {} 协议的上游,没有发出请求", + protocol.map(|p| format!("{p:?}")).unwrap_or_default() + )), + }; + }; + let url = crate::forward::upstream_url(base_url, probe.path, None); let mut req = http .post(&url) // 测速不该无限等。**但也不能太短** —— 一个排队中的上游正是我们 // 想量的东西,掐早了会把「慢」误报成「不通」。 .timeout(Duration::from_secs(60)); req = crate::forward::apply_credential(req, protocol, key); + for (name, value) in probe.headers { + req = req.header(*name, *value); + } let fail = |e: String, connect_ms: u64| L3Result { provider: provider.to_string(), model: model.to_string(), @@ -127,7 +193,7 @@ pub async fn run( error: Some(e), }; - let resp = match req.json(&probe_body(model)).send().await { + let resp = match req.json(&probe.body).send().await { Ok(r) => r, Err(e) => { return fail( @@ -226,6 +292,7 @@ pub fn estimate( input_tokens: input, max_output_tokens: MAX_TOKENS, cost_micros, + subscription, note, } } @@ -234,9 +301,16 @@ pub fn estimate( /// /// **批量是最容易让人手滑的地方** —— 点一下「全部测速」可能是 /// 十几次真实调用,所以要列出每一项**并给出总计**。 +/// +/// **订阅制那几项不进合计**:它们不按 token 收钱,消耗的是额度,界面上 +/// 单独说。以前它们和「价格未知」一样让合计变成空 —— 于是只要勾上一家 +/// 订阅制上游,用户就再也看不到这批测速要花多少钱。 pub fn total_micros(es: &[Estimate]) -> Option { - // 有任何一项算不出来,总计就不该给一个看起来完整的数字 - if es.iter().any(|e| e.cost_micros.is_none()) { + // 有任何一项按量计费却算不出来,总计就不该给一个看起来完整的数字 + if es + .iter() + .any(|e| !e.subscription && e.cost_micros.is_none()) + { return None; } Some(es.iter().filter_map(|e| e.cost_micros).sum()) @@ -328,6 +402,61 @@ mod tests { assert!(total_micros(&es).is_none()); } + #[test] + fn a_subscription_item_stays_out_of_the_total_instead_of_voiding_it() { + // 勾上一家订阅制上游,不该让用户看不到其余几家要花多少钱。 + let es = vec![ + estimate(&prices(), "官方", "claude-sonnet-4-5", false), + estimate(&prices(), "订阅", "claude-sonnet-4-5", true), + ]; + assert_eq!(total_micros(&es), es[0].cost_micros); + // 价格未知的那一项照样让合计不成立 + let mut es = es; + es.push(estimate(&prices(), "中转", "某个中转站的模型", false)); + assert!(total_micros(&es).is_none()); + } + + #[test] + fn an_anthropic_probe_carries_the_version_header_the_official_api_requires() { + // 没有它,官方端点回 400,而那会被报成「这家不通」。 + let p = probe_request(Some(tw_config::Protocol::Anthropic), "m").unwrap(); + assert_eq!(p.path, "/v1/messages"); + assert!(p.headers.iter().any(|(k, _)| *k == "anthropic-version")); + // 猜不出协议时和转发的默认一致 + let guessed = probe_request(None, "m").unwrap(); + assert_eq!(guessed.path, "/v1/messages"); + } + + #[test] + fn an_openai_chat_probe_goes_to_chat_completions_and_asks_for_usage() { + // 以前一律发 /v1/messages,OpenAI 协议的上游必然 404。 + let p = probe_request(Some(tw_config::Protocol::OpenaiChat), "gpt-4o").unwrap(); + assert_eq!(p.path, "/v1/chat/completions"); + assert_eq!(p.body["stream"], true); + assert_eq!(p.body["max_tokens"], MAX_TOKENS); + assert_eq!(p.body["stream_options"]["include_usage"], true); + assert!(p.headers.is_empty(), "OpenAI 系不该带 Anthropic 的头"); + } + + #[tokio::test] + async fn a_protocol_without_a_probe_says_so_and_sends_nothing() { + // 发一个注定失败的请求、再把失败算到上游头上,比直说更糟。 + // 地址指向一个不存在的端口:真发了的话错误会是「连不上」 + let r = run( + &reqwest::Client::new(), + "http://127.0.0.1:9", + "k", + Some(tw_config::Protocol::Gemini), + "g", + "gemini-2.5-pro", + ) + .await; + assert!(!r.ok); + let e = r.error.unwrap(); + assert!(e.contains("暂不支持"), "{e}"); + assert!(e.contains("没有发出请求"), "{e}"); + } + #[test] fn message_start_alone_is_not_the_first_token() { // **上游收到请求立刻就发它。**拿它当 TTFT 会让所有上游看起来