From 0e05cd6eef23f82288991572137774fc7b63003f Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Sun, 8 Nov 2026 20:38:57 +0800 Subject: [PATCH 1/7] fix(redact): avoid credential false positives in code and pool logs Require quoted field names for comma-separated credential values and stop unquoted recovery phrases at code delimiters. Exclude Rust numeric types and short unquoted numeric lookup keys while retaining explicit credential and quoted-value coverage. Preserve structural array indices in security hit paths while continuing to redact request-derived field names. Add regressions for the false positives, header pairs, credential positives, and masked path keys. --- crates/tw-gateway/src/guard/detail.rs | 39 ++++++++++++- crates/tw-gateway/src/guard/detail/tests.rs | 28 +++++++++ .../tw-guard/src/redact/secrets/blockchain.rs | 54 +++++++++++++++--- .../src/redact/secrets/blockchain/tests.rs | 57 +++++++++++++++++++ 4 files changed, 169 insertions(+), 9 deletions(-) diff --git a/crates/tw-gateway/src/guard/detail.rs b/crates/tw-gateway/src/guard/detail.rs index c27b122e..e7342504 100644 --- a/crates/tw-gateway/src/guard/detail.rs +++ b/crates/tw-gateway/src/guard/detail.rs @@ -244,14 +244,49 @@ fn cap(s: &str, n: usize) -> String { out } -/// 一处命中写成线上的样子。角色、工具名、路径是请求里来的字,也过一遍打码 +/// 路径里的字段名可能来自请求,仍要打码;数组下标是结构,不能按正文账本替换。 +fn masked_path(red: &Redaction, path: &str) -> String { + let b = path.as_bytes(); + let mut out = String::with_capacity(path.len()); + let mut start = 0; + let mut i = 0; + while i < b.len() { + // 非标识符键写成 JSON 字符串,里面的 [数字] 仍属于键,不能跳过打码。 + if b[i] == b'"' { + i += 1; + while i < b.len() && b[i] != b'"' { + if b[i] == b'\\' { + i += 1; + } + i += 1; + } + } else if b[i] == b'[' { + let mut end = i + 1; + while b.get(end).is_some_and(u8::is_ascii_digit) { + end += 1; + } + if end > i + 1 && b.get(end) == Some(&b']') { + out.push_str(&red.apply(&path[start..i])); + out.push_str(&path[i..=end]); + i = end + 1; + start = i; + continue; + } + } + i += 1; + } + out.push_str(&red.apply(&path[start..])); + out +} + +/// 一处命中写成线上的样子。角色、工具名、路径里的字段名也过一遍打码。 fn location(red: &Redaction, place: Place, path: &str, e: Excerpt) -> HitLocation { HitLocation { part: place.part, message_index: place.message_index, role: place.role.map(|r| red.apply(&r)), tool: place.tool.map(|t| red.apply(&t)), - path: red.apply(path), + path: masked_path(red, path), before: e.before, matched: e.matched, after: e.after, diff --git a/crates/tw-gateway/src/guard/detail/tests.rs b/crates/tw-gateway/src/guard/detail/tests.rs index d7341dd7..5003be4e 100644 --- a/crates/tw-gateway/src/guard/detail/tests.rs +++ b/crates/tw-gateway/src/guard/detail/tests.rs @@ -75,6 +75,34 @@ fn place_of(l: &HitLocation) -> (HitPart, Option, Option<&str>, Option<&str ) } +#[test] +fn paths_preserve_indices_while_masking_secrets_in_keys() { + let rules = RuleSet::defaults().with_custom("index-zero", "0").unwrap(); + let body = json!({"messages": [ + {"role": "assistant", "content": [ + {"type": "tool_use", "id": "call", "name": "audit", + "input": {"debug[0]": "0"}} + ]}, + {"role": "user", "content": [ + {"type": "tool_result", "tool_use_id": "call", "content": "0"} + ]} + ]}); + let details = redacted(Mode::Enforce, Some(Dialect::Anthropic), &body, rules); + assert_eq!(details.len(), 1); + let paths: Vec<_> = details[0] + .locations + .iter() + .map(|l| l.path.as_str()) + .collect(); + assert_eq!( + paths, + [ + "messages[0].content[0].input[\"debug[<>]\"]", + "messages[1].content[0].content", + ] + ); +} + // ---------------------------------------------------------------- 出站脱敏:四种格式 #[test] diff --git a/crates/tw-guard/src/redact/secrets/blockchain.rs b/crates/tw-guard/src/redact/secrets/blockchain.rs index 73b8f07d..f33754ae 100644 --- a/crates/tw-guard/src/redact/secrets/blockchain.rs +++ b/crates/tw-guard/src/redact/secrets/blockchain.rs @@ -106,7 +106,7 @@ pub(in crate::redact) fn scan( .and_then(|c| c.name("name")) .is_some_and(|m| m.start() == 0 && m.end() == decoded.len()) && let Some(id) = field_id(&decoded).filter(|id| set.is_on(id)) - && let Some((r, _, true)) = value(text, s.end) + && let Some((r, _, true)) = value(text, s.clone()) && inside(ss, r.clone()) && literal_value(&crate::locate::unescape(&text[r.clone()])) { @@ -526,7 +526,7 @@ fn context(text: &str, set: &RuleSet, strings: Option<&[Range]>, out: &mu continue; } } - let Some((mut r, end, quoted)) = value(text, m.end()) else { + let Some((mut r, end, quoted)) = value(text, m.range()) else { continue; }; // Bitstamp's X-Auth value has a scheme followed by the API key. @@ -546,7 +546,9 @@ fn context(text: &str, set: &RuleSet, strings: Option<&[Range]>, out: &mu r = from..to; } } - // Plain recovery phrases commonly appear without quotes. + // Plain recovery phrases commonly appear without quotes. Stop at code + // delimiters and escaped newlines too: a type declaration inside a + // nested tool result must not consume the rest of that result. let n = normalized(m.as_str()); if !quoted && !text[r.clone()].starts_with(['[', '{']) @@ -555,12 +557,25 @@ fn context(text: &str, set: &RuleSet, strings: Option<&[Range]>, out: &mu || matches!(n.as_str(), "助记词" | "恢复短语" | "种子短语")) { r.end = text[r.start..] - .find(['\n', '\r']) + .find([ + '\n', '\r', '\\', ',', ';', '"', '\'', '`', '(', ')', '[', ']', '{', '}', '<', + '>', + ]) .map_or(text.len(), |e| r.start + e); + r.end = r.start + text[r.clone()].trim_end().len(); } if strings.is_some_and(|ss| !inside(ss, r.clone())) { continue; } + // Short numeric lookup keys in logs commonly identify a pool entry. + // Quoted values and explicit credential labels still protect short secrets. + if n == "key" + && !quoted + && r.len() < 8 + && text[r.clone()].bytes().all(|c| c.is_ascii_digit()) + { + continue; + } seen = end.max(r.end); let header = m.as_str().contains('-') || m.as_str().starts_with("POLY_") @@ -577,8 +592,12 @@ fn context(text: &str, set: &RuleSet, strings: Option<&[Range]>, out: &mu /// A literal following a field/header name. Quoted values may contain spaces, /// Unicode and escaped characters. Arrays/objects are allowed only when the /// caller proves the entire span is inside a JSON string (text pasted into chat). -fn value(text: &str, mut i: usize) -> Option<(Range, usize, bool)> { +fn value(text: &str, name: Range) -> Option<(Range, usize, bool)> { let b = text.as_bytes(); + let mut i = name.end; + let quoted_name = name.start.checked_sub(1).is_some_and(|before| { + matches!(b[before], b'"' | b'\'' | b'`') && b.get(i) == Some(&b[before]) + }); if matches!(b.get(i), Some(b'"' | b'\'' | b'`')) { i += 1; } @@ -593,7 +612,10 @@ fn value(text: &str, mut i: usize) -> Option<(Range, usize, bool)> { } match b.get(i) { _ if text[i..].starts_with(':') => i += ":".len(), - Some(b':' | b'=' | b',') => i += 1, + Some(b':' | b'=') => i += 1, + // Header setters and tuples use a quoted name, followed by a comma. + // A variable in print(key, "label") is not a credential assignment. + Some(b',') if quoted_name => i += 1, _ => return None, } if matches!(b.get(i), Some(b'=' | b'~' | b'>')) { @@ -642,7 +664,7 @@ fn value(text: &str, mut i: usize) -> Option<(Range, usize, bool)> { i += 1; } end = i; - if text[start..end].contains(['(', ')', '[', '{']) { + if text[start..end].contains(['(', ')', '[', '{', '<', '>']) { return None; } } @@ -738,6 +760,24 @@ fn literal_value(v: &str) -> bool { } fn bare_literal(v: &str) -> bool { + if matches!( + v, + "u8" | "u16" + | "u32" + | "u64" + | "u128" + | "usize" + | "i8" + | "i16" + | "i32" + | "i64" + | "i128" + | "isize" + | "f32" + | "f64" + ) { + return false; + } // An unquoted identifier is a variable reference. Actual opaque keys normally // mix character classes; quoted passphrases have no alphabet restriction. v.starts_with(['[', '{']) diff --git a/crates/tw-guard/src/redact/secrets/blockchain/tests.rs b/crates/tw-guard/src/redact/secrets/blockchain/tests.rs index 0b50861d..98a1e8a9 100644 --- a/crates/tw-guard/src/redact/secrets/blockchain/tests.rs +++ b/crates/tw-guard/src/redact/secrets/blockchain/tests.rs @@ -511,3 +511,60 @@ fn numeric_credentials_in_text_are_hidden_without_replacing_json_numbers() { let body = r#"{"seed":42,"OTP":927416}"#; assert!(scan(body, &RuleSet::defaults()).is_empty()); } + +#[test] +fn code_arguments_and_type_annotations_are_not_credential_assignments() { + for text in [ + "print(key, 'field_names', list(value))", + "print(key, 'type', type(value).__name__)", + "const labels = [key, 'time', 'event'];", + "pub passphrase: String,", + "pub passphrase: Option,", + "pub seed: Vec,", + "pub secret: Option,", + "passphrase: String,\\n next_field: value", + "passphrase: Option,\\n next_field: value", + "fn restore(passphrase: &str) -> String { value.to_string() }", + ] { + let set = RuleSet::defaults(); + assert!(scan_plain(text, &set).is_empty(), "{text}"); + let body = serde_json::json!({"input":[{"role":"user","content":text}]}).to_string(); + let (sent, ledger) = crate::redact::flow::replace( + crate::policy::Mode::Enforce, + &set, + body.clone().into(), + &Ledger::new(Scheme::SECRET), + crate::redact::flow::Shape::Generate(tw_dialect::ir::Dialect::Responses), + ); + assert_eq!(sent.as_ref(), body.as_bytes(), "{text}"); + assert!(ledger.is_empty(), "{text}"); + } +} + +#[test] +fn quoted_header_pairs_still_protect_the_value() { + for text in [ + "headers.insert(\"X-API-KEY\", \"opaqueAlpha37\")", + "headers = [(\"POLY_API_KEY\", \"opaqueAlpha37\")]", + "headers[\"api_key\"] = \"opaqueAlpha37\"", + ] { + let hits = scan_plain(text, &RuleSet::defaults()); + let values: Vec<_> = hits.iter().map(|h| &text[h.bytes.clone()]).collect(); + assert_eq!(values, ["opaqueAlpha37"], "{text}"); + } +} + +#[test] +fn short_numeric_lookup_keys_are_not_secrets_but_explicit_credentials_are() { + for text in [ + "[WsPool] new connection: key=0, 2 assets", + "key=42", + "pub seed: u64,", + "let seed: u64 = get_seed();", + ] { + assert!(scan_plain(text, &RuleSet::defaults()).is_empty(), "{text}"); + } + for text in ["KEY: '42'", "API_KEY=42", "OTP: 927416", "seed: 42"] { + assert_eq!(scan_plain(text, &RuleSet::defaults()).len(), 1, "{text}"); + } +} From 0cbf10cc923dfca30b9cb59daa68b633912578b2 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:27:40 +0800 Subject: [PATCH 2/7] fix(gateway): honor native system proxy settings Enable reqwest native proxy discovery on macOS and Windows. Rebuild system proxy clients when applying configuration so updated OS settings are read. Refs ThinkWatchProject/ThinkWatch-Lite#406 --- Cargo.lock | 48 +++++++++++++++++++++++++++++-- Cargo.toml | 2 +- crates/tw-gateway/src/outbound.rs | 3 +- crates/tw-gateway/src/state.rs | 10 +++++-- 4 files changed, 56 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 473332eb..27c506ea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -730,6 +730,16 @@ dependencies = [ "futures", ] +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation" version = "0.10.1" @@ -1568,9 +1578,11 @@ dependencies = [ "percent-encoding", "pin-project-lite", "socket2", + "system-configuration", "tokio", "tower-service", "tracing", + "windows-registry", ] [[package]] @@ -2890,7 +2902,7 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" dependencies = [ - "core-foundation", + "core-foundation 0.10.1", "core-foundation-sys", "jni", "log", @@ -3005,7 +3017,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ "bitflags", - "core-foundation", + "core-foundation 0.10.1", "core-foundation-sys", "libc", "security-framework-sys", @@ -3330,6 +3342,27 @@ dependencies = [ "windows", ] +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "target-lexicon" version = "0.13.5" @@ -4795,6 +4828,17 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + [[package]] name = "windows-result" version = "0.3.4" diff --git a/Cargo.toml b/Cargo.toml index be2c670e..beb2f2fd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -128,7 +128,7 @@ toml_edit = "0.25" # serde_yaml 已经归档,且本来就不保留格式。 saphyr-parser = "0.0.12" -reqwest = { version = "0.13", default-features = false, features = ["stream", "json", "rustls", "socks", "http2", "form"] } # form: OAuth 换 token 是表单 POST,密钥的百分号编码不自己写 +reqwest = { version = "0.13", default-features = false, features = ["stream", "json", "rustls", "socks", "http2", "form", "system-proxy"] } # system-proxy: Windows/macOS 原生代理;form: OAuth 换 token # L1 分段测速要自己走握手 —— reqwest 把建连整个包起来,只给一个总时间, # 而分段正是这一层的全部价值。版本跟着 reqwest 的传递依赖走,不引新的树。 rustls = "0.23" diff --git a/crates/tw-gateway/src/outbound.rs b/crates/tw-gateway/src/outbound.rs index 5f9efd5a..64e39411 100644 --- a/crates/tw-gateway/src/outbound.rs +++ b/crates/tw-gateway/src/outbound.rs @@ -66,7 +66,8 @@ pub fn client_for_provider( b = b.no_proxy(); } tw_config::SYSTEM => { - // reqwest 默认就读系统代理,什么都不做即可。 + // reqwest 的 system-proxy 特性读取 Windows/macOS 原生设置,同时 + // 支持环境变量。禁用默认特性时必须显式开启,否则只剩环境变量。 } name => { let proxy = cfg.proxies.iter().find(|x| x.name == name).ok_or_else(|| { diff --git a/crates/tw-gateway/src/state.rs b/crates/tw-gateway/src/state.rs index ab0fb69f..bf8a4690 100644 --- a/crates/tw-gateway/src/state.rs +++ b/crates/tw-gateway/src/state.rs @@ -58,8 +58,8 @@ impl Runtime { /// /// `previous` 在时**尽量复用上一份的 Client**。每次重载都重建所有 /// Client,等于把每个上游的连接池连同已经握好的 TLS 一起扔掉 —— - /// 改一条路由规则不该让下一个请求多付一次完整的建连。只有代理相关 - /// 的字段变了才必须重建,因为代理是绑在 Client 上的。 + /// 改一条路由规则不该让下一个请求多付一次完整的建连。显式代理只在代理相关 + /// 字段变了时重建;跟随系统的每次重载都重新读取系统设置。 /// /// 插件最后建:**它不会失败**(哪个插件有问题只停它自己,见 [`crate::plugin::load`]), /// 放在所有可能失败的步骤之后,建出来就一定换得进去。 @@ -72,7 +72,11 @@ impl Runtime { for p in &config.providers { let reusable = previous.and_then(|prev| { let old = prev.config.providers.iter().find(|x| x.name == p.name)?; - if proxy_shape(&prev.config, old) == proxy_shape(&config, p) { + // 系统代理在 Client 建立时读取。重新应用配置时必须重读,不能因 + // 配置里仍写着 system 就沿用开启/切换代理之前的连接池。 + if p.proxy != tw_config::SYSTEM + && proxy_shape(&prev.config, old) == proxy_shape(&config, p) + { prev.clients.get(&p.name) } else { None From ceff13e808edbd68d517a8b256ecaf3cb3a624ab Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:27:56 +0800 Subject: [PATCH 3/7] fix(dialect): preserve structured Mistral response content Read string and array content in streaming and non-streaming Chat responses. Keep typed thinking separate from visible text and ignore non-text chunks. Add a gateway regression where the upstream waits for the client to receive its first array fragment before sending the remainder. Refs ThinkWatchProject/ThinkWatch-Lite#407 --- crates/tw-dialect/src/chat/response.rs | 59 +++++++++++++++++++- crates/tw-dialect/src/chat/stream.rs | 77 ++++++++++++++++++++++++-- crates/tw-gateway/tests/dialect.rs | 77 ++++++++++++++++++++++++++ 3 files changed, 205 insertions(+), 8 deletions(-) diff --git a/crates/tw-dialect/src/chat/response.rs b/crates/tw-dialect/src/chat/response.rs index c284e5a0..96ba6305 100644 --- a/crates/tw-dialect/src/chat/response.rs +++ b/crates/tw-dialect/src/chat/response.rs @@ -55,6 +55,36 @@ pub fn usage_json(u: &Usage) -> Value { }) } +/// Chat 兼容端点的正文:标准字符串,或 Mistral 的有序内容块。 +/// 只读文本和显式的推理文字,引用、图片与未知块不能当作回答正文。 +pub(super) fn content_parts(v: &Value, mut emit: impl FnMut(bool, &str)) { + if let Some(text) = v.as_str() { + if !text.is_empty() { + emit(false, text); + } + } else if let Some(parts) = v.as_array() { + for part in parts { + match str_of(part, "type") { + Some("text") => { + if let Some(text) = str_of(part, "text").filter(|t| !t.is_empty()) { + emit(false, text); + } + } + Some("thinking") => { + for thought in arr_of(part, "thinking") { + if str_of(thought, "type") == Some("text") + && let Some(text) = str_of(thought, "text").filter(|t| !t.is_empty()) + { + emit(true, text); + } + } + } + _ => {} + } + } + } +} + /// 上游 Chat 的整包响应 → 中间表示。 pub fn decode_response(v: &Value) -> Response { let choice = v @@ -74,9 +104,16 @@ pub fn decode_response(v: &Value) -> Response { })); } for key in ["content", "refusal"] { - if let Some(t) = str_of(msg, key).filter(|t| !t.is_empty()) { - blocks.push(Block::Text(t.to_string())); - } + content_parts(&msg[key], |thinking, text| { + blocks.push(if thinking { + Block::Thinking(Thinking { + text: text.to_string(), + signature: Some(Signature::new(Vendor::Chat, "")), + }) + } else { + Block::Text(text.to_string()) + }); + }); } for c in arr_of(msg, "tool_calls") { let id = str_of(c, "id").unwrap_or_default().to_string(); @@ -193,6 +230,22 @@ pub fn error_message(v: &Value) -> Option { mod tests { use super::*; + #[test] + fn mistral_content_blocks_keep_their_order_and_kinds() { + let response = decode_response(&json!({"choices":[{"message":{"content":[ + {"type":"thinking","thinking":[{"type":"text","text":"reason"}]}, + {"type":"text","text":"first"}, + {"type":"reference","text":"not prose"}, + {"type":"text","text":"second"} + ]}, "finish_reason":"stop"}]})); + assert!(matches!(&response.blocks[0], Block::Thinking(t) if t.text == "reason")); + assert_eq!( + &response.blocks[1..], + &[Block::Text("first".into()), Block::Text("second".into())] + ); + assert_eq!(response.stop, Some(StopReason::EndTurn)); + } + #[test] fn cached_tokens_are_taken_out_of_the_prompt_count() { // 不减的话,缓存命中的部分会被按输入价再算一遍 diff --git a/crates/tw-dialect/src/chat/stream.rs b/crates/tw-dialect/src/chat/stream.rs index 9cb07190..32e62cd6 100644 --- a/crates/tw-dialect/src/chat/stream.rs +++ b/crates/tw-dialect/src/chat/stream.rs @@ -8,7 +8,9 @@ use std::collections::HashMap; use serde_json::{Value, json}; -use super::response::{completion_id, finish_reason, stop_reason, usage, usage_json}; +use super::response::{ + completion_id, content_parts, finish_reason, stop_reason, usage, usage_json, +}; use crate::convert::Session; use crate::frame::{self, Frame}; use crate::ir::*; @@ -81,13 +83,21 @@ impl Parser { }); } for key in ["content", "refusal"] { - if let Some(t) = str_of(delta, key).filter(|t| !t.is_empty()) { - let index = self.ensure(Open::Text, None, out); + content_parts(&delta[key], |thinking, text| { + let index = self.ensure( + if thinking { Open::Thinking } else { Open::Text }, + None, + out, + ); out.push(Event::Delta { index, - delta: Delta::Text(t.to_string()), + delta: if thinking { + Delta::Thinking(text.to_string()) + } else { + Delta::Text(text.to_string()) + }, }); - } + }); } for c in arr_of(delta, "tool_calls") { let k = u64_of(c, "index").unwrap_or(0); @@ -318,6 +328,63 @@ mod tests { out } + #[test] + fn mistral_array_content_is_emitted_before_the_stream_finishes() { + let mut parser = Parser::default(); + let mut out = Vec::new(); + let mut decoder = Decoder::default(); + for content in [ + json!([{"type":"text", "text":"FIRST"}]), + json!(", SECOND"), + json!([{"type":"text", "text":", THIRD"}]), + ] { + let chunk = frame::data(&json!({"choices":[{"delta":{"content":content}}]})); + for bytes in chunk.as_bytes().chunks(7) { + for f in decoder.feed(bytes) { + parser.frame(&f, &mut out); + } + } + } + let text: String = out + .iter() + .filter_map(|event| match event { + Event::Delta { + delta: Delta::Text(t), + .. + } => Some(t.as_str()), + _ => None, + }) + .collect(); + assert_eq!(text, "FIRST, SECOND, THIRD"); + assert!(!out.iter().any(|e| matches!(e, Event::Stop(_)))); + } + + #[test] + fn mistral_thinking_stays_separate_from_visible_text() { + let chunk = frame::data(&json!({"choices":[{"delta":{"content":[ + {"type":"thinking", "thinking":[{"type":"text", "text":"reason"}, {"type":"reference", "text":"not prose"}]}, + {"type":"text", "text":"answer"}, + {"type":"unknown", "text":"not prose"} + ]},"finish_reason":"stop"}]})); + let events = parse(&[&chunk]); + let deltas: Vec<_> = events + .iter() + .filter_map(|event| match event { + Event::Delta { + delta: Delta::Text(t), + .. + } => Some((false, t.as_str())), + Event::Delta { + delta: Delta::Thinking(t), + .. + } => Some((true, t.as_str())), + _ => None, + }) + .collect(); + assert_eq!(deltas, [(true, "reason"), (false, "answer")]); + assert!(events.contains(&Event::Stop(StopReason::EndTurn))); + } + /// 有的中转每一块都带着 `"error": null`:照常读内容。真的错误没写说明时,不拿那一块凑 #[test] fn a_null_error_is_read_as_content_and_a_bare_error_has_no_chunk_for_a_message() { diff --git a/crates/tw-gateway/tests/dialect.rs b/crates/tw-gateway/tests/dialect.rs index 1749a5bc..b7ed2904 100644 --- a/crates/tw-gateway/tests/dialect.rs +++ b/crates/tw-gateway/tests/dialect.rs @@ -153,6 +153,83 @@ async fn ask(gw: SocketAddr, body: String) -> (u16, String) { (status, r.text().await.unwrap()) } +/// 上游在客户端读到第一段之前不再发送:转换器若丢首段或攒整包,这里就超时。 +#[tokio::test] +async fn mistral_array_text_reaches_the_client_before_the_upstream_finishes() { + use futures::StreamExt; + + let proceed = Arc::new(tokio::sync::Notify::new()); + let next = proceed.clone(); + let app = Router::new().route("/v1/chat/completions", post(move || { + let next = next.clone(); + async move { + let body = axum::body::Body::from_stream(async_stream::stream! { + yield Ok::<_, std::convert::Infallible>(bytes::Bytes::from_static( + b"data: {\"choices\":[{\"delta\":{\"content\":[{\"type\":\"text\",\"text\":\"FIRST\"}]}}]}\r\n\r\n" + )); + next.notified().await; + yield Ok(bytes::Bytes::from_static( + b"data: {\"choices\":[{\"delta\":{\"content\":\", SECOND\"},\"finish_reason\":\"stop\"}]}\r\n\r\ndata: [DONE]\r\n\r\n" + )); + }); + axum::response::Response::builder() + .header("content-type", "text/event-stream; charset=utf-8") + .body(body).unwrap() + } + })); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let upstream = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let (gateway, _) = start_gateway(upstream).await; + let response = reqwest::Client::builder() + .no_proxy() + .build() + .unwrap() + .post(format!("http://{gateway}/v1/messages")) + .header("x-api-key", "tw-testkey") + .header("content-type", "application/json") + .body(claude_body(true)) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let mut stream = response.bytes_stream(); + let mut received = Vec::new(); + tokio::time::timeout(Duration::from_secs(3), async { + while !String::from_utf8_lossy(&received).contains("FIRST") { + received.extend_from_slice( + &stream + .next() + .await + .expect("stream ended before first text") + .unwrap(), + ); + } + }) + .await + .expect("array text was buffered or lost"); + assert!(!String::from_utf8_lossy(&received).contains("SECOND")); + proceed.notify_one(); + tokio::time::timeout(Duration::from_secs(3), async { + while let Some(chunk) = stream.next().await { + received.extend_from_slice(&chunk.unwrap()); + } + }) + .await + .unwrap(); + let body = String::from_utf8(received).unwrap(); + let text: String = body + .lines() + .filter_map(|line| { + let v: serde_json::Value = serde_json::from_str(line.strip_prefix("data: ")?).ok()?; + v.pointer("/delta/text")?.as_str().map(str::to_owned) + }) + .collect(); + assert_eq!(text, "FIRST, SECOND"); + assert!(body.contains("message_stop")); + server.abort(); +} + #[tokio::test] async fn a_claude_code_request_reaches_an_openai_only_upstream_in_the_right_shape() { let (up, seen) = start_openai_upstream(false).await; From a27fffda3f78d5374e482f3c2f3b2d22480e1348 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:51:11 +0800 Subject: [PATCH 4/7] fix(redact): restore split placeholders in Mistral content arrays Array text fragments must share the existing Chat text lane so placeholders split across frames or string/array transitions are restored before dialect conversion. Keep thinking content untouched. Cover array and mixed fragments in the restorer and extend the incremental gateway regression to verify redaction, restoration and conversion together. Refs ThinkWatchProject/ThinkWatch-Lite#407 --- crates/tw-gateway/tests/dialect.rs | 32 +++++++++++++--- crates/tw-guard/src/redact/sse.rs | 60 ++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 5 deletions(-) diff --git a/crates/tw-gateway/tests/dialect.rs b/crates/tw-gateway/tests/dialect.rs index b7ed2904..d3583a44 100644 --- a/crates/tw-gateway/tests/dialect.rs +++ b/crates/tw-gateway/tests/dialect.rs @@ -92,6 +92,13 @@ async fn start_openai_upstream(sse: bool) -> (SocketAddr, Arc>>) { async fn start_gateway( up: SocketAddr, +) -> (SocketAddr, tokio::sync::broadcast::Receiver) { + start_gateway_with_security(up, tw_config::Security::default()).await +} + +async fn start_gateway_with_security( + up: SocketAddr, + security: tw_config::Security, ) -> (SocketAddr, tokio::sync::broadcast::Receiver) { let cfg = Config { version: 1, @@ -109,6 +116,7 @@ async fn start_gateway( protocol: Some(tw_config::Protocol::OpenaiChat), ..Default::default() }], + security, ..Default::default() }; let state = tw_gateway::AppState::new(cfg).unwrap(); @@ -160,16 +168,24 @@ async fn mistral_array_text_reaches_the_client_before_the_upstream_finishes() { let proceed = Arc::new(tokio::sync::Notify::new()); let next = proceed.clone(); - let app = Router::new().route("/v1/chat/completions", post(move || { + let app = Router::new().route("/v1/chat/completions", post(move |body: bytes::Bytes| { let next = next.clone(); async move { + let sent: serde_json::Value = serde_json::from_slice(&body).unwrap(); + let text = sent["messages"].as_array().unwrap().iter() + .find(|m| m["role"] == "user").unwrap()["content"].as_str().unwrap(); + assert!(text.contains("<>"), "{text}"); + assert!(!text.contains("array-secret-fixture"), "{text}"); let body = axum::body::Body::from_stream(async_stream::stream! { yield Ok::<_, std::convert::Infallible>(bytes::Bytes::from_static( b"data: {\"choices\":[{\"delta\":{\"content\":[{\"type\":\"text\",\"text\":\"FIRST\"}]}}]}\r\n\r\n" )); next.notified().await; yield Ok(bytes::Bytes::from_static( - b"data: {\"choices\":[{\"delta\":{\"content\":\", SECOND\"},\"finish_reason\":\"stop\"}]}\r\n\r\ndata: [DONE]\r\n\r\n" + b"data: {\"choices\":[{\"delta\":{\"content\":[{\"type\":\"text\",\"text\":\", <>, SECOND\"}]},\"finish_reason\":\"stop\"}]}\r\n\r\ndata: [DONE]\r\n\r\n" )); }); axum::response::Response::builder() @@ -180,7 +196,13 @@ async fn mistral_array_text_reaches_the_client_before_the_upstream_finishes() { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let upstream = listener.local_addr().unwrap(); let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); - let (gateway, _) = start_gateway(upstream).await; + let security = serde_json::from_value(serde_json::json!({ + "redact": {"mode":"enforce", "custom":[{ + "name":"array fixture", "pattern":"array-secret-fixture" + }]} + })) + .unwrap(); + let (gateway, _) = start_gateway_with_security(upstream, security).await; let response = reqwest::Client::builder() .no_proxy() .build() @@ -188,7 +210,7 @@ async fn mistral_array_text_reaches_the_client_before_the_upstream_finishes() { .post(format!("http://{gateway}/v1/messages")) .header("x-api-key", "tw-testkey") .header("content-type", "application/json") - .body(claude_body(true)) + .body(claude_body(true).replace("帮我看看 a/b.rs", "帮我看看 a/b.rs array-secret-fixture")) .send() .await .unwrap(); @@ -225,7 +247,7 @@ async fn mistral_array_text_reaches_the_client_before_the_upstream_finishes() { v.pointer("/delta/text")?.as_str().map(str::to_owned) }) .collect(); - assert_eq!(text, "FIRST, SECOND"); + assert_eq!(text, "FIRST, array-secret-fixture, SECOND"); assert!(body.contains("message_stop")); server.abort(); } diff --git a/crates/tw-guard/src/redact/sse.rs b/crates/tw-guard/src/redact/sse.rs index 190bd8ca..31c2255c 100644 --- a/crates/tw-guard/src/redact/sse.rs +++ b/crates/tw-guard/src/redact/sse.rs @@ -399,6 +399,26 @@ fn fields(d: Dialect, v: &Value) -> Vec { lane: Lane::Text(choice_lane(n, 0)), path: vec![Key("choices"), Idx(pos), Key("delta"), Key("content")], }); + } else if let Some(parts) = delta.get("content").and_then(Value::as_array) { + // Mistral 的数组与字符串是同一路正文,分片可以在两种写法间切换。 + // 按顺序还原每个 text,不能把 thinking 或引用并到正文里。 + for (i, part) in parts.iter().enumerate() { + if kind(part) == Some("text") + && part.get("text").is_some_and(Value::is_string) + { + out.push(Field { + lane: Lane::Text(choice_lane(n, 0)), + path: vec![ + Key("choices"), + Idx(pos), + Key("delta"), + Key("content"), + Idx(i), + Key("text"), + ], + }); + } + } } if let Some(calls) = delta.get("tool_calls").and_then(Value::as_array) { for (k, c) in calls.iter().enumerate() { @@ -1041,6 +1061,46 @@ mod tests { assert_eq!(args, format!(r#"{{"v":"{KEY}"}}"#)); } + #[test] + fn mistral_text_arrays_share_the_chat_text_lane() { + let array = |text: &str| json!([{"type":"text", "text":text}]); + for contents in [ + vec![array("key: <> end")], + vec![json!("key: <> end")], + vec![array("key: <> end")], + vec![json!([ + {"type":"text", "text":"key: <>"}]}, + {"type":"text", "text":"RET_1>> end"} + ])], + ] { + let mut frames: Vec<_> = contents + .into_iter() + .map(|content| chat(json!({"content":content}), Value::Null)) + .collect(); + frames.push(chat(json!({}), json!("stop"))); + let out = run(Dialect::Chat, &frames); + let text: String = values(&out) + .iter() + .flat_map(|v| { + let content = &v["choices"][0]["delta"]["content"]; + content.as_str().into_iter().chain( + content + .as_array() + .into_iter() + .flatten() + .filter(|p| p["type"] == "text") + .filter_map(|p| p["text"].as_str()), + ) + }) + .collect(); + assert_eq!(text, format!("key: {KEY} end"), "{out}"); + if out.contains("unchanged") { + assert!(out.contains("unchanged <>"), "{out}"); + } + } + } + #[test] fn a_chat_tail_is_written_as_a_chat_chunk() { // 以前补的一律是 Anthropic 的 delta —— Chat 客户端不认识它,那几个字就丢了 From 27bbb8d53ef7a91b711ca97961e6e28ab45f4d4f Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:56:44 +0800 Subject: [PATCH 5/7] chore(release): prepare Core 0.89.2 Ship the reviewed redaction, native system proxy and Mistral response fixes together. Bump workspace packages and document the verified behavior and remaining report limitations. --- Cargo.lock | 44 ++++++++++++++++++++--------------------- Cargo.toml | 2 +- release-notes/0.89.2.md | 11 +++++++++++ 3 files changed, 34 insertions(+), 23 deletions(-) create mode 100644 release-notes/0.89.2.md diff --git a/Cargo.lock b/Cargo.lock index 27c506ea..3fd56d9b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3763,7 +3763,7 @@ dependencies = [ [[package]] name = "tw-api" -version = "0.89.1" +version = "0.89.2" dependencies = [ "serde", "serde_json", @@ -3774,7 +3774,7 @@ dependencies = [ [[package]] name = "tw-bedrock" -version = "0.89.1" +version = "0.89.2" dependencies = [ "aws-credential-types", "aws-sigv4", @@ -3795,7 +3795,7 @@ dependencies = [ [[package]] name = "tw-breaker" -version = "0.89.1" +version = "0.89.2" dependencies = [ "serde", "serde_json", @@ -3803,7 +3803,7 @@ dependencies = [ [[package]] name = "tw-config" -version = "0.89.1" +version = "0.89.2" dependencies = [ "blake3", "libc", @@ -3829,7 +3829,7 @@ dependencies = [ [[package]] name = "tw-control" -version = "0.89.1" +version = "0.89.2" dependencies = [ "axum", "base64 0.22.1", @@ -3875,7 +3875,7 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.89.1" +version = "0.89.2" dependencies = [ "memchr", "serde", @@ -3884,7 +3884,7 @@ dependencies = [ [[package]] name = "tw-engine" -version = "0.89.1" +version = "0.89.2" dependencies = [ "chrono", "serde", @@ -3898,7 +3898,7 @@ dependencies = [ [[package]] name = "tw-gateway" -version = "0.89.1" +version = "0.89.2" dependencies = [ "arc-swap", "async-stream", @@ -3950,7 +3950,7 @@ dependencies = [ [[package]] name = "tw-guard" -version = "0.89.1" +version = "0.89.2" dependencies = [ "aho-corasick", "base64 0.22.1", @@ -3971,7 +3971,7 @@ dependencies = [ [[package]] name = "tw-handover" -version = "0.89.1" +version = "0.89.2" dependencies = [ "libc", "serde", @@ -3984,7 +3984,7 @@ dependencies = [ [[package]] name = "tw-link" -version = "0.89.1" +version = "0.89.2" dependencies = [ "serde", "serde_json", @@ -3998,7 +3998,7 @@ dependencies = [ [[package]] name = "tw-observe" -version = "0.89.1" +version = "0.89.2" dependencies = [ "tokio", "tracing", @@ -4007,7 +4007,7 @@ dependencies = [ [[package]] name = "tw-pack" -version = "0.89.1" +version = "0.89.2" dependencies = [ "age", "blake3", @@ -4031,7 +4031,7 @@ dependencies = [ [[package]] name = "tw-plugin" -version = "0.89.1" +version = "0.89.2" dependencies = [ "libc", "rand 0.10.2", @@ -4047,7 +4047,7 @@ dependencies = [ [[package]] name = "tw-pricing" -version = "0.89.1" +version = "0.89.2" dependencies = [ "arc-swap", "flate2", @@ -4060,14 +4060,14 @@ dependencies = [ [[package]] name = "tw-secret" -version = "0.89.1" +version = "0.89.2" dependencies = [ "thiserror 2.0.20", ] [[package]] name = "tw-store" -version = "0.89.1" +version = "0.89.2" dependencies = [ "blake3", "bytes", @@ -4087,7 +4087,7 @@ dependencies = [ [[package]] name = "tw-sync" -version = "0.89.1" +version = "0.89.2" dependencies = [ "age", "axum", @@ -4115,7 +4115,7 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.89.1" +version = "0.89.2" dependencies = [ "serde", "serde_json", @@ -4124,7 +4124,7 @@ dependencies = [ [[package]] name = "tw-watch" -version = "0.89.1" +version = "0.89.2" dependencies = [ "libc", "notify", @@ -4135,7 +4135,7 @@ dependencies = [ [[package]] name = "tw-yaml" -version = "0.89.1" +version = "0.89.2" dependencies = [ "saphyr-parser", "serde_yaml_ng", @@ -4145,7 +4145,7 @@ dependencies = [ [[package]] name = "twcore" -version = "0.89.1" +version = "0.89.2" dependencies = [ "anyhow", "axum", diff --git a/Cargo.toml b/Cargo.toml index beb2f2fd..dc8504c0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,7 +61,7 @@ categories = ["network-programming", "web-programming::http-server"] # 二进制走 CalVer,crate 走 SemVer —— 两者是两回事,卖给不同的人。 # 这里是 crate 的版本。 -version = "0.89.1" +version = "0.89.2" [workspace.dependencies] # ── 内部 crate ─────────────────────────────────────────── diff --git a/release-notes/0.89.2.md b/release-notes/0.89.2.md new file mode 100644 index 00000000..871da6d1 --- /dev/null +++ b/release-notes/0.89.2.md @@ -0,0 +1,11 @@ +This release improves credential detection, native system proxy support and compatibility with Mistral responses. + +- Reduce credential false positives in source code and pool logs. Comma-separated values require a quoted credential field name, unquoted recovery phrases stop at code delimiters, and Rust numeric types and short numeric lookup keys are excluded. Explicit credentials and quoted secret values remain covered. +- Preserve structural array indices in security hit paths while continuing to mask request-derived field names. +- Upstreams configured to use the system proxy can now read native macOS and Windows proxy settings. Applying or reloading configuration rebuilds those clients to refresh the settings. Direct and explicitly configured proxy modes retain their own routing behavior. +- Accept both string and typed array content in streaming and non-streaming Chat responses, including Mistral text and thinking chunks. Text is forwarded incrementally, and thinking stays separate from visible text. +- Restore placeholders split across array text fragments or transitions between string and array content before response format conversion. Thinking content and signatures remain untouched. + +The Mistral changes fix reproduced content-loss cases; they do not establish the cause of every delay or truncation reported in Lite issue #407. System proxy settings are refreshed when configuration is applied or reloaded, rather than watched continuously. + +The control-plane protocol and request-store schema are unchanged. No configuration or database migration is required. From 60cc0347f1b027451023191fc2b6196d0ceb84b1 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:09:41 +0800 Subject: [PATCH 6/7] test(gateway): make release smoke and reload checks deterministic Wait until the upstream has received the held request before rebuilding a listener so the test proves that an actual in-flight request survives. Select the smoke fixture's named default route explicitly and verify that Bedrock requests use its intended rule. --- crates/tw-gateway/tests/hotreload.rs | 127 ++++++++++++++++----------- scripts/smoke.sh | 4 +- 2 files changed, 80 insertions(+), 51 deletions(-) diff --git a/crates/tw-gateway/tests/hotreload.rs b/crates/tw-gateway/tests/hotreload.rs index 8dd3fcc8..4be11625 100644 --- a/crates/tw-gateway/tests/hotreload.rs +++ b/crates/tw-gateway/tests/hotreload.rs @@ -616,23 +616,41 @@ async fn a_port_already_taken_keeps_the_old_listener_and_says_why() { assert!(state.listening().error.is_none()); } +/// 等测试放行才回答:先确认请求真的到了上游,再切换监听器。 +/// 固定睡眠无法保证此前提,读取系统代理或 CI 调度都可能推迟客户端建连。 +async fn held_upstream() -> ( + SocketAddr, + Arc, + Arc, +) { + let entered = Arc::new(tokio::sync::Notify::new()); + let release = Arc::new(tokio::sync::Notify::new()); + let app = Router::new().fallback(any({ + let entered = entered.clone(); + let release = release.clone(); + move || { + let entered = entered.clone(); + let release = release.clone(); + async move { + entered.notify_one(); + release.notified().await; + axum::response::Response::builder() + .header("content-type", "application/json") + .body(axum::body::Body::from(r#"{"by":"slow"}"#)) + .unwrap() + } + } + })); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (addr, entered, release) +} + #[tokio::test] async fn a_request_in_flight_survives_the_listener_being_rebuilt() { - // **新的先起来,老的停止接受新连接并等现有请求自然结束**。 - // 一个跑了六分钟的流不该因为你改了个端口而断掉。 - let slow = { - let app = Router::new().fallback(any(|| async { - tokio::time::sleep(Duration::from_millis(600)).await; - axum::response::Response::builder() - .header("content-type", "application/json") - .body(axum::body::Body::from(r#"{"by":"slow"}"#)) - .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 - }; + // 新端口开始服务时,旧请求仍在上游等待;放行后必须自然完成。 + let (slow, entered, release) = held_upstream().await; let mut c = cfg(vec![provider("slow", slow)], vec![]); let (p1, p2) = (spare_port(), spare_port()); c.listen.gateway.port = p1; @@ -640,7 +658,10 @@ async fn a_request_in_flight_survives_the_listener_being_rebuilt() { following(&state, &c).await; let inflight = tokio::spawn(async move { - reqwest::Client::new() + reqwest::Client::builder() + .no_proxy() + .build() + .unwrap() .post(format!("http://127.0.0.1:{p1}/v1/messages")) .header("x-api-key", "tw-k") .timeout(Duration::from_secs(10)) @@ -648,24 +669,31 @@ async fn a_request_in_flight_survives_the_listener_being_rebuilt() { .send() .await }); - tokio::time::sleep(Duration::from_millis(120)).await; + tokio::time::timeout(Duration::from_secs(5), entered.notified()) + .await + .expect("the old request never reached its upstream"); let mut next = c.clone(); next.listen.gateway.port = p2; - state.reload(next).unwrap(); - - // **新端口不等旧请求跑完就要能连。**以前是等旧的那一个排空了才去绑 - // 新的 —— 一个长的流在跑时,这几分钟里两边都不接新连接 - tokio::time::sleep(Duration::from_millis(80)).await; - assert!(!inflight.is_finished(), "测试的前提:旧请求还在跑"); - let probe = tokio::net::TcpStream::connect(("127.0.0.1", p2)).await; - assert!(probe.is_ok(), "旧请求还没跑完,新端口就该能连了"); + switch(&state, next).await; + assert_eq!(state.listening().error, None); + assert!( + !inflight.is_finished(), + "the old request must still be in flight" + ); + assert!( + tokio::net::TcpStream::connect(("127.0.0.1", p2)) + .await + .is_ok(), + "the new port must accept connections while the old request is running" + ); - let r = inflight + release.notify_one(); + let response = inflight .await .unwrap() - .expect("换监听器把跑到一半的请求掐了"); - assert_eq!(r.status(), 200); - assert!(r.text().await.unwrap().contains("slow")); + .expect("rebuilding the listener cut off the old request"); + assert_eq!(response.status(), 200); + assert!(response.text().await.unwrap().contains("slow")); } fn bind(raw: &str) -> tw_config::Bind { @@ -745,20 +773,8 @@ async fn the_pre_save_check_does_not_call_our_own_port_taken() { #[tokio::test] async fn a_request_in_flight_survives_the_old_listener_giving_way() { - // 旧的先让出端口时,**让的只是监听**:已经连上、跑到一半的请求照常跑完 - let slow = { - let app = Router::new().fallback(any(|| async { - tokio::time::sleep(Duration::from_millis(600)).await; - axum::response::Response::builder() - .header("content-type", "application/json") - .body(axum::body::Body::from(r#"{"by":"slow"}"#)) - .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 - }; + // 旧的先让出端口时,只让出监听;已经到达上游的请求仍须完整返回。 + let (slow, entered, release) = held_upstream().await; let mut c = cfg(vec![provider("slow", slow)], vec![]); let port = spare_port(); c.listen.gateway.port = port; @@ -767,7 +783,10 @@ async fn a_request_in_flight_survives_the_old_listener_giving_way() { following(&state, &c).await; let inflight = tokio::spawn(async move { - reqwest::Client::new() + reqwest::Client::builder() + .no_proxy() + .build() + .unwrap() .post(format!("http://127.0.0.1:{port}/v1/messages")) .header("x-api-key", "tw-k") .timeout(Duration::from_secs(10)) @@ -775,23 +794,31 @@ async fn a_request_in_flight_survives_the_old_listener_giving_way() { .send() .await }); - tokio::time::sleep(Duration::from_millis(120)).await; + tokio::time::timeout(Duration::from_secs(5), entered.notified()) + .await + .expect("the old request never reached its upstream"); let mut next = c.clone(); next.listen.gateway.bind = bind("127.0.0.1"); switch(&state, next).await; assert_eq!(state.listening().error, None); - assert!(!inflight.is_finished(), "测试的前提:旧请求还在跑"); + assert!( + !inflight.is_finished(), + "the old request must still be in flight" + ); assert!( tokio::net::TcpStream::connect(("127.0.0.1", port)) .await .is_ok(), - "旧请求还没跑完,新的监听就该能连了" + "the rebuilt listener must accept connections while the old request is running" ); - let r = inflight + + release.notify_one(); + let response = inflight .await .unwrap() - .expect("让出端口把跑到一半的请求掐了"); - assert_eq!(r.status(), 200); + .expect("giving way cut off the old request"); + assert_eq!(response.status(), 200); + assert!(response.text().await.unwrap().contains("slow")); } #[tokio::test] diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 0ffeda10..2fb7874c 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -209,6 +209,7 @@ python3 - "$CFG" "$UPPORT" "$PORT" <<'PY' import sys, io cfg, upport, port = sys.argv[1], sys.argv[2], sys.argv[3] io.open(cfg, 'w', encoding='utf-8').write(f"""version: 1 +default_route: 默认 listen: gateway: port: {port} @@ -477,7 +478,8 @@ for _ in $(seq 1 20); do | python3 -c 'import sys, json rows = json.load(sys.stdin) r = rows[0] if rows else {} -good = r.get("provider") == "bedrock" and r.get("input_tokens") == 31 and r.get("output_tokens") == 3 +good = (r.get("provider") == "bedrock" and r.get("input_tokens") == 31 and r.get("output_tokens") == 3 + and r.get("routing", {}).get("rule") == "Bedrock 的模型走 Bedrock") print("ok" if good else json.dumps(r, ensure_ascii=False, sort_keys=True))' 2>/dev/null) [ "$GOT" = "ok" ] && break sleep 0.25 From 03fd0d6356ab8fa43891404e7656786a23e7c99e Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:13:35 +0800 Subject: [PATCH 7/7] test(gateway): synchronize the live speed sampling window Native proxy discovery can delay a test client beyond the fixed startup sleep. Keep loopback requests direct and hold upstream output until the request is actually observed, so the speed assertions sample the intended phase. --- crates/tw-gateway/tests/live_speed.rs | 69 +++++++++++++++++++-------- 1 file changed, 49 insertions(+), 20 deletions(-) diff --git a/crates/tw-gateway/tests/live_speed.rs b/crates/tw-gateway/tests/live_speed.rs index e98fb76f..51cc3272 100644 --- a/crates/tw-gateway/tests/live_speed.rs +++ b/crates/tw-gateway/tests/live_speed.rs @@ -4,6 +4,7 @@ //! 起真网关、真上游:要验的是「流到一半」那一刻总线上的读数,单元测试里只能假装。 use std::net::SocketAddr; +use std::sync::Arc; use std::time::Duration; use axum::Router; @@ -29,22 +30,32 @@ async fn listen(app: Router) -> SocketAddr { } /// 开场帧马上发,读完输入之后每 `every` 吐一段,一共 `deltas` 段,最后报累计输出 -fn streaming(deltas: usize, every: Duration) -> Router { - Router::new().fallback(any(move || async move { - let body = async_stream::stream! { - yield Ok::<_, std::io::Error>(Bytes::from_static(MESSAGE_START)); - tokio::time::sleep(PREFILL).await; - yield Ok(Bytes::from_static(TEXT_BLOCK)); - for _ in 0..deltas { - yield Ok(Bytes::from_static(TEXT_DELTA)); - tokio::time::sleep(every).await; - } - yield Ok(Bytes::from_static(MESSAGE_END)); - }; - axum::response::Response::builder() - .header("content-type", "text/event-stream") - .body(axum::body::Body::from_stream(body)) - .unwrap() +fn streaming( + deltas: usize, + every: Duration, + prefill_gate: Option>, +) -> Router { + Router::new().fallback(any(move || { + let prefill_gate = prefill_gate.clone(); + async move { + let body = async_stream::stream! { + yield Ok::<_, std::io::Error>(Bytes::from_static(MESSAGE_START)); + if let Some(gate) = prefill_gate { + gate.notified().await; + } + tokio::time::sleep(PREFILL).await; + yield Ok(Bytes::from_static(TEXT_BLOCK)); + for _ in 0..deltas { + yield Ok(Bytes::from_static(TEXT_DELTA)); + tokio::time::sleep(every).await; + } + yield Ok(Bytes::from_static(MESSAGE_END)); + }; + axum::response::Response::builder() + .header("content-type", "text/event-stream") + .body(axum::body::Body::from_stream(body)) + .unwrap() + } })) } @@ -83,7 +94,11 @@ async fn serve(cfg: Config) -> Gateway { } async fn ask(gw: SocketAddr) -> String { - reqwest::Client::new() + reqwest::Client::builder() + .no_proxy() + .timeout(Duration::from_secs(10)) + .build() + .unwrap() .post(format!("http://{gw}/v1/messages")) .header("x-api-key", "tw-k") .body(r#"{"model":"claude-sonnet-5","stream":true,"messages":[]}"#) @@ -99,17 +114,31 @@ async fn ask(gw: SocketAddr) -> String { /// 速度;开口之后每秒约 20 个(每 100 毫秒一段、一段估两个) #[tokio::test] async fn the_speed_is_there_while_the_stream_is_still_running() { - let up = listen(streaming(30, Duration::from_millis(100))).await; + let prefill_gate = Arc::new(tokio::sync::Notify::new()); + let up = listen(streaming( + 30, + Duration::from_millis(100), + Some(prefill_gate.clone()), + )) + .await; let gw = serve(cfg(up)).await; let request = tokio::spawn(ask(gw.addr)); - tokio::time::sleep(Duration::from_millis(200)).await; + // 客户端建连可能受调度影响;等请求真的开始,并把上游留在输出前。 + tokio::time::timeout(Duration::from_secs(5), async { + while gw.bus.live().running.is_empty() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the request never reached the gateway"); let live = gw.bus.live(); assert_eq!(live.running.len(), 1, "{live:?}"); assert_eq!(live.tokens_per_sec, Some(0)); assert_eq!(live.running[0].tokens_per_sec, None); assert_eq!(live.running[0].output_tokens, None); + prefill_gate.notify_one(); tokio::time::sleep(Duration::from_millis(1_600)).await; let live = gw.bus.live(); let r = &live.running[0]; @@ -131,7 +160,7 @@ async fn the_speed_is_there_while_the_stream_is_still_running() { /// 模型的估数乘 2(比例最多到 2) #[tokio::test] async fn a_finished_stream_teaches_the_estimate() { - let up = listen(streaming(30, Duration::from_millis(5))).await; + let up = listen(streaming(30, Duration::from_millis(5), None)).await; let gw = serve(cfg(up)).await; assert_eq!(gw.pace.ratio("up", "claude-sonnet-5"), 1.0); let text = ask(gw.addr).await;