From 79decbafd2667500a0ccbb6d9899380ac277955a Mon Sep 17 00:00:00 2001 From: Arihant Deva Date: Sat, 28 Nov 2026 14:49:41 -0500 Subject: [PATCH 1/3] fix(build): keep compile-only flags and their operands off the link line A CXXFLAGS carrying `-nostdinc++ -isystem /usr/include/c++/v1 --sysroot=` reaches the kit's CMake configure, becomes CMAKE_CXX_FLAGS, and CMake puts that variable on the link line as well as the compile line. build.rs filtered the fragments with a per-argument predicate, but split_fragment returns "-isystem" and its directory as two arguments: the flag was dropped and the bare directory was kept. The linker reads that as an input file and the build dies with ld: file cannot be mmap()ed, errno=22 (Invalid argument) path=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1 Two things were wrong. Operand-taking flags need their operand dropped with them, and two compile-only spellings were missing from the predicate: `--sysroot=` keeps its value inside the argument, and `-nostdinc` / `-nostdinc++` carry none. The filters move to build_link_args.rs so they can be tested -- cargo test never runs a build script's own #[cfg(test)] module -- and every operand-taking spelling (-isystem, -I, -F, -iframework, -iquote, -idirafter) now has a case, plus one pinning the exact flags that broke. Verified with CXXFLAGS still exported: cargo test is 630 + 1,590 across the suite, clippy -D warnings clean, test-ledger 0 missing. --- build.rs | 98 +------------------- build_link_args.rs | 137 ++++++++++++++++++++++++++++ tests/test_wally_build_link_args.rs | 127 ++++++++++++++++++++++++++ 3 files changed, 267 insertions(+), 95 deletions(-) create mode 100644 build_link_args.rs create mode 100644 tests/test_wally_build_link_args.rs diff --git a/build.rs b/build.rs index acd86873..847c8d70 100644 --- a/build.rs +++ b/build.rs @@ -317,6 +317,8 @@ fn link_native(build_env: &BTreeMap) { } } +include!("build_link_args.rs"); + fn read_json(path: &Path) -> serde_json::Value { let text = fs::read_to_string(path).unwrap_or_else(|e| { panic!( @@ -373,102 +375,8 @@ fn probe_link_args(reply: &Path, target: &str, config: &str) -> Vec { let mut args = Vec::new(); for fragment in &fragments { if let Some(text) = fragment["fragment"].as_str() { - args.extend( - split_fragment(text) - .into_iter() - .filter(|a| !is_compile_only(a)), - ); + args.extend(link_args_from(split_fragment(text))); } } args } - -/// GCC-style drivers get CMAKE_CXX_FLAGS on the link line too ("-O3 -DNDEBUG"); -/// harmless to a driver, fatal once passed straight to ld (the Swift host's -/// -Xlinker path). Keep only what linking needs. -fn is_compile_only(arg: &str) -> bool { - if arg.starts_with("-Wl,") { - return false; - } - if let Some(msvc) = arg.strip_prefix('/') { - return is_msvc_compile_only(msvc); - } - if matches!(arg, "-MD" | "-MDd" | "-MT" | "-MTd") { - return true; - } - [ - "-D", - "-U", - "-I", - "-O", - "-g", - "-W", - "-std=", - "-isystem", - "-pedantic", - ] - .iter() - .any(|p| arg.starts_with(p)) -} - -/// MSVC spells CMAKE_CXX_FLAGS with `/` (`/DWIN32 /EHsc /O2 /Ob2 /DNDEBUG`), and -/// `link.exe` warns LNK4044 on each one it is handed. `/D` is a define unless it -/// is one of the linker's own `/D…` options. -fn is_msvc_compile_only(opt: &str) -> bool { - const LINKER_D: [&str; 11] = [ - "DEBUG", - "DEBUGTYPE", - "DEF", - "DEFAULTLIB", - "DELAY", - "DELAYLOAD", - "DELAYSIGN", - "DEPENDENTLOADFLAG", - "DLL", - "DRIVER", - "DYNAMICBASE", - ]; - if let Some(define) = opt.strip_prefix('D') { - let name = define.split([':', '=']).next().unwrap_or(define); - let head = format!("D{name}").to_ascii_uppercase(); - return !LINKER_D.iter().any(|l| head == *l); - } - matches!( - opt, - "GR" | "GR-" | "MD" | "MDd" | "MT" | "MTd" | "Zi" | "Z7" | "utf-8" | "bigobj" | "MP" - ) || opt.starts_with("EH") - || opt.starts_with("std:") - || (opt.starts_with('O') && opt.len() <= 3 && !opt.contains(':')) - || (opt.len() == 2 && opt.starts_with('W') && opt.as_bytes()[1].is_ascii_digit()) -} - -/// A file API fragment can hold several arguments ("-framework IOKit", -/// "kernel32.lib user32.lib"); CMake double-quotes an argument with spaces. -fn split_fragment(text: &str) -> Vec { - let mut out = Vec::new(); - let mut current = String::new(); - let mut quoted = false; - let mut any = false; - for c in text.chars() { - match c { - '"' => { - quoted = !quoted; - any = true; - } - c if c.is_whitespace() && !quoted => { - if any { - out.push(std::mem::take(&mut current)); - any = false; - } - } - c => { - current.push(c); - any = true; - } - } - } - if any { - out.push(current); - } - out -} diff --git a/build_link_args.rs b/build_link_args.rs new file mode 100644 index 00000000..e64a9f77 --- /dev/null +++ b/build_link_args.rs @@ -0,0 +1,137 @@ +// The link-line filter `build.rs` applies to the kit's CMake `commandFragments`. +// +// A separate file with no dependencies, so `build.rs` and +// `tests/test_wally_build_link_args.rs` can both compile it: a build script's own +// `#[cfg(test)]` module is never run by `cargo test`. + +/// Drop the arguments a compiler driver needs and a linker does not, keeping +/// the ones whose value is a separate argument out of the same list. +/// +/// `split_fragment` gives "-isystem /dir" back as two entries, and a bare +/// directory is a link input: dropping the flag and keeping the path is what +/// turned a `CXXFLAGS` of `-nostdinc++ -isystem ${SDKROOT}/usr/include/c++/v1 +/// --sysroot=${SDKROOT}` into `ld: file cannot be mmap()ed ... usr/include/c++/v1`. +/// The same shape hides `-I`, `-F`, `-L`'s compile-only siblings and the +/// `--sysroot=` spelling, which takes its value inside the argument and +/// so leaked on its own. +pub fn link_args_from(chunk: Vec) -> Vec { + let mut kept = Vec::with_capacity(chunk.len()); + let mut rest = chunk.into_iter(); + while let Some(arg) = rest.next() { + if TAKES_SEPARATE_OPERAND.contains(&arg.as_str()) { + // Drop the flag and the argument it eats, whatever it looks like. + rest.next(); + continue; + } + if is_compile_only(&arg) { + continue; + } + kept.push(arg); + } + kept +} + +/// Compiler flags whose value arrives as the next argument. A pathlib entry +/// here never reaches the linker, and neither does its operand. +const TAKES_SEPARATE_OPERAND: [&str; 6] = [ + "-isystem", + "-I", + "-F", + "-iframework", + "-iquote", + "-idirafter", +]; + +/// GCC-style drivers get CMAKE_CXX_FLAGS on the link line too ("-O3 -DNDEBUG"); +/// harmless to a driver, fatal once passed straight to ld (the Swift host's +/// -Xlinker path). Keep only what linking needs. +pub fn is_compile_only(arg: &str) -> bool { + if arg.starts_with("-Wl,") { + return false; + } + if let Some(msvc) = arg.strip_prefix('/') { + return is_msvc_compile_only(msvc); + } + if matches!(arg, "-MD" | "-MDd" | "-MT" | "-MTd") { + return true; + } + [ + "-D", + "-U", + "-I", + "-O", + "-g", + "-W", + "-std=", + "-isystem", + "-pedantic", + // A compile-only sysroot is spelled with the value inside the + // argument, so it has no separate operand to drop with it. + "--sysroot", + "-nostdinc", + ] + .iter() + .any(|p| arg.starts_with(p)) +} + +/// MSVC spells CMAKE_CXX_FLAGS with `/` (`/DWIN32 /EHsc /O2 /Ob2 /DNDEBUG`), and +/// `link.exe` warns LNK4044 on each one it is handed. `/D` is a define unless it +/// is one of the linker's own `/D…` options. +pub fn is_msvc_compile_only(opt: &str) -> bool { + const LINKER_D: [&str; 11] = [ + "DEBUG", + "DEBUGTYPE", + "DEF", + "DEFAULTLIB", + "DELAY", + "DELAYLOAD", + "DELAYSIGN", + "DEPENDENTLOADFLAG", + "DLL", + "DRIVER", + "DYNAMICBASE", + ]; + if let Some(define) = opt.strip_prefix('D') { + let name = define.split([':', '=']).next().unwrap_or(define); + let head = format!("D{name}").to_ascii_uppercase(); + return !LINKER_D.iter().any(|l| head == *l); + } + matches!( + opt, + "GR" | "GR-" | "MD" | "MDd" | "MT" | "MTd" | "Zi" | "Z7" | "utf-8" | "bigobj" | "MP" + ) || opt.starts_with("EH") + || opt.starts_with("std:") + || (opt.starts_with('O') && opt.len() <= 3 && !opt.contains(':')) + || (opt.len() == 2 && opt.starts_with('W') && opt.as_bytes()[1].is_ascii_digit()) +} + +/// A file API fragment can hold several arguments ("-framework IOKit", +/// "kernel32.lib user32.lib"); CMake double-quotes an argument with spaces. +pub fn split_fragment(text: &str) -> Vec { + let mut out = Vec::new(); + let mut current = String::new(); + let mut quoted = false; + let mut any = false; + for c in text.chars() { + match c { + '"' => { + quoted = !quoted; + any = true; + } + c if c.is_whitespace() && !quoted => { + if any { + out.push(std::mem::take(&mut current)); + any = false; + } + } + c => { + current.push(c); + any = true; + } + } + } + if any { + out.push(current); + } + out +} diff --git a/tests/test_wally_build_link_args.rs b/tests/test_wally_build_link_args.rs new file mode 100644 index 00000000..26f9a81b --- /dev/null +++ b/tests/test_wally_build_link_args.rs @@ -0,0 +1,127 @@ +//! The link-line filter `build.rs` applies to the kit's CMake `commandFragments`. +//! +//! The filter lives in `build_link_args.rs` because a build script's own +//! `#[cfg(test)]` module is never run by `cargo test`; both sides compile that file. +//! +//! The regression these exist for: a `CXXFLAGS` of +//! `-nostdinc++ -isystem /usr/include/c++/v1 --sysroot=` reached the kit's +//! CMake configure, became `CMAKE_CXX_FLAGS`, and CMake put it on the link line too. +//! `split_fragment` returns `-isystem` and its directory as two arguments, so the +//! filter dropped the flag and kept the bare directory — which the linker reads as +//! an input file and dies on with +//! `ld: file cannot be mmap()ed, errno=22 ... /usr/include/c++/v1`. + +#![allow(dead_code)] + +#[path = "../build_link_args.rs"] +mod build_link_args; + +use build_link_args::{is_compile_only, is_msvc_compile_only, link_args_from, split_fragment}; + +const SDKROOT: &str = "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk"; + +fn kept(flags: &str) -> Vec { + link_args_from(split_fragment(flags)) +} + +/// The exact string that broke the build, dropped in full. +#[test] +fn a_compile_only_sysroot_never_reaches_the_linker() { + let flags = format!("-nostdinc++ -isystem {SDKROOT}/usr/include/c++/v1 --sysroot={SDKROOT}"); + assert!( + kept(&flags).is_empty(), + "compile-only flags must not become link inputs, got {:?}", + kept(&flags) + ); +} + +/// Every include flag whose value is a separate argument takes its directory +/// with it. Missing one spelling is exactly the shape of the bug. +#[test] +fn every_operand_taking_include_flag_drops_its_directory() { + for flag in [ + "-isystem", + "-I", + "-F", + "-iframework", + "-iquote", + "-idirafter", + ] { + // A real link argument trails the pair, so "nothing left" is a pass, + // not an empty-input fluke. + let flags = format!("{flag} /some/include/dir -Wl,-rpath,/keep"); + assert_eq!( + kept(&flags), + vec!["-Wl,-rpath,/keep".to_string()], + "{flag} left its operand behind on the link line" + ); + } +} + +/// `-nostdinc++` carries no operand but is still compile-only. +#[test] +fn nostdinc_is_dropped() { + assert!(is_compile_only("-nostdinc++")); + assert!(is_compile_only("-nostdinc")); +} + +/// The `--sysroot=` spelling keeps its value inside the argument, so it +/// leaks on its own even once operand-taking flags are paired. +#[test] +fn the_dot_spelling_of_sysroot_is_dropped() { + assert!(is_compile_only(&format!("--sysroot={SDKROOT}"))); + assert_eq!( + kept(&format!("--sysroot={SDKROOT}")), + Vec::::new(), + "an equals-form sysroot must not survive on its own" + ); +} + +/// What linking actually needs still comes through. +#[test] +fn linking_arguments_survive() { + let flags = "-O3 -DNDEBUG -isystem /skip -Wl,-rpath,/keep /keep/libfoo.a \ + -framework IOKit -lc++ -Wl,-force_load,/keep/libbar.a"; + assert_eq!( + kept(flags), + vec![ + "-Wl,-rpath,/keep".to_string(), + "/keep/libfoo.a".to_string(), + "-framework".to_string(), + "IOKit".to_string(), + "-lc++".to_string(), + "-Wl,-force_load,/keep/libbar.a".to_string(), + ] + ); +} + +/// A quoted fragment is one argument: its spaces are not separators, so a path +/// with a space in it reaches `link_args_from` whole. +#[test] +fn a_quoted_include_path_survives_split_fragment_intact() { + assert_eq!( + split_fragment(&format!("-isystem \"{SDKROOT}/usr/include/c++/v1\" -O2")), + vec![ + "-isystem".to_string(), + format!("{SDKROOT}/usr/include/c++/v1"), + "-O2".to_string(), + ] + ); +} + +/// `-D` is a define at compile time and a linker-switch prefix otherwise, so +/// the bare spelling drops while the linker's own `/D…` names do not. +#[test] +fn msvc_linker_switches_are_not_mistaken_for_defines() { + for keep in ["DEBUG", "DLL", "DEF:out.def", "DYNAMICBASE"] { + assert!( + !is_msvc_compile_only(keep), + "/{keep} is a linker switch and must survive" + ); + } + for drop in [ + "DWIN32", "D_DEBUG", "EHsc", "GR-", "O2", "Zi", "MD", "utf-8", + ] { + assert!(is_msvc_compile_only(drop), "/{drop} is compile-only"); + } +} From 2748ec97ada137cdf95a3fe042a9bc5bfafcd9f0 Mon Sep 17 00:00:00 2001 From: Arihant Deva Date: Sat, 28 Nov 2026 14:49:54 -0500 Subject: [PATCH 2/3] fix(codex): declare the codex harness on every upstream request The Responses translator sent only a User-Agent, on the stated grounds that the contract's Harness enum had no Codex member. It has had one since 7f97280 ("contracts: sync the CLI contract from InferenceInfra staging (release 2's contract family and the codex harness)"), which regenerated console_contract.rs with `Harness::KCodex => "codex"`. The comment was written on 4513e23, five days before that sync, and was never revisited. So a Codex session was attributed by the server's User-Agent fallback instead of by declaration, while the Anthropic bridge declared claude_code and claude_desktop and the config writers declared opencode, openclaw and deepseek. inference.runanywhere.ai attributes usage and the harness column in the ledger from that header, and RA_REASONING_ALLOWANCE_HARNESS_ONLY gates the reasoning allowance on a recognised harness: an undeclared Codex session is at the mercy of a substring match. Send HARNESS_HEADER with the contract's own spelling, next to the User-Agent, which stays because harness.py's User-Agent table matches on it too. The existing end-to-end case now asserts the header; it fails with the header removed (left: None, right: Some("codex")). --- src/codex/server.rs | 20 +++++++++++++++----- tests/test_wally_codex.rs | 4 ++++ 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/src/codex/server.rs b/src/codex/server.rs index d8a602c1..94fd273b 100644 --- a/src/codex/server.rs +++ b/src/codex/server.rs @@ -11,7 +11,10 @@ use crate::anthropic::translate::{ UpstreamFailureBody, MAX_IMAGES_PER_REQUEST, }; use crate::codex::translate::{self, error_body, failure_code, StreamState}; -use crate::harness::{fit_reasoning_effort, text_only_ids, CatalogModel, Endpoint}; +use crate::harness::{ + fit_reasoning_effort, harness_header_value, text_only_ids, CatalogModel, DeclaredHarness, + Endpoint, HARNESS_HEADER, +}; use crate::io::output::{error_line, status_line}; use crate::net::decompress::Decoder; use crate::net::http1::{ResponseWriter, Server, ServerHandle, ServerRequest}; @@ -362,9 +365,10 @@ fn stop_running_instance() { runtime.upstream.drain_cancels(); } -/// The `User-Agent` sent upstream. The contract's `Harness` enum has no Codex -/// member, so there is no `X-RA-Harness` to declare; the agent string names it -/// the way `upstream_user_agent` names the others. +/// The `User-Agent` sent upstream. It names the harness the way +/// `upstream_user_agent` names the others; the `X-RA-Harness` header comes from +/// that same function, because the contract does carry `codex` +/// (`Harness::KCodex`, added with release 2's contract family). pub fn upstream_user_agent() -> String { format!("wally/{} (codex)", crate::WALLY_VERSION) } @@ -405,7 +409,13 @@ pub fn start( log_tag: "codex", stopping: AtomicBool::new(false), cancels: relay::cancel_worker(&upstream.console_url, &upstream.api_key), - headers: vec![("User-Agent".to_string(), upstream_user_agent())], + headers: vec![ + ( + HARNESS_HEADER.to_string(), + harness_header_value(DeclaredHarness::KCodex).to_string(), + ), + ("User-Agent".to_string(), upstream_user_agent()), + ], }, model: model.to_string(), catalog: cached_model_ids(), diff --git a/tests/test_wally_codex.rs b/tests/test_wally_codex.rs index b86fbe4c..45968a69 100644 --- a/tests/test_wally_codex.rs +++ b/tests/test_wally_codex.rs @@ -847,6 +847,10 @@ fn a_streamed_turn_goes_through_end_to_end() { Some("Bearer test-upstream-key") ); assert!(header("User-Agent").unwrap().ends_with("(codex)")); + // The contract carries `codex`, so the shim declares it instead of leaving + // the server to guess from the User-Agent alone. Regression: the header was + // never sent, because a comment claimed the enum had no Codex member. + assert_eq!(header("X-RA-Harness").as_deref(), Some("codex")); } #[test] From 568be8a31d23d105a6747e8ac08b45842ab3ac89 Mon Sep 17 00:00:00 2001 From: Arihant Deva Date: Sat, 28 Nov 2026 15:12:51 -0500 Subject: [PATCH 3/3] fix(harness): reuse one upstream connection in the image gate, keep Content-Encoding The gate that trims resent images built a fresh `ureq::Agent` inside `forward`, so the agent's connection pool was born and died with each request. Every turn paid a full TCP + TLS handshake to the hosted endpoint. `codex::start` names exactly that cost as its reason for skipping the gate on a hosted Codex session: "not through `harness::image_gate`: the gate opens a new TLS connection for every request (measured at ~200 ms of added time to first token)" One agent is now built in `start` and moved into the handler, so turns share keep-alive connections the way the translators' `UpstreamPool` does. The idle age is raised to 120s because a coding session sits idle between turns and the 15s default expires before the next prompt, handing back the handshake this change exists to avoid. Two smaller things on the same path: - `Content-Encoding` from the upstream reply is now forwarded. The request's `Accept-Encoding` was already forwarded, so the editor asked for an encoded reply. ureq is built here without its gzip or brotli features, so it hands the body back untouched and leaves the header on; this crate's own client decodes whatever the header declares. Dropping it meant advertising an encoding the editor could no longer see. ureq strips the header itself whenever it does decode (`run.rs`), so forwarding it is correct for both cases. - On the non-streaming path the reader is dropped before the client write, so a stopped reader cannot hold a pooled connection open. Four cases in `image_gate`'s own module, where `cargo test` actually runs them: four turns ride one accepted connection (a fresh agent per request accepts four), the shared path still trims nine resent images to the gateway's eight, other paths forward byte-for-byte, and an encoded reply keeps its `Content-Encoding` (that one reads the gate over a raw socket, since this crate's client would decode it and answer for the decoder instead of the header). Scope: `src/harness/image_gate.rs` only. No change to what the gate rewrites, to which harnesses use it, or to any translator. --- src/harness/image_gate.rs | 355 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 336 insertions(+), 19 deletions(-) diff --git a/src/harness/image_gate.rs b/src/harness/image_gate.rs index beae42b8..16ef0fba 100644 --- a/src/harness/image_gate.rs +++ b/src/harness/image_gate.rs @@ -5,11 +5,22 @@ //! from earlier turns block a new one. This gate drops the oldest earlier //! images before the request is forwarded. MiMo takes none, so its images //! become a note instead. +//! +//! The upstream connection is pooled. A fresh `ureq::Agent` per request owns a +//! fresh connection pool, so every turn would pay a full TCP + TLS handshake; +//! `codex::start` cites that cost as its reason for not using this gate at all. +//! One agent is built in `start` and moved into the handler, so turns share +//! keep-alive connections the way the translators' `UpstreamPool` does. use crate::anthropic::translate::{self, MAX_IMAGES_PER_REQUEST}; use crate::net::http1::{ResponseWriter, Server, ServerRequest}; use std::io::Read; +/// How long an idle upstream connection is kept for reuse. A coding session +/// sits idle between turns, so the default 15s would expire before the next +/// prompt and hand back the handshake we are trying to avoid. +const IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120); + /// `http://127.0.0.1:/v1` forwarding to `upstream_origin` (no `/v1`). /// The server lives until this process exits: the harness is a child, and /// dropping the handle would stop the gate before the child sent anything. @@ -22,13 +33,32 @@ pub fn start(upstream_origin: &str, api_key: &str) -> Option { return None; } let api_key = api_key.to_string(); + let agent = upstream_agent(); let mut server = Server::new(); - server.not_found(move |request, writer| forward(&origin, &api_key, request, writer)); + server.not_found(move |request, writer| forward(&origin, &api_key, &agent, request, writer)); let (handle, port) = server.bind_and_run("127.0.0.1").ok()?; std::mem::forget(handle); Some(format!("http://127.0.0.1:{port}/v1")) } +/// One agent for the life of the gate, so its connection pool is shared across +/// requests instead of rebuilt per turn. +fn upstream_agent() -> ureq::Agent { + let config = ureq::Agent::config_builder() + .http_status_as_error(false) + .max_redirects(0) + .timeout_global(None) + .max_idle_age(IDLE_TIMEOUT) + .tls_config( + ureq::tls::TlsConfig::builder() + .provider(ureq::tls::TlsProvider::NativeTls) + .root_certs(ureq::tls::RootCerts::PlatformVerifier) + .build(), + ) + .build(); + ureq::Agent::new_with_config(config) +} + fn rewrite(path: &str, body: &[u8]) -> Vec { if !path.ends_with("/chat/completions") { return body.to_vec(); @@ -51,7 +81,13 @@ fn rewrite(path: &str, body: &[u8]) -> Vec { serde_json::to_vec(&parsed).unwrap_or_else(|_| body.to_vec()) } -fn forward(origin: &str, api_key: &str, request: &ServerRequest, writer: &mut ResponseWriter<'_>) { +fn forward( + origin: &str, + api_key: &str, + agent: &ureq::Agent, + request: &ServerRequest, + writer: &mut ResponseWriter<'_>, +) { let query = if request.query.is_empty() { String::new() } else { @@ -59,18 +95,6 @@ fn forward(origin: &str, api_key: &str, request: &ServerRequest, writer: &mut Re }; let url = format!("{origin}{}{query}", request.path); let body = rewrite(&request.path, &request.body); - let config = ureq::Agent::config_builder() - .http_status_as_error(false) - .max_redirects(0) - .timeout_global(None) - .tls_config( - ureq::tls::TlsConfig::builder() - .provider(ureq::tls::TlsProvider::NativeTls) - .root_certs(ureq::tls::RootCerts::PlatformVerifier) - .build(), - ) - .build(); - let agent = ureq::Agent::new_with_config(config); let mut builder = ureq::http::Request::builder() .method(request.method.as_str()) .uri(&url); @@ -110,13 +134,28 @@ fn forward(origin: &str, api_key: &str, request: &ServerRequest, writer: &mut Re .and_then(|value| value.to_str().ok()) .unwrap_or("application/json") .to_string(); + // `Content-Encoding` is forwarded because the body is forwarded as ureq + // delivered it. ureq only decodes when its own gzip/brotli features are on + // (they are not), and it strips the header exactly when it decodes + // (`run.rs`, "If the body will be decompressed, strip Content-Encoding"). + // Dropping it for a body that is still gzip would hand the editor + // compressed bytes it has no way to know are compressed: the request's own + // `Accept-Encoding` is forwarded a few lines above, so the editor did ask + // for this encoding and must be told the reply carries it. + let content_encoding = response + .headers() + .get("content-encoding") + .and_then(|value| value.to_str().ok()) + .filter(|value| !value.is_empty() && !value.eq_ignore_ascii_case("identity")) + .map(str::to_owned); + let mut response_headers = vec![("Content-Type", content_type.as_str())]; + if let Some(encoding) = content_encoding.as_deref() { + response_headers.push(("Content-Encoding", encoding)); + } let streaming = content_type.contains("text/event-stream"); let mut reader = response.into_body().into_reader(); if streaming { - if writer - .begin_chunked(status, &[("Content-Type", &content_type)]) - .is_err() - { + if writer.begin_chunked(status, &response_headers).is_err() { return; } let mut buf = [0u8; 8192]; @@ -138,6 +177,284 @@ fn forward(origin: &str, api_key: &str, request: &ServerRequest, writer: &mut Re let _ = writer.send_full(502, &[("Content-Type", "text/plain")], b"bad gateway"); return; } - let _ = writer.send_full(status, &[("Content-Type", &content_type)], &collected); + // `into_body()` took the response, so this reader owns the connection. + // Dropping it returns that connection to the pool before the client + // write, and an editor that stopped reading this reply cannot hold it + // open. The body is already copied. + drop(reader); + let _ = writer.send_full(status, &response_headers, &collected); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::net::http1::{Client, Request}; + use std::net::{SocketAddr, TcpListener, TcpStream}; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::{Arc, Mutex}; + use std::time::Duration; + + /// A gzip `Content-Encoding` on the upstream reply must reach the editor. + /// The request's own `Accept-Encoding` is forwarded, so the editor asked for + /// an encoded reply and a proxy that swallows the header hands it bytes it + /// cannot know are compressed. ureq leaves the body untouched when its gzip + /// feature is off, which is how this crate is built. + #[test] + fn an_encoded_reply_keeps_its_content_encoding() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + std::thread::spawn(move || { + for socket in listener.incoming().flatten() { + let mut socket = socket; + // Read until the request is complete: headers and a + // `Content-Length` body can arrive in separate packets, and + // replying after the first one truncates the request. + let mut buf = [0u8; 8192]; + let _ = socket.set_read_timeout(Some(Duration::from_secs(5))); + let mut seen = Vec::new(); + while !seen.windows(4).any(|w| w == b"\r\n\r\n") { + match socket.read(&mut buf) { + Ok(0) | Err(_) => break, + Ok(n) => seen.extend_from_slice(&buf[..n]), + } + } + let head_len = seen + .windows(4) + .position(|w| w == b"\r\n\r\n") + .map(|i| i + 4) + .unwrap_or(seen.len()); + let declared = String::from_utf8_lossy(&seen[..head_len]) + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse::().ok())? + }) + .unwrap_or(0); + while seen.len() < head_len + declared { + match socket.read(&mut buf) { + Ok(0) | Err(_) => break, + Ok(n) => seen.extend_from_slice(&buf[..n]), + } + } + // A real gzip member for `{}`, so the body is well formed + // whether or not this build decodes it. + const GZIP_BODY: [u8; 23] = [ + 0x1f, 0x8b, 0x08, 0x00, 0xa8, 0x33, 0x0b, 0x6b, 0x00, 0x03, 0xab, 0xae, 0x05, + 0x00, 0x43, 0xbf, 0xa6, 0xa3, 0x02, 0x00, 0x00, 0x00, 0x00, + ]; + eprintln!( + "FAKE got {} bytes: {:?}", + seen.len(), + String::from_utf8_lossy(&seen[..head_len.min(seen.len())]) + ); + let mut head = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\ + Content-Encoding: gzip\r\nContent-Length: {}\r\n\r\n", + GZIP_BODY.len() + ) + .into_bytes(); + head.extend_from_slice(&GZIP_BODY); + let _ = socket.write_all(&head); + let _ = socket.flush(); + } + }); + + let gate = start(&format!("http://127.0.0.1:{port}"), "k").expect("gate starts"); + // Read the gate's reply over a plain socket: this crate's `Client` + // decodes whatever encoding the reply declares, which would answer for + // the decoder instead of for the header under test. + let gate_port: u16 = gate + .rsplit(':') + .next() + .and_then(|rest| rest.split('/').next()) + .and_then(|port| port.parse().ok()) + .expect("gate port"); + let mut socket = TcpStream::connect(("127.0.0.1", gate_port)).unwrap(); + socket + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + use std::io::{Read as _, Write as _}; + socket + .write_all( + b"POST /v1/chat/completions HTTP/1.1\r\nhost: gate\r\n\ + content-type: application/json\r\naccept-encoding: gzip\r\n\ + content-length: 2\r\n\r\n{}", + ) + .unwrap(); + let mut reply = Vec::new(); + let mut buf = [0u8; 4096]; + while let Ok(n) = socket.read(&mut buf) { + if n == 0 { + break; + } + reply.extend_from_slice(&buf[..n]); + if reply.windows(4).any(|w| w == b"\r\n\r\n") + && reply.len() >= { + // Headers plus the 23-byte gzip member. + reply + .windows(4) + .position(|w| w == b"\r\n\r\n") + .map(|i| i + 4 + 23) + .unwrap_or(usize::MAX) + } + { + break; + } + } + let head = String::from_utf8_lossy(&reply).to_string(); + assert!( + head.to_ascii_lowercase().contains("content-encoding: gzip"), + "the editor asked for gzip and the reply still carries it, got:\n{head}" + ); + assert!( + reply.windows(2).any(|w| w == [0x1f, 0x8b]), + "the gzip body must reach the editor untouched" + ); + } + + /// A plain-HTTP origin that counts the connections it accepts, so a reused + /// keep-alive socket is one accept and a fresh one is two. + fn counting_origin(replies: usize) -> (String, Arc, ServerHandleGuard) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let listener_addr = listener.local_addr().unwrap(); + let port = listener_addr.port(); + let accepts = Arc::new(AtomicUsize::new(0)); + let counter = accepts.clone(); + let stop = Arc::new(Mutex::new(false)); + let flag = stop.clone(); + let handle = std::thread::spawn(move || { + for socket in listener.incoming().flatten() { + if *flag.lock().unwrap() { + return; + } + counter.fetch_add(1, Ordering::SeqCst); + std::thread::spawn(move || serve(socket, replies)); + } + }); + ( + format!("http://127.0.0.1:{port}"), + accepts, + ServerHandleGuard { + stop, + addr: listener_addr, + handle: Some(handle), + }, + ) + } + + /// Answers every request on this socket, so a client that reuses it stays + /// on the same accept. + fn serve(mut socket: TcpStream, replies: usize) { + use std::io::{Read, Write}; + let _ = socket.set_read_timeout(Some(Duration::from_secs(5))); + let mut answered = 0; + let mut buf = [0u8; 8192]; + loop { + match socket.read(&mut buf) { + Ok(0) | Err(_) => return, + Ok(_) => {} + } + if answered >= replies { + return; + } + answered += 1; + let _ = socket.write_all( + b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\n\r\n{}", + ); + let _ = socket.flush(); + } + } + + /// Stops the counting origin by waking the accept loop with one last + /// connection; `stop` makes it return instead of serving that socket. + struct ServerHandleGuard { + stop: Arc>, + addr: SocketAddr, + handle: Option>, + } + + impl Drop for ServerHandleGuard { + fn drop(&mut self) { + *self.stop.lock().unwrap() = true; + let _ = TcpStream::connect(self.addr); + if let Some(handle) = self.handle.take() { + let _ = handle.join(); + } + } + } + + /// An HTTP client against the gate, one request per call. + fn through_gate(gate: &str, path: &str) -> i32 { + let mut client = Client::new(gate, Duration::from_secs(5), Duration::from_secs(5)).unwrap(); + let request = Request::post(path, br#"{"model":"glm-5.3-flash","messages":[]}"#.to_vec()) + .header("Content-Type", "application/json"); + client.send(&request, None, None).unwrap().status + } + + /// The point of the change: turns share one upstream connection. A fresh + /// agent per request made that impossible, which is why the gate cost a + /// handshake every turn and `codex::start` refused to use it. + #[test] + fn turns_reuse_one_upstream_connection() { + let (origin, accepts, _guard) = counting_origin(8); + let gate = start(&origin, "k").expect("gate starts"); + for _ in 0..4 { + assert_eq!(through_gate(&gate, "/v1/chat/completions"), 200); + } + assert_eq!( + accepts.load(Ordering::SeqCst), + 1, + "four turns must ride one keep-alive connection, not four handshakes" + ); + } + + /// Rewriting still happens on the shared path: the images a later turn + /// resends are trimmed before the request leaves. + #[test] + fn the_shared_connection_still_trims_resent_images() { + assert_eq!(rewrite("/v1/chat/completions", b"{}"), b"{}"); + let nine: Vec = (0..9) + .map(|i| { + format!( + r#"{{"role":"user","content":[{{"type":"text","text":"t{i}"}},{{"type":"image_url","image_url":{{"url":"data:image/png;base64,AA=="}}}}]}}"# + ) + }) + .collect(); + let body = format!( + r#"{{"model":"glm-5.3-flash","messages":[{}]}}"#, + nine.join(",") + ); + let out = rewrite("/v1/chat/completions", body.as_bytes()); + let parsed: serde_json::Value = serde_json::from_slice(&out).unwrap(); + let images: usize = parsed["messages"] + .as_array() + .unwrap() + .iter() + .map(|message| { + message["content"] + .as_array() + .map(|parts| { + parts + .iter() + .filter(|part| part["type"] == "image_url") + .count() + }) + .unwrap_or(0) + }) + .sum(); + assert_eq!( + images, MAX_IMAGES_PER_REQUEST, + "nine resent images are trimmed to the gateway's limit" + ); + } + + /// A non-chat path is forwarded byte-for-byte; the gate must not rewrite a + /// model list or a cancel route. + #[test] + fn other_paths_are_forwarded_untouched() { + let body = br#"{"not":"a chat request"}"#; + assert_eq!(rewrite("/v1/models", body), body); } }