From 5dedc3569881ec77248efe80fd1d23413536ade7 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 03:57:16 -0600 Subject: [PATCH 1/5] fleet(proxy): fail-fast transport deadline, single-flight recovery, stamped broker start (#5758) --- pkgs/fleet/crates/fleet-proxy/src/serve.rs | 233 +++++++++++++++++++- pkgs/fleet/crates/fleet-proxy/src/tunnel.rs | 136 +++++++++++- pkgs/fleet/crates/fleet-queue/src/client.rs | 65 +++++- 3 files changed, 412 insertions(+), 22 deletions(-) diff --git a/pkgs/fleet/crates/fleet-proxy/src/serve.rs b/pkgs/fleet/crates/fleet-proxy/src/serve.rs index d71d853f10..d4a5391824 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/serve.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/serve.rs @@ -245,10 +245,139 @@ impl TunnelPool { } } +/// How long a caller waits for another caller's in-flight +/// recovery of the same port before failing fast — the transport +/// deadline, so waiting never costs more than one bounded attempt. +const RECOVERY_WAIT: Duration = crate::tunnel::TRANSPORT_DEADLINE; + +#[derive(Default)] +struct GateState { + in_flight: bool, + active_generation: u64, + completed_generation: u64, + last_error: Option, + next_generation: u64, +} + +/// Single-flight tunnel recovery (#5758): at most one tunnel open +/// per port is ever in flight. Concurrent callers wait (bounded by +/// [`RECOVERY_WAIT`]) for the in-flight attempt: if it failed they +/// fail fast with that same error — no CONNECT stampede against a +/// dead target; if it succeeded they take their turn as the next +/// serialized opener, because the target is demonstrably back. +struct RecoveryGate { + state: Mutex>, + finished: Condvar, +} + +impl RecoveryGate { + fn new() -> RecoveryGate { + RecoveryGate { + state: Mutex::new(std::collections::HashMap::new()), + finished: Condvar::new(), + } + } + + fn run(&self, port: u16, attempt: impl FnOnce() -> Result) -> Result { + let deadline = Instant::now() + RECOVERY_WAIT; + let mut waiting_on: Option = None; + loop { + let mut state = self.state.lock().unwrap(); + let entry = state.entry(port).or_default(); + if entry.in_flight { + let generation = entry.active_generation; + if waiting_on != Some(generation) { + waiting_on = Some(generation); + } + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err(format!( + "tunnel recovery for port {port} still in flight; failing fast" + )); + } + let (guard, _) = self.finished.wait_timeout(state, left).unwrap(); + state = guard; + continue; + } + if let Some(generation) = waiting_on { + if entry.completed_generation == generation { + if let Some(err) = &entry.last_error { + // The attempt we waited on failed: share + // its verdict instead of CONNECTing again. + return Err(err.clone()); + } + // It succeeded: fall through and open our own + // tunnel as the next serialized attempt. + waiting_on = None; + } + } + // Become the one in-flight opener for this port. + let entry = state.entry(port).or_default(); + entry.next_generation += 1; + entry.active_generation = entry.next_generation; + entry.in_flight = true; + let generation = entry.active_generation; + drop(state); + let got = attempt(); + let mut state = self.state.lock().unwrap(); + let entry = state.entry(port).or_default(); + entry.in_flight = false; + entry.completed_generation = generation; + entry.last_error = match &got { + Ok(_) => None, + Err(e) => Some(e.clone()), + }; + self.finished.notify_all(); + return got; + } + } +} + +/// `YYYY-MM-DDTHH:MM:SSZ` for a unix timestamp — the broker's log +/// stamp, computed without a date crate (civil-from-days). +fn format_utc(secs: u64) -> String { + let days = (secs / 86_400) as i64; + let tod = secs % 86_400; + let z = days + 719_468; + let era = if z >= 0 { z } else { z - 146_096 } / 146_097; + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = if m <= 2 { y + 1 } else { y }; + format!( + "{year:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", + tod / 3600, + (tod % 3600) / 60, + tod % 60 + ) +} + +/// The one startup stamp every broker start writes first +/// (#5758): UTC time, implementation, version, pool size, and +/// pid — so which broker owned an incident window (and with what +/// pool) is reconstructable from broker.log alone. Credentials +/// are never part of it. +fn startup_line(pool_size: usize, socket_path: &std::path::Path) -> String { + format!( + "{} fleet proxy serve start implementation=fleet-proxy version={} pool_size={} pid={} socket={}", + format_utc(now_secs()), + env!("CARGO_PKG_VERSION"), + pool_size, + std::process::id(), + socket_path.display() + ) +} + struct Broker { config: Config, egress: Option, pool: TunnelPool, + /// Single-flight gate for tunnel opens (recovery stampedes). + recovery: RecoveryGate, /// Last client-request time (unix secs). Keepalive health /// checks deliberately never write this. last_used: AtomicU64, @@ -256,6 +385,13 @@ struct Broker { impl Broker { fn open_conn(&self, port: u16) -> Result { + // Every tunnel open goes through the single-flight gate: + // concurrent recovery for one port is one CONNECT, and a + // failed attempt's verdict is shared with its waiters. + self.recovery.run(port, || self.open_conn_raw(port)) + } + + fn open_conn_raw(&self, port: u16) -> Result { let target = self.config.target_host(); let stream: TcpStream = if self.config.proxy_direct() { connect_tunnel(None, target, port) @@ -583,6 +719,12 @@ pub fn run(config: &Config) -> i32 { return crate::EXIT_TRANSPORT; } }; + let size = pool_size(); + // The stamp is the FIRST line a starting broker writes, so it + // precedes any per-request tunnel failure the egress setup + // below may log. + println!("{}", startup_line(size, &socket_path)); + let _ = std::io::stdout().flush(); let egress = if config.proxy_direct() { None } else { @@ -600,7 +742,8 @@ pub fn run(config: &Config) -> i32 { let broker = Arc::new(Broker { config: config.clone(), egress, - pool: TunnelPool::new(pool_size()), + pool: TunnelPool::new(size), + recovery: RecoveryGate::new(), last_used: AtomicU64::new(now_secs()), }); // Preconnect: warm the laptop-agent pool through the same @@ -635,13 +778,6 @@ pub fn run(config: &Config) -> i32 { } }); } - println!( - "fleet proxy serve on {} (pool: {} per port, overflow wait {} ms)", - socket_path.display(), - broker.pool.size(), - POOL_WAIT_BUDGET.as_millis() - ); - let _ = std::io::stdout().flush(); for stream in listener.incoming() { match stream { Ok(stream) => { @@ -805,4 +941,85 @@ mod tests { assert_eq!(pool.idle_count(PORT), 0); assert_eq!(pool.live_count(PORT), 0); } + + #[test] + fn single_flight_failure_is_shared_by_all_waiters() { + // Fault injection (#5758): N concurrent callers hit a dead + // target; exactly ONE recovery attempt runs and every + // waiter fails fast with its verdict — no stampede. + let gate = Arc::new(RecoveryGate::new()); + let attempts = Arc::new(AtomicU64::new(0)); + let mut handles = Vec::new(); + for _ in 0..8 { + let gate = Arc::clone(&gate); + let attempts = Arc::clone(&attempts); + handles.push(std::thread::spawn(move || { + gate.run(PORT, || { + attempts.fetch_add(1, Ordering::Relaxed); + std::thread::sleep(Duration::from_millis(150)); + Err::<(), String>("tunnel to laptop:4799: refused".to_string()) + }) + })); + } + for h in handles { + let got = h.join().unwrap(); + assert_eq!( + got.unwrap_err(), + "tunnel to laptop:4799: refused".to_string() + ); + } + assert_eq!(attempts.load(Ordering::Relaxed), 1); + } + + #[test] + fn single_flight_serializes_successful_opens() { + // On success each caller still gets its own tunnel, but + // never concurrently: the in-flight count peaks at 1. + let gate = Arc::new(RecoveryGate::new()); + let in_flight = Arc::new(AtomicU64::new(0)); + let peak = Arc::new(AtomicU64::new(0)); + let mut handles = Vec::new(); + for _ in 0..4 { + let gate = Arc::clone(&gate); + let in_flight = Arc::clone(&in_flight); + let peak = Arc::clone(&peak); + handles.push(std::thread::spawn(move || { + gate.run(PORT, || { + let now = in_flight.fetch_add(1, Ordering::Relaxed) + 1; + peak.fetch_max(now, Ordering::Relaxed); + std::thread::sleep(Duration::from_millis(30)); + in_flight.fetch_sub(1, Ordering::Relaxed); + Ok::<(), String>(()) + }) + })); + } + for h in handles { + assert!(h.join().unwrap().is_ok()); + } + assert_eq!(peak.load(Ordering::Relaxed), 1); + } + + #[test] + fn startup_line_carries_the_incident_stamps() { + assert_eq!(format_utc(0), "1970-01-01T00:00:00Z"); + assert_eq!(format_utc(951_782_400), "2000-02-29T00:00:00Z"); + assert_eq!(format_utc(951_782_400 + 3661), "2000-02-29T01:01:01Z"); + // Pool size default is untouched by this change (#5758.5). + assert_eq!(DEFAULT_POOL_SIZE, 50); + let line = startup_line(50, std::path::Path::new("/tmp/broker.sock")); + assert!(line.contains("implementation=fleet-proxy"), "{line}"); + assert!( + line.contains(&format!("version={}", env!("CARGO_PKG_VERSION"))), + "{line}" + ); + assert!(line.contains("pool_size=50"), "{line}"); + assert!( + line.contains(&format!("pid={}", std::process::id())), + "{line}" + ); + assert!(line.contains("socket=/tmp/broker.sock"), "{line}"); + // Shape: " fleet proxy serve start …". + let stamp = line.split(' ').next().unwrap(); + assert!(stamp.ends_with('Z') && stamp.contains('T'), "{line}"); + } } diff --git a/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs b/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs index 965ff5e389..c0ee512b27 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs @@ -12,11 +12,62 @@ //! URL names — again, exactly as the Python does it. use std::io::{Read, Write}; -use std::net::TcpStream; -use std::time::Duration; +use std::net::{TcpStream, ToSocketAddrs}; +use std::time::{Duration, Instant}; -/// Handshake timeout for opening a tunnel (the Python's 60 s). -const CONNECT_TIMEOUT: Duration = Duration::from_secs(60); +/// Total deadline for transport setup/recovery (#5758): opening a +/// tunnel — TCP connect plus the CONNECT handshake — either +/// completes within this budget or fails, so a dead target costs a +/// caller seconds at most, never the old 60 s handshake timeout +/// stacked on retries (trips showed 16–26 s failed-trip p50). The +/// budget bounds SETUP only: once a tunnel is established the +/// 660 s read timeout below applies, unchanged — that allowance +/// belongs to daemon-side exec duration, not transport. +pub const TRANSPORT_DEADLINE: Duration = Duration::from_secs(2); + +fn remaining(deadline: Duration, start: Instant) -> Option { + let left = deadline.saturating_sub(start.elapsed()); + if left.is_zero() { None } else { Some(left) } +} + +fn deadline_exceeded(what: &str, deadline: Duration) -> std::io::Error { + std::io::Error::new( + std::io::ErrorKind::TimedOut, + format!( + "{what} exceeded the {} ms transport deadline", + deadline.as_millis() + ), + ) +} + +/// TCP connect bounded by the transport deadline (the inherent +/// `TcpStream::connect` has no timeout at all — the OS default is +/// minutes on a dead route). +fn connect_tcp( + host: &str, + port: u16, + deadline: Duration, + start: Instant, +) -> std::io::Result { + let addrs: Vec<_> = (host, port).to_socket_addrs()?.collect(); + if addrs.is_empty() { + return Err(std::io::Error::new( + std::io::ErrorKind::AddrNotAvailable, + format!("{host} resolved to no addresses"), + )); + } + let mut last_err: Option = None; + for addr in &addrs { + let Some(left) = remaining(deadline, start) else { + return Err(deadline_exceeded("TCP connect", deadline)); + }; + match TcpStream::connect_timeout(addr, left) { + Ok(stream) => return Ok(stream), + Err(e) => last_err = Some(e), + } + } + Err(last_err.unwrap_or_else(|| deadline_exceeded("TCP connect", deadline))) +} /// Read/write timeouts once a tunnel carries HTTP (the Python /// broker's HTTPConnection timeout is 660 s). pub const TUNNEL_READ_TIMEOUT: Duration = Duration::from_secs(660); @@ -142,15 +193,31 @@ pub fn connect_tunnel( target_host: &str, target_port: u16, ) -> std::io::Result { + connect_tunnel_with_deadline(egress, target_host, target_port, TRANSPORT_DEADLINE) +} + +/// [`connect_tunnel`] with the transport deadline supplied — the +/// fault-injection tests use a short deadline against a silent +/// peer; production always passes [`TRANSPORT_DEADLINE`]. +pub fn connect_tunnel_with_deadline( + egress: Option<&Egress>, + target_host: &str, + target_port: u16, + deadline: Duration, +) -> std::io::Result { + let start = Instant::now(); match egress { None => { - let stream = TcpStream::connect((target_host, target_port))?; + let stream = connect_tcp(target_host, target_port, deadline, start)?; tune(&stream); Ok(stream) } Some(egress) => { - let mut stream = TcpStream::connect((egress.host.as_str(), egress.port))?; - stream.set_read_timeout(Some(CONNECT_TIMEOUT))?; + let mut stream = connect_tcp(&egress.host, egress.port, deadline, start)?; + let left = remaining(deadline, start) + .ok_or_else(|| deadline_exceeded("CONNECT handshake", deadline))?; + stream.set_read_timeout(Some(left))?; + stream.set_write_timeout(Some(left))?; let request = format!( "CONNECT {target_host}:{target_port} HTTP/1.1\r\n\ Host: {target_host}:{target_port}\r\n\ @@ -160,9 +227,15 @@ pub fn connect_tunnel( ); stream.write_all(request.as_bytes())?; // Byte-wise until the blank line — see the doc comment. + // The read timeout is re-armed to the remaining budget + // on every byte, so a peer that trickles headers cannot + // stretch the handshake past the total deadline. let mut buf: Vec = Vec::with_capacity(256); let mut byte = [0u8; 1]; while !buf.ends_with(b"\r\n\r\n") { + let left = remaining(deadline, start) + .ok_or_else(|| deadline_exceeded("CONNECT handshake", deadline))?; + stream.set_read_timeout(Some(left))?; let n = stream.read(&mut byte)?; if n == 0 { return Err(std::io::Error::new( @@ -238,4 +311,53 @@ mod tests { assert!(egress_from_url("http://:3128", 3130).is_err()); assert!(egress_from_url("", 3130).is_err()); } + + #[test] + fn transport_deadline_bounds_setup_not_established_tunnels() { + // The #5758 split: setup/recovery is capped at 2 s, while + // an established tunnel keeps the 660 s exec allowance. + assert_eq!(TRANSPORT_DEADLINE, Duration::from_secs(2)); + assert_eq!(TUNNEL_READ_TIMEOUT, Duration::from_secs(660)); + } + + #[test] + fn silent_connect_peer_fails_within_the_deadline() { + // Fault injection: a peer that accepts TCP but never + // answers the CONNECT. Pre-fix this read hung for the + // 60 s handshake timeout; the deadline must cut it off. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let silent = std::thread::spawn(move || { + let (_peer, _) = listener.accept().unwrap(); + std::thread::sleep(Duration::from_secs(2)); + }); + let egress = Egress { + host: "127.0.0.1".to_string(), + port, + authorization: "Basic eA==".to_string(), + }; + let t0 = Instant::now(); + let got = + connect_tunnel_with_deadline(Some(&egress), "laptop", 4799, Duration::from_millis(200)); + let elapsed = t0.elapsed(); + assert!(got.is_err(), "silent peer must not yield a tunnel"); + assert!( + elapsed < Duration::from_millis(1500), + "failed setup took {elapsed:?}, deadline was 200 ms" + ); + silent.join().unwrap(); + } + + #[test] + fn refused_direct_target_fails_fast() { + // A port nothing listens on: the bounded connect returns + // promptly instead of riding an OS-scale timeout. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + drop(listener); + let t0 = Instant::now(); + let got = connect_tunnel_with_deadline(None, "127.0.0.1", port, TRANSPORT_DEADLINE); + assert!(got.is_err()); + assert!(t0.elapsed() < TRANSPORT_DEADLINE, "took {:?}", t0.elapsed()); + } } diff --git a/pkgs/fleet/crates/fleet-queue/src/client.rs b/pkgs/fleet/crates/fleet-queue/src/client.rs index b281f1d95e..c86cbf3998 100644 --- a/pkgs/fleet/crates/fleet-queue/src/client.rs +++ b/pkgs/fleet/crates/fleet-queue/src/client.rs @@ -203,21 +203,36 @@ fn unix_roundtrip(data: &[u8]) -> Result { fn broker_program() -> (String, Vec) { if let Ok(exe) = std::env::current_exe() { if let Some(dir) = exe.parent() { - let fleet = dir.join("fleet"); - if fleet.exists() { - return ( - fleet.to_string_lossy().into_owned(), - vec!["proxy".to_string(), "serve".to_string()], - ); - } + return broker_program_in(dir); } } + python_broker_program() +} + +fn python_broker_program() -> (String, Vec) { ( "python3".to_string(), vec![format!("{}/tools/laptop-agent-broker.py", home())], ) } +/// The selection rule, pure over the directory beside the running +/// binary so it is testable without touching the real install +/// (#5758): a sibling `fleet` binary ALWAYS wins — no auto-start +/// path may spawn the Python broker while a fleet binary exists; +/// Python is the fallback for the standalone rollback builds that +/// ship without one. +fn broker_program_in(dir: &std::path::Path) -> (String, Vec) { + let fleet = dir.join("fleet"); + if fleet.exists() { + return ( + fleet.to_string_lossy().into_owned(), + vec!["proxy".to_string(), "serve".to_string()], + ); + } + python_broker_program() +} + fn spawn_broker() { let dir = format!("{}/.cache/laptop-agent", home()); let _ = std::fs::create_dir_all(&dir); @@ -1757,4 +1772,40 @@ mod tests { prop_assert_eq!(out, row); } } + + #[test] + fn broker_program_prefers_a_sibling_fleet_binary() { + // #5758 acceptance: while a fleet binary exists beside the + // running one, auto-start spawns `fleet proxy serve` — + // never the Python broker. + let dir = + std::env::temp_dir().join(format!("fleet-queue-broker-program-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("fleet"), b"#!/bin/sh\n").unwrap(); + let (program, args) = broker_program_in(&dir); + assert_eq!(program, dir.join("fleet").to_string_lossy()); + assert_eq!(args, vec!["proxy".to_string(), "serve".to_string()]); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn broker_program_falls_back_to_python_without_a_sibling() { + // The standalone rollback builds (no fleet beside them) + // keep the Python spawn. + let dir = std::env::temp_dir().join(format!( + "fleet-queue-broker-program-none-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (program, args) = broker_program_in(&dir); + assert_eq!(program, "python3"); + assert_eq!(args.len(), 1); + assert!( + args[0].ends_with("/tools/laptop-agent-broker.py"), + "{args:?}" + ); + let _ = std::fs::remove_dir_all(&dir); + } } From 5af36206dcd8fc380697ec89781638c158604629 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 04:03:44 -0600 Subject: [PATCH 2/5] =?UTF-8?q?fleet(proxy):=20recovery-only=20single-flig?= =?UTF-8?q?ht=20=E2=80=94=20healthy=20opens=20stay=20concurrent,=20waiters?= =?UTF-8?q?=20keep=20their=20generation=20verdict=20(#5758,=20PR=20#6490?= =?UTF-8?q?=20Codex=20P1+P2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkgs/fleet/crates/fleet-proxy/src/serve.rs | 202 +++++++++++++++------ 1 file changed, 144 insertions(+), 58 deletions(-) diff --git a/pkgs/fleet/crates/fleet-proxy/src/serve.rs b/pkgs/fleet/crates/fleet-proxy/src/serve.rs index d4a5391824..4eada6c768 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/serve.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/serve.rs @@ -245,26 +245,35 @@ impl TunnelPool { } } -/// How long a caller waits for another caller's in-flight -/// recovery of the same port before failing fast — the transport -/// deadline, so waiting never costs more than one bounded attempt. +/// How long a caller waits for an in-flight recovery of the same +/// port before failing fast — the transport deadline, so waiting +/// never costs more than one bounded attempt. const RECOVERY_WAIT: Duration = crate::tunnel::TRANSPORT_DEADLINE; #[derive(Default)] struct GateState { - in_flight: bool, + /// A tunnel open failed and no recovery has succeeded since: + /// the next opener is the single recovery attempt. + needs_recovery: bool, + recovery_in_flight: bool, active_generation: u64, completed_generation: u64, last_error: Option, next_generation: u64, } -/// Single-flight tunnel recovery (#5758): at most one tunnel open -/// per port is ever in flight. Concurrent callers wait (bounded by -/// [`RECOVERY_WAIT`]) for the in-flight attempt: if it failed they -/// fail fast with that same error — no CONNECT stampede against a -/// dead target; if it succeeded they take their turn as the next -/// serialized opener, because the target is demonstrably back. +/// Single-flight tunnel RECOVERY (#5758, shaped by PR #6490's +/// Codex review): healthy opens are NOT gated — a cold pool or a +/// burst opens concurrently exactly as before. The gate engages +/// only after a failure: the next opener for that port becomes +/// the one recovery attempt, and concurrent callers wait (bounded +/// by [`RECOVERY_WAIT`]) for its verdict — failure is shared with +/// the waiters (no CONNECT stampede against a dead target); +/// success clears the gate and waiters proceed to their own, +/// concurrent opens. A waiter always consumes the verdict of the +/// generation it waited on BEFORE looking at any newer attempt, +/// so an opener's immediate retry can never steal or overwrite +/// the failure its cohort observed. struct RecoveryGate { state: Mutex>, finished: Condvar, @@ -281,14 +290,27 @@ impl RecoveryGate { fn run(&self, port: u16, attempt: impl FnOnce() -> Result) -> Result { let deadline = Instant::now() + RECOVERY_WAIT; let mut waiting_on: Option = None; - loop { + // Phase 1: decide — wait for an in-flight recovery, share + // its failure, or become an opener (recovery or normal). + let (recovery, generation) = loop { let mut state = self.state.lock().unwrap(); let entry = state.entry(port).or_default(); - if entry.in_flight { - let generation = entry.active_generation; - if waiting_on != Some(generation) { - waiting_on = Some(generation); + // Consume the waited-on generation's verdict FIRST, + // before any newer in-flight attempt can overwrite + // what this caller observed (Codex P2, PR #6490). + if let Some(wgen) = waiting_on { + if entry.completed_generation == wgen { + match &entry.last_error { + Some(err) => return Err(err.clone()), + None => { + // Recovery succeeded: open ungated. + break (false, 0); + } + } } + } + if entry.recovery_in_flight { + waiting_on = Some(entry.active_generation); let left = deadline.saturating_duration_since(Instant::now()); if left.is_zero() { return Err(format!( @@ -299,37 +321,39 @@ impl RecoveryGate { state = guard; continue; } - if let Some(generation) = waiting_on { - if entry.completed_generation == generation { - if let Some(err) = &entry.last_error { - // The attempt we waited on failed: share - // its verdict instead of CONNECTing again. - return Err(err.clone()); - } - // It succeeded: fall through and open our own - // tunnel as the next serialized attempt. - waiting_on = None; - } + if entry.needs_recovery { + entry.next_generation += 1; + entry.active_generation = entry.next_generation; + entry.recovery_in_flight = true; + entry.needs_recovery = false; + break (true, entry.active_generation); } - // Become the one in-flight opener for this port. - let entry = state.entry(port).or_default(); - entry.next_generation += 1; - entry.active_generation = entry.next_generation; - entry.in_flight = true; - let generation = entry.active_generation; - drop(state); - let got = attempt(); - let mut state = self.state.lock().unwrap(); - let entry = state.entry(port).or_default(); - entry.in_flight = false; + // Healthy path: no gate at all. + break (false, 0); + }; + // Phase 2: the attempt itself, outside the lock. + let got = attempt(); + // Phase 3: record the outcome. A failure (any mode) arms + // single-flight recovery for the next opener; a recovery + // success disarms it and releases its cohort. + let mut state = self.state.lock().unwrap(); + let entry = state.entry(port).or_default(); + if got.is_err() { + entry.needs_recovery = true; + } + if recovery { + entry.recovery_in_flight = false; entry.completed_generation = generation; entry.last_error = match &got { Ok(_) => None, Err(e) => Some(e.clone()), }; + if got.is_ok() { + entry.needs_recovery = false; + } self.finished.notify_all(); - return got; } + got } } @@ -385,9 +409,9 @@ struct Broker { impl Broker { fn open_conn(&self, port: u16) -> Result { - // Every tunnel open goes through the single-flight gate: - // concurrent recovery for one port is one CONNECT, and a - // failed attempt's verdict is shared with its waiters. + // Tunnel opens pass through the recovery gate: ungated + // while healthy, single-flight once an open has failed — + // see [`RecoveryGate`]. self.recovery.run(port, || self.open_conn_raw(port)) } @@ -943,38 +967,45 @@ mod tests { } #[test] - fn single_flight_failure_is_shared_by_all_waiters() { - // Fault injection (#5758): N concurrent callers hit a dead - // target; exactly ONE recovery attempt runs and every - // waiter fails fast with its verdict — no stampede. + fn recovery_failure_is_shared_by_all_waiters() { + // Fault injection (#5758): one failure arms the gate; + // then N concurrent callers produce exactly ONE recovery + // attempt and every waiter fails fast with its verdict — + // no CONNECT stampede against a dead target. let gate = Arc::new(RecoveryGate::new()); let attempts = Arc::new(AtomicU64::new(0)); + let attempt = |attempts: &Arc| { + attempts.fetch_add(1, Ordering::Relaxed); + std::thread::sleep(Duration::from_millis(150)); + Err::<(), String>("tunnel to laptop:4799: refused".to_string()) + }; + // Prime: a normal-mode failure arms single-flight recovery. + let priming = gate.run(PORT, || attempt(&attempts)); + assert!(priming.is_err()); + assert_eq!(attempts.load(Ordering::Relaxed), 1); let mut handles = Vec::new(); for _ in 0..8 { let gate = Arc::clone(&gate); let attempts = Arc::clone(&attempts); handles.push(std::thread::spawn(move || { - gate.run(PORT, || { - attempts.fetch_add(1, Ordering::Relaxed); - std::thread::sleep(Duration::from_millis(150)); - Err::<(), String>("tunnel to laptop:4799: refused".to_string()) - }) + gate.run(PORT, || attempt(&attempts)) })); } for h in handles { - let got = h.join().unwrap(); assert_eq!( - got.unwrap_err(), + h.join().unwrap().unwrap_err(), "tunnel to laptop:4799: refused".to_string() ); } - assert_eq!(attempts.load(Ordering::Relaxed), 1); + // Priming + exactly one shared recovery attempt. + assert_eq!(attempts.load(Ordering::Relaxed), 2); } #[test] - fn single_flight_serializes_successful_opens() { - // On success each caller still gets its own tunnel, but - // never concurrently: the in-flight count peaks at 1. + fn healthy_opens_proceed_concurrently() { + // Codex P1 on PR #6490: the gate must NOT serialize the + // healthy path — a cold-pool burst opens in parallel, so + // nobody times out queued behind successful CONNECTs. let gate = Arc::new(RecoveryGate::new()); let in_flight = Arc::new(AtomicU64::new(0)); let peak = Arc::new(AtomicU64::new(0)); @@ -987,7 +1018,7 @@ mod tests { gate.run(PORT, || { let now = in_flight.fetch_add(1, Ordering::Relaxed) + 1; peak.fetch_max(now, Ordering::Relaxed); - std::thread::sleep(Duration::from_millis(30)); + std::thread::sleep(Duration::from_millis(100)); in_flight.fetch_sub(1, Ordering::Relaxed); Ok::<(), String>(()) }) @@ -996,7 +1027,62 @@ mod tests { for h in handles { assert!(h.join().unwrap().is_ok()); } - assert_eq!(peak.load(Ordering::Relaxed), 1); + assert!( + peak.load(Ordering::Relaxed) > 1, + "healthy opens were serialized (peak {})", + peak.load(Ordering::Relaxed) + ); + } + + #[test] + fn waiter_keeps_its_generations_verdict_despite_a_retry() { + // Codex P2 on PR #6490: a waiter on a failed recovery + // generation must consume THAT verdict even if the + // opener's immediate retry starts a newer generation + // before the waiter reacquires the lock. + let gate = Arc::new(RecoveryGate::new()); + // Prime the gate into recovery mode (attempt #1). + let n = Arc::new(AtomicU64::new(0)); + let mk = |n: &Arc, ms: u64| { + let k = n.fetch_add(1, Ordering::Relaxed) + 1; + std::thread::sleep(Duration::from_millis(ms)); + Err::<(), String>(format!("failure-{k}")) + }; + assert_eq!(gate.run(PORT, || mk(&n, 0)).unwrap_err(), "failure-1"); + // Leader: recovery attempt #2 (slow fail), then an + // immediate retry = attempt #3 (even slower fail). + let leader = { + let gate = Arc::clone(&gate); + let n = Arc::clone(&n); + std::thread::spawn(move || { + let first = gate.run(PORT, || mk(&n, 200)); + let second = gate.run(PORT, || mk(&n, 600)); + (first, second) + }) + }; + // Waiter arrives while attempt #2 is in flight. + std::thread::sleep(Duration::from_millis(50)); + let waited = gate.run(PORT, || mk(&n, 0)); + // The waiter shares attempt #2's verdict — it neither + // waits for nor reports attempt #3's. + assert_eq!(waited.unwrap_err(), "failure-2"); + let (first, second) = leader.join().unwrap(); + assert_eq!(first.unwrap_err(), "failure-2"); + assert_eq!(second.unwrap_err(), "failure-3"); + } + + #[test] + fn successful_recovery_disarms_the_gate() { + // After a recovery succeeds, opens are concurrent again. + let gate = Arc::new(RecoveryGate::new()); + assert!( + gate.run(PORT, || Err::<(), String>("dead".to_string())) + .is_err() + ); + assert!(gate.run(PORT, || Ok::<(), String>(())).is_ok()); + // needs_recovery cleared: a later failure is a fresh + // normal-mode failure, and the gate re-arms only then. + assert!(gate.run(PORT, || Ok::<(), String>(())).is_ok()); } #[test] From 8242f6acc8b8e03480528c617fd646ee9ab1fc76 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 04:10:31 -0600 Subject: [PATCH 3/5] fleet(proxy): model-based property test for RecoveryGate + per-generation verdicts (#5758, PR #6490 Codex round 2) --- pkgs/fleet/crates/fleet-proxy/src/serve.rs | 300 +++++++++++++++++---- 1 file changed, 246 insertions(+), 54 deletions(-) diff --git a/pkgs/fleet/crates/fleet-proxy/src/serve.rs b/pkgs/fleet/crates/fleet-proxy/src/serve.rs index 4eada6c768..f04c091df2 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/serve.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/serve.rs @@ -257,9 +257,78 @@ struct GateState { needs_recovery: bool, recovery_in_flight: bool, active_generation: u64, - completed_generation: u64, - last_error: Option, next_generation: u64, + /// Verdict of each completed recovery generation (None = + /// success), kept per generation so a waiter always reads the + /// verdict of the generation IT waited on, never a successor's. + /// Pruned to the most recent generations (see `record`). + verdicts: std::collections::HashMap>, +} + +/// What [`decide`] tells a caller to do next — the gate's pure +/// decision core, driven synchronously by the model-based +/// property test and under the condvar by [`RecoveryGate::run`]. +#[derive(Debug, PartialEq, Eq)] +enum Decision { + /// Healthy path: open now, ungated. + OpenNormal, + /// You are the one recovery attempt, generation attached. + OpenRecovery(u64), + /// A recovery is in flight: wait for this generation. + Wait(u64), + /// The generation you waited on failed: share its verdict. + ShareFailure(String), + /// The generation you waited on succeeded: open ungated. + ProceedAfterRecovery, +} + +/// Pure gate decision for one caller. `waiting_on` is the +/// generation the caller has been waiting for, if any — its +/// verdict is consumed FIRST, before any newer in-flight attempt +/// is considered (Codex P2, PR #6490). +fn decide(entry: &mut GateState, waiting_on: Option) -> Decision { + if let Some(wgen) = waiting_on { + if let Some(verdict) = entry.verdicts.get(&wgen) { + return match verdict { + Some(err) => Decision::ShareFailure(err.clone()), + None => Decision::ProceedAfterRecovery, + }; + } + } + if entry.recovery_in_flight { + return Decision::Wait(entry.active_generation); + } + if entry.needs_recovery { + entry.next_generation += 1; + entry.active_generation = entry.next_generation; + entry.recovery_in_flight = true; + entry.needs_recovery = false; + return Decision::OpenRecovery(entry.active_generation); + } + Decision::OpenNormal +} + +/// Pure gate bookkeeping for a finished attempt. Any failure +/// arms recovery for the next opener; a recovery attempt also +/// records its generation's verdict (consumed by its waiters via +/// [`decide`]) and disarms the gate on success. Verdicts are +/// pruned to the last 64 generations — far beyond any live +/// waiter cohort. +fn record(entry: &mut GateState, recovery_generation: Option, error: Option<&String>) { + if error.is_some() { + entry.needs_recovery = true; + } + if let Some(generation) = recovery_generation { + entry.recovery_in_flight = false; + entry.verdicts.insert(generation, error.cloned()); + if error.is_none() { + entry.needs_recovery = false; + } + if entry.verdicts.len() > 64 { + let floor = generation.saturating_sub(64); + entry.verdicts.retain(|gnum, _| *gnum > floor); + } + } } /// Single-flight tunnel RECOVERY (#5758, shaped by PR #6490's @@ -290,67 +359,33 @@ impl RecoveryGate { fn run(&self, port: u16, attempt: impl FnOnce() -> Result) -> Result { let deadline = Instant::now() + RECOVERY_WAIT; let mut waiting_on: Option = None; - // Phase 1: decide — wait for an in-flight recovery, share - // its failure, or become an opener (recovery or normal). - let (recovery, generation) = loop { + let recovery_generation = loop { let mut state = self.state.lock().unwrap(); let entry = state.entry(port).or_default(); - // Consume the waited-on generation's verdict FIRST, - // before any newer in-flight attempt can overwrite - // what this caller observed (Codex P2, PR #6490). - if let Some(wgen) = waiting_on { - if entry.completed_generation == wgen { - match &entry.last_error { - Some(err) => return Err(err.clone()), - None => { - // Recovery succeeded: open ungated. - break (false, 0); - } + match decide(entry, waiting_on) { + Decision::ShareFailure(err) => return Err(err), + Decision::ProceedAfterRecovery => break None, + Decision::OpenNormal => break None, + Decision::OpenRecovery(generation) => break Some(generation), + Decision::Wait(generation) => { + waiting_on = Some(generation); + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err(format!( + "tunnel recovery for port {port} still in flight; failing fast" + )); } + let (guard, _) = self.finished.wait_timeout(state, left).unwrap(); + state = guard; + continue; } } - if entry.recovery_in_flight { - waiting_on = Some(entry.active_generation); - let left = deadline.saturating_duration_since(Instant::now()); - if left.is_zero() { - return Err(format!( - "tunnel recovery for port {port} still in flight; failing fast" - )); - } - let (guard, _) = self.finished.wait_timeout(state, left).unwrap(); - state = guard; - continue; - } - if entry.needs_recovery { - entry.next_generation += 1; - entry.active_generation = entry.next_generation; - entry.recovery_in_flight = true; - entry.needs_recovery = false; - break (true, entry.active_generation); - } - // Healthy path: no gate at all. - break (false, 0); }; - // Phase 2: the attempt itself, outside the lock. let got = attempt(); - // Phase 3: record the outcome. A failure (any mode) arms - // single-flight recovery for the next opener; a recovery - // success disarms it and releases its cohort. let mut state = self.state.lock().unwrap(); let entry = state.entry(port).or_default(); - if got.is_err() { - entry.needs_recovery = true; - } - if recovery { - entry.recovery_in_flight = false; - entry.completed_generation = generation; - entry.last_error = match &got { - Ok(_) => None, - Err(e) => Some(e.clone()), - }; - if got.is_ok() { - entry.needs_recovery = false; - } + record(entry, recovery_generation, got.as_ref().err()); + if recovery_generation.is_some() { self.finished.notify_all(); } got @@ -1085,6 +1120,163 @@ mod tests { assert!(gate.run(PORT, || Ok::<(), String>(())).is_ok()); } + // Model-based property test for the RecoveryGate decision + // core (Codex P1 round 2 on PR #6490; the repo testing + // doctrine: a state machine's invariants get a model and a + // generator, not only handwritten schedules). The MODEL is + // the oracle: an independent, minimal restatement of the + // gate spec — armed flag, the single in-flight recovery + // generation, and per-generation verdicts. Generated step + // sequences advance four simulated callers through the REAL + // `decide`/`record` functions; after every step the gate + // state must equal the model's, the decision must be the one + // the model predicts, and at most one simulated caller may + // hold a recovery opening. + #[derive(Debug, Clone, PartialEq)] + enum SimCaller { + New, + Waiting(u64), + Opening(Option, bool, String), + Done(Result<(), String>), + } + + #[test] + fn recovery_gate_matches_the_model_on_generated_interleavings() { + use proptest::prelude::*; + #[derive(Default)] + struct Model { + armed: bool, + in_flight: Option, + next_gen: u64, + verdicts: std::collections::HashMap>, + } + fn model_decide(m: &Model, waiting_on: Option) -> Decision { + if let Some(wgen) = waiting_on { + if let Some(verdict) = m.verdicts.get(&wgen) { + return match verdict { + Some(err) => Decision::ShareFailure(err.clone()), + None => Decision::ProceedAfterRecovery, + }; + } + } + if let Some(g) = m.in_flight { + return Decision::Wait(g); + } + if m.armed { + return Decision::OpenRecovery(m.next_gen + 1); + } + Decision::OpenNormal + } + let strategy = proptest::collection::vec((0usize..4, any::()), 0..48usize); + proptest!(|( + steps in strategy, + )| { + let mut entry = GateState::default(); + let mut model = Model::default(); + let mut callers = vec![SimCaller::New; 4]; + let mut attempts = 0u64; + let advance = |entry: &mut GateState, + model: &mut Model, + callers: &mut Vec, + ci: usize, + succeed: bool, + attempts: &mut u64| { + match callers[ci].clone() { + SimCaller::New | SimCaller::Waiting(_) => { + let waiting_on = match callers[ci] { + SimCaller::Waiting(g) => Some(g), + _ => None, + }; + let expected = model_decide(model, waiting_on); + let got = decide(entry, waiting_on); + prop_assert_eq!(&got, &expected); + match got { + Decision::ShareFailure(err) => { + // Oracle check: the shared error is + // exactly the waited generation's + // recorded verdict. + let wgen = waiting_on.unwrap(); + prop_assert_eq!( + Some(&Some(err.clone())), + model.verdicts.get(&wgen) + ); + callers[ci] = SimCaller::Done(Err(err)); + } + Decision::ProceedAfterRecovery | Decision::OpenNormal => { + *attempts += 1; + let label = format!("err-c{ci}-a{attempts}"); + callers[ci] = SimCaller::Opening(None, succeed, label); + } + Decision::OpenRecovery(g) => { + model.in_flight = Some(g); + model.next_gen = g; + model.armed = false; + *attempts += 1; + let label = format!("err-c{ci}-a{attempts}"); + callers[ci] = SimCaller::Opening(Some(g), succeed, label); + } + Decision::Wait(g) => { + callers[ci] = SimCaller::Waiting(g); + } + } + } + SimCaller::Opening(gnum, succeed, label) => { + let err = if succeed { None } else { Some(label.clone()) }; + record(entry, gnum, err.as_ref()); + if err.is_some() { + model.armed = true; + } + if let Some(g) = gnum { + model.in_flight = None; + model.verdicts.insert(g, err.clone()); + if err.is_none() { + model.armed = false; + } + } + callers[ci] = SimCaller::Done(if succeed { + Ok(()) + } else { + Err(label) + }); + } + SimCaller::Done(_) => {} + } + // State equality with the model after every step. + prop_assert_eq!(entry.needs_recovery, model.armed); + prop_assert_eq!(entry.recovery_in_flight, model.in_flight.is_some()); + prop_assert_eq!(entry.verdicts.len(), model.verdicts.len()); + for (g, v) in &model.verdicts { + prop_assert_eq!(entry.verdicts.get(g), Some(v)); + } + // Invariant: at most one recovery opening exists. + let recovery_openings = callers + .iter() + .filter(|c| matches!(c, SimCaller::Opening(Some(_), _, _))) + .count(); + prop_assert!(recovery_openings <= 1); + Ok(()) + }; + for (ci, succeed) in &steps { + advance(&mut entry, &mut model, &mut callers, *ci, *succeed, &mut attempts)?; + } + // Drain: with cooperative (succeeding) steps every + // caller must reach a terminal state — no caller is + // ever stranded waiting on a generation. + for _ in 0..200 { + if callers.iter().all(|c| matches!(c, SimCaller::Done(_))) { + break; + } + for ci in 0..4 { + advance(&mut entry, &mut model, &mut callers, ci, true, &mut attempts)?; + } + } + prop_assert!( + callers.iter().all(|c| matches!(c, SimCaller::Done(_))), + "callers stranded: {callers:?}" + ); + }); + } + #[test] fn startup_line_carries_the_incident_stamps() { assert_eq!(format_utc(0), "1970-01-01T00:00:00Z"); From 7eb4bbed99335c4f8ba5cf13ffbcb4db7612899d Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 04:17:10 -0600 Subject: [PATCH 4/5] fleet(proxy): split connect deadline across fallback addresses; smoke asserts the stamped startup line (#5758, PR #6490 Codex round 3) --- pkgs/fleet/crates/fleet-proxy/src/tunnel.rs | 36 +++++++++++++++++++-- pkgs/fleet/smoke.sh | 7 +++- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs b/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs index c0ee512b27..1348abe00c 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs @@ -56,12 +56,28 @@ fn connect_tcp( format!("{host} resolved to no addresses"), )); } + connect_addrs(&addrs, deadline, start) +} + +/// Try each resolved address in order under the shared deadline +/// (split per remaining address — see the loop body). +fn connect_addrs( + addrs: &[std::net::SocketAddr], + deadline: Duration, + start: Instant, +) -> std::io::Result { let mut last_err: Option = None; - for addr in &addrs { + let total = addrs.len(); + for (i, addr) in addrs.iter().enumerate() { let Some(left) = remaining(deadline, start) else { return Err(deadline_exceeded("TCP connect", deadline)); }; - match TcpStream::connect_timeout(addr, left) { + // Split the remaining budget across the addresses still + // untried (Codex P2, PR #6490): giving the first address + // the whole deadline lets a silently-dropping one starve + // reachable fallbacks behind it. + let share = left / (total - i) as u32; + match TcpStream::connect_timeout(addr, share) { Ok(stream) => return Ok(stream), Err(e) => last_err = Some(e), } @@ -348,6 +364,22 @@ mod tests { silent.join().unwrap(); } + #[test] + fn fallback_address_is_reached_after_a_dead_first_address() { + // Codex P2, PR #6490: the first address gets only its + // share of the deadline, so a reachable fallback behind + // a dead one is still tried. 10.255.255.1 is unroutable + // (instant error) or black-holed (share timeout) — both + // must fall through to the loopback listener. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let good = listener.local_addr().unwrap(); + let dead: std::net::SocketAddr = "10.255.255.1:65000".parse().unwrap(); + let t0 = Instant::now(); + let got = connect_addrs(&[dead, good], Duration::from_millis(600), t0); + assert!(got.is_ok(), "fallback never reached: {got:?}"); + assert!(t0.elapsed() < Duration::from_secs(2)); + } + #[test] fn refused_direct_target_fails_fast() { // A port nothing listens on: the bounded connect returns diff --git a/pkgs/fleet/smoke.sh b/pkgs/fleet/smoke.sh index ddf71612f5..4b3a08a65d 100755 --- a/pkgs/fleet/smoke.sh +++ b/pkgs/fleet/smoke.sh @@ -258,7 +258,12 @@ run "proxy: legacy proto-0 client round-trips (no hello)" 0 "legacy-ok" \ # with no LAPTOP_AGENT_POOL anywhere in its environment, so # its startup line must render the compiled default of 50. run "proxy: broker startup renders the effective pool size (default 50)" 0 \ - "pool: 50 per port" grep "pool: 50 per port" "$PX/broker.log" + "pool_size=50" grep "pool_size=50" "$PX/broker.log" +# Identity stamp (#5758): the same first startup line names the +# implementation and carries a UTC timestamp + pid, so broker +# ownership of an incident window is reconstructable from the log. +run "proxy: broker startup line is timestamped with implementation + pid" 0 \ + "implementation=fleet-proxy" grep -E "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]+Z fleet proxy serve start implementation=fleet-proxy version=[^ ]+ pool_size=50 pid=[0-9]+" "$PX/broker.log" # 32-concurrent burst against that default-config broker, # mirroring the #5412 benchmark method (hello-negotiated From ddef62e58e8f7087160148bd2caf36243aa05090 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 04:22:08 -0600 Subject: [PATCH 5/5] fleet(proxy): bound DNS resolution by the transport deadline (#5758, PR #6490 Codex round 4) --- pkgs/fleet/crates/fleet-proxy/src/tunnel.rs | 25 ++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs b/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs index 1348abe00c..c134e66351 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs @@ -49,7 +49,30 @@ fn connect_tcp( deadline: Duration, start: Instant, ) -> std::io::Result { - let addrs: Vec<_> = (host, port).to_socket_addrs()?.collect(); + // Resolution is inside the deadline too (Codex P2, PR + // #6490): `to_socket_addrs` blocks synchronously with no + // timeout, so it runs on a helper thread and the caller + // waits only for the remaining budget. A stalled resolver + // leaves that one thread parked — the tunnel attempt itself + // fails on budget like every other setup stall. + let (tx, rx) = std::sync::mpsc::channel(); + { + let host = host.to_string(); + std::thread::spawn(move || { + let got = (host.as_str(), port) + .to_socket_addrs() + .map(|it| it.collect::>()); + let _ = tx.send(got); + }); + } + let Some(left) = remaining(deadline, start) else { + return Err(deadline_exceeded("DNS resolution", deadline)); + }; + let addrs = match rx.recv_timeout(left) { + Ok(Ok(addrs)) => addrs, + Ok(Err(e)) => return Err(e), + Err(_) => return Err(deadline_exceeded("DNS resolution", deadline)), + }; if addrs.is_empty() { return Err(std::io::Error::new( std::io::ErrorKind::AddrNotAvailable,