From 79decbafd2667500a0ccbb6d9899380ac277955a Mon Sep 17 00:00:00 2001 From: Arihant Deva Date: Sat, 28 Nov 2026 14:49:41 -0500 Subject: [PATCH 1/2] 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/2] 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]