From 89e0320592120bcee24e3d88179148cc080775f1 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 19:33:34 -0600 Subject: [PATCH 1/3] refactor(fleet-queue): broker run() returns setup failures instead of exiting Precondition for multi-role serve (design #5698 step 2, impl #6264): queue_broker::run and secrets_broker::run called std::process::exit on setup failures (home resolution, token files, Turso token/schema, bind). Every such site now returns the same exit code (2 or 3) to the caller. The standalone bins already exit with the returned code, so single-role behavior is unchanged; a supervisor hosting several roles in one process now sees a role setup failure as that role returning its code. --- .../crates/fleet-queue/src/queue_broker.rs | 78 +++++++++++-------- .../crates/fleet-queue/src/secrets_broker.rs | 49 +++++++----- 2 files changed, 74 insertions(+), 53 deletions(-) diff --git a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs index eeb05dfb74..241b9aa319 100644 --- a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs +++ b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs @@ -664,7 +664,6 @@ fn verb_with_execution(st: &State, fn_name: &str, args: Value, req: &Value) -> V } } - /// The GitHub token the dep rechecker authenticates with, /// resolved by name through the secrets broker like every other /// broker credential (#8276). @@ -770,10 +769,7 @@ impl crate::turso_queue::DepProbe for GhDepProbe { use crate::turso_queue::DepObs; match self.get_json(&format!("/repos/{repo}/pulls/{number}")) { Ok(v) => { - let merged = v - .get("merged") - .and_then(|m| m.as_bool()) - .unwrap_or(false); + let merged = v.get("merged").and_then(|m| m.as_bool()).unwrap_or(false); let state = v.get("state").and_then(|s| s.as_str()).unwrap_or(""); if merged { DepObs::Cleared("pr merged".to_string()) @@ -1192,24 +1188,32 @@ pub fn run() -> i32 { use std::io::Read as _; let bind = std::env::var("QUEUE_BROKER_BIND").unwrap_or_else(|_| "100.99.113.103:4801".to_string()); - let home = crate::home::from_env().unwrap_or_else(|error| { - eprintln!("queue-broker: {error}"); - std::process::exit(2); - }); + let home = match crate::home::from_env() { + Ok(home) => home, + Err(error) => { + eprintln!("queue-broker: {error}"); + return 2; + } + }; let token_file = std::env::var("QUEUE_BROKER_TOKEN_FILE") .unwrap_or_else(|_| format!("{home}/.config/queue-broker/token")); - let token = crate::token_file::load_token_file(&token_file).unwrap_or_else(|e| { - crate::log::info("queue-broker", &e); - std::process::exit(3); - }); + let token = match crate::token_file::load_token_file(&token_file) { + Ok(v) => v, + Err(e) => { + crate::log::info("queue-broker", &e); + return 3; + } + }; let secrets_url = default_secrets_url(std::env::var("QUEUE_BROKER_SECRETS_URL").ok()); let secrets_token_file = std::env::var("QUEUE_BROKER_SECRETS_TOKEN_FILE") .unwrap_or_else(|_| format!("{home}/.config/secrets-broker/token")); - let secrets_token = - crate::token_file::load_token_file(&secrets_token_file).unwrap_or_else(|e| { + let secrets_token = match crate::token_file::load_token_file(&secrets_token_file) { + Ok(v) => v, + Err(e) => { crate::log::info("queue-broker", &e); - std::process::exit(3); - }); + return 3; + } + }; let agent: ureq::Agent = ureq::Agent::config_builder() .http_status_as_error(false) @@ -1237,26 +1241,29 @@ pub fn run() -> i32 { let url = std::env::var("QUEUE_BROKER_TURSO_URL") .unwrap_or_else(|_| crate::turso_queue::DEFAULT_TURSO_URL.to_string()); let token = match std::env::var("QUEUE_BROKER_TURSO_TOKEN_FILE") { - Ok(f) => crate::token_file::load_token_file(&f).unwrap_or_else(|e| { - crate::log::info("queue-broker", &e); - std::process::exit(3); - }), + Ok(f) => match crate::token_file::load_token_file(&f) { + Ok(v) => v, + Err(e) => { + crate::log::info("queue-broker", &e); + return 3; + } + }, Err(_) => { let resolver = Resolver::new(vec![Box::new(DirectSecrets { url: secrets_url.clone(), token: secrets_token.clone(), agent: agent.clone(), })]); - resolver - .resolve(crate::turso_queue::TURSO_TOKEN_SECRET_NAME) - .map(|v| v.expose().to_string()) - .unwrap_or_else(|e| { + match resolver.resolve(crate::turso_queue::TURSO_TOKEN_SECRET_NAME) { + Ok(v) => v.expose().to_string(), + Err(e) => { crate::log::info( "queue-broker", &format!("turso backend token resolve failed: {e}"), ); - std::process::exit(3); - }) + return 3; + } + } } }; let mut backend = crate::turso_queue::TursoBackend::new(url, token, agent.clone()); @@ -1269,13 +1276,13 @@ pub fn run() -> i32 { agent: agent.clone(), token: Mutex::new(None), })); - backend.ensure_schema().unwrap_or_else(|e| { + if let Err(e) = backend.ensure_schema() { crate::log::info( "queue-broker", &format!("turso backend schema ensure failed: {e}"), ); - std::process::exit(3); - }); + return 3; + } crate::log::info( "queue-broker", &format!("queue backend: turso ({})", backend.url()), @@ -1296,10 +1303,13 @@ pub fn run() -> i32 { turso, }); - let server = Server::http(&bind).unwrap_or_else(|e| { - crate::log::info("queue-broker", &format!("cannot bind {bind}: {e:?}")); - std::process::exit(3); - }); + let server = match Server::http(&bind) { + Ok(server) => server, + Err(e) => { + crate::log::info("queue-broker", &format!("cannot bind {bind}: {e:?}")); + return 3; + } + }; crate::log::info("queue-broker", &format!("listening on {bind}")); // Dual-bind (#6216): the same handler over a Unix socket. A bind diff --git a/pkgs/fleet/crates/fleet-queue/src/secrets_broker.rs b/pkgs/fleet/crates/fleet-queue/src/secrets_broker.rs index 35f3f9378d..5170e6c6b9 100644 --- a/pkgs/fleet/crates/fleet-queue/src/secrets_broker.rs +++ b/pkgs/fleet/crates/fleet-queue/src/secrets_broker.rs @@ -429,16 +429,22 @@ pub fn run() -> i32 { use std::io::Read as _; let bind = std::env::var("SECRETS_BROKER_BIND").unwrap_or_else(|_| "100.99.113.103:4800".to_string()); - let home = crate::home::from_env().unwrap_or_else(|error| { - eprintln!("secrets-broker: {error}"); - std::process::exit(2); - }); + let home = match crate::home::from_env() { + Ok(home) => home, + Err(error) => { + eprintln!("secrets-broker: {error}"); + return 2; + } + }; let token_file = std::env::var("SECRETS_BROKER_TOKEN_FILE") .unwrap_or_else(|_| format!("{home}/.config/secrets-broker/token")); - let token = crate::token_file::load_token_file(&token_file).unwrap_or_else(|e| { - crate::log::info("secrets-broker", &e); - std::process::exit(3); - }); + let token = match crate::token_file::load_token_file(&token_file) { + Ok(v) => v, + Err(e) => { + crate::log::info("secrets-broker", &e); + return 3; + } + }; let ttl_s: u64 = std::env::var("SECRETS_BROKER_TTL_S") .ok() .and_then(|v| v.parse().ok()) @@ -456,19 +462,24 @@ pub fn run() -> i32 { // and a failed refresh keeps the old values). { let state = Arc::clone(&state); - std::thread::spawn(move || loop { - match refresh(&state) { - Ok(n) => crate::log::info("secrets-broker", &format!("refreshed {n} secrets")), - Err(e) => crate::log::info("secrets-broker", &format!("refresh failed: {e}")), + std::thread::spawn(move || { + loop { + match refresh(&state) { + Ok(n) => crate::log::info("secrets-broker", &format!("refreshed {n} secrets")), + Err(e) => crate::log::info("secrets-broker", &format!("refresh failed: {e}")), + } + std::thread::sleep(Duration::from_secs(ttl_s)); } - std::thread::sleep(Duration::from_secs(ttl_s)); }); } - let server = Server::http(&bind).unwrap_or_else(|e| { - crate::log::info("secrets-broker", &format!("cannot bind {bind}: {e:?}")); - std::process::exit(3); - }); + let server = match Server::http(&bind) { + Ok(server) => server, + Err(e) => { + crate::log::info("secrets-broker", &format!("cannot bind {bind}: {e:?}")); + return 3; + } + }; crate::log::info("secrets-broker", &format!("listening on {bind}")); // Dual-bind (#6216): the same handler over a Unix socket. A bind @@ -618,8 +629,8 @@ fn url_decode(s: &str) -> String { #[cfg(test)] mod tests { use super::{ - fetch_through_with, parse_list_entries, pre_body_refusal, resolve_list_id, url_decode, - State, + State, fetch_through_with, parse_list_entries, pre_body_refusal, resolve_list_id, + url_decode, }; #[test] From 69040da8c23776c6143c8df015e687dd75d98647 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 19:33:35 -0600 Subject: [PATCH 2/3] =?UTF-8?q?feat(fleet):=20multi-role=20serve=20list=20?= =?UTF-8?q?=E2=80=94=20one=20daemon,=20several=20roles=20(#6264)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements design #5698 option (i), approved by Drew 2026-11-05: fleet serve [ ...] runs two or more roles in one process, each existing blocking serve loop on its own thread under a small supervisor. All roles are capability-checked before anything binds (an unavailable role stubs the whole list at exit 69 — no partial starts); a role thread that returns or panics is fatal, exiting with the role code and naming the role, so the external supervisor restarts the unit. The list can express the complete current serve set (queue-broker, secrets-broker, search, proxy) — the equivalent-of-all criterion — pinned by serve_set_covers_every_serve_token. Single-role invocations are untouched: a role plus its own tail (search flags, --help) is not a list and keeps the existing per-role paths; bare fleet serve stays a usage error; duplicate roles and stray tokens in a list are usage errors naming the token. --- pkgs/fleet/crates/fleet/src/main.rs | 286 ++++++++++++++++++++++++++++ 1 file changed, 286 insertions(+) diff --git a/pkgs/fleet/crates/fleet/src/main.rs b/pkgs/fleet/crates/fleet/src/main.rs index 548ae77422..efc74ff43b 100644 --- a/pkgs/fleet/crates/fleet/src/main.rs +++ b/pkgs/fleet/crates/fleet/src/main.rs @@ -455,6 +455,9 @@ fn broker_argument_error(d: &Domain, args: &[String]) -> Option { if d.name != "serve" { return None; } + if parse_serve_list(args).is_some() { + return None; + } let role = args.first()?.as_str(); if !matches!(role, "queue-broker" | "secrets-broker") { return None; @@ -474,6 +477,222 @@ fn search_serve_tail<'a>(d: &Domain, args: &'a [String]) -> Option<&'a [String]> } } +/// One role of the `serve` domain, spelled as its registry token +/// (#6264, design #5698). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ServeRole { + QueueBroker, + SecretsBroker, + Search, + Proxy, +} + +impl ServeRole { + fn from_token(token: &str) -> Option { + match token { + "queue-broker" => Some(ServeRole::QueueBroker), + "secrets-broker" => Some(ServeRole::SecretsBroker), + "search" => Some(ServeRole::Search), + "proxy" => Some(ServeRole::Proxy), + _ => None, + } + } + + fn token(self) -> &'static str { + match self { + ServeRole::QueueBroker => "queue-broker", + ServeRole::SecretsBroker => "secrets-broker", + ServeRole::Search => "search", + ServeRole::Proxy => "proxy", + } + } + + fn capability(self) -> Capability { + match self { + ServeRole::QueueBroker => Capability::QueueBroker, + ServeRole::SecretsBroker => Capability::SecretsBroker, + ServeRole::Search => Capability::SearchServe, + ServeRole::Proxy => Capability::ProxyServe, + } + } +} + +/// The complete current serve set (#6264): every role the serve +/// domain can run today. The serve list can express all of them in +/// one invocation — Drew's "equivalent of all" acceptance criterion +/// on design #5698 — and `serve_set_covers_every_serve_token` in the +/// tests pins this list to the tokens `required_capability` accepts. +const SERVE_SET: [ServeRole; 4] = [ + ServeRole::QueueBroker, + ServeRole::SecretsBroker, + ServeRole::Search, + ServeRole::Proxy, +]; + +/// Parse a multi-role serve list (design #5698 option (i), impl +/// #6264): `fleet serve [ ...]` with two or more +/// distinct role tokens and nothing else. +/// +/// Returns None when the invocation is not a list — a single role, +/// or a role followed by its own tail (the search role's flags, a +/// help flag) — so those keep the existing single-role paths and +/// their per-role argument rules. Returns Some(Err) when the first +/// two tokens are roles but the rest of the list is malformed (a +/// stray token or a duplicate role): a list is validated as a +/// whole, never partially started. +fn parse_serve_list(args: &[String]) -> Option, String>> { + if args.len() < 2 { + return None; + } + ServeRole::from_token(&args[0])?; + ServeRole::from_token(&args[1])?; + let mut roles: Vec = Vec::new(); + for token in args { + match ServeRole::from_token(token) { + Some(role) => { + if roles.contains(&role) { + return Some(Err(format!( + "duplicate role '{token}' in 'fleet serve' list" + ))); + } + roles.push(role); + } + None => { + return Some(Err(format!( + "unexpected argument '{token}' in 'fleet serve' list: a serve list is role tokens only ({})", + SERVE_SET + .iter() + .map(|r| r.token()) + .collect::>() + .join(", ") + ))); + } + } + } + Some(Ok(roles)) +} + +/// Run one serve role in the calling thread. Only reached after the +/// role's capability state checked out Available, so a feature that +/// is not compiled in is unreachable here. +fn run_serve_role(role: ServeRole, config: &fleet_config::Config) -> i32 { + match role { + ServeRole::QueueBroker => { + #[cfg(feature = "queue-broker")] + { + fleet_queue::queue_broker::run() + } + #[cfg(not(feature = "queue-broker"))] + { + unreachable!("queue-broker role gated by capability before spawn") + } + } + ServeRole::SecretsBroker => { + #[cfg(feature = "secrets-broker")] + { + fleet_queue::secrets_broker::run() + } + #[cfg(not(feature = "secrets-broker"))] + { + unreachable!("secrets-broker role gated by capability before spawn") + } + } + ServeRole::Search => { + #[cfg(feature = "search-serve")] + { + fleet_search::serve::run(&[]) + } + #[cfg(not(feature = "search-serve"))] + { + unreachable!("search role gated by capability before spawn") + } + } + ServeRole::Proxy => { + #[cfg(feature = "proxy-serve")] + { + fleet_proxy::serve::run(config) + } + #[cfg(not(feature = "proxy-serve"))] + { + unreachable!("proxy role gated by capability before spawn") + } + } + } +} + +/// Run a validated multi-role serve list in this one process +/// (#6264): every role's existing blocking serve loop on its own +/// thread, supervised from here. All roles are capability-checked +/// before anything binds — a role this invocation cannot run stubs +/// the whole list (exit 69) with no partial start. A role thread +/// that returns or panics is fatal to the process (the external +/// supervisor restarts the unit, per design #5698): the exit code +/// is the role's own when it reported one, else 1, and the role is +/// named on stderr either way. +fn run_serve_list(surface: &Surface, roles: &[ServeRole], invoked_as: &str) -> i32 { + for role in roles { + let state = surface.cap_state(role.capability(), "serve"); + if state != CapState::Available { + eprintln!( + "fleet serve: role '{}' cannot run in this invocation", + role.token() + ); + return stub(surface, "serve", &state, invoked_as); + } + } + println!( + "fleet serve: starting {} roles in one process: {}", + roles.len(), + roles + .iter() + .map(|r| r.token()) + .collect::>() + .join(", ") + ); + let mut handles = Vec::new(); + for role in roles { + let role = *role; + let config = surface.config.clone(); + handles.push(( + role, + std::thread::spawn(move || run_serve_role(role, &config)), + )); + } + loop { + // The position scan's borrow ends before the finished + // handle is taken out of the vector. + let finished = handles.iter().position(|(_, h)| h.is_finished()); + if let Some(pos) = finished { + let (role, handle) = handles + .into_iter() + .nth(pos) + .expect("position was just observed"); + // The process exits with this role's outcome, which + // ends the sibling threads with it. + let code = match handle.join() { + Ok(code) => code, + Err(_) => { + eprintln!("fleet serve: role '{}' panicked", role.token()); + return 1; + } + }; + if code == EXIT_OK { + eprintln!( + "fleet serve: role '{}' exited; shutting the serve list down", + role.token() + ); + return 1; + } + eprintln!( + "fleet serve: role '{}' exited with code {code}; shutting the serve list down", + role.token() + ); + return code; + } + std::thread::sleep(std::time::Duration::from_millis(100)); + } +} + /// Run one domain invocation (also the argv0-alias landing pad). fn run_domain(surface: &Surface, d: &Domain, args: &[String], invoked_as: &str) -> i32 { // The search role takes real flags, so its own usage answers @@ -502,6 +721,18 @@ fn run_domain(surface: &Surface, d: &Domain, args: &[String], invoked_as: &str) }; match surface.cap_state(cap, d.name) { CapState::Available => { + // #6264 (design #5698 option (i)): a multi-role serve + // list runs every listed role in this one process. The + // parse returns None for single-role invocations, which + // keep the paths below unchanged. + if d.name == "serve" { + if let Some(list) = parse_serve_list(args) { + match list { + Ok(roles) => return run_serve_list(surface, &roles, invoked_as), + Err(message) => return usage_error(&message), + } + } + } // Step 2 (#5430): the queue domain runs for real — the // repo-queue client surface and the two broker roles. // `--version` through the argv0 route is the census fix: @@ -1468,6 +1699,61 @@ mod tests { ); } + #[test] + fn serve_list_parses_two_or_more_distinct_roles() { + let list = parse_serve_list(&args(&["queue-broker", "secrets-broker"])) + .expect("two role tokens are a list") + .expect("distinct roles parse"); + assert_eq!(list, vec![ServeRole::QueueBroker, ServeRole::SecretsBroker]); + let list = parse_serve_list(&args(&["search", "proxy", "queue-broker"])) + .expect("three role tokens are a list") + .expect("distinct roles parse"); + assert_eq!( + list, + vec![ServeRole::Search, ServeRole::Proxy, ServeRole::QueueBroker] + ); + } + + #[test] + fn serve_list_rejects_duplicates_and_stray_tokens() { + let dup = parse_serve_list(&args(&["queue-broker", "queue-broker"])) + .expect("role tokens are a list") + .expect_err("a duplicate role is an error"); + assert!(dup.contains("duplicate role 'queue-broker'"), "{dup}"); + let stray = parse_serve_list(&args(&["queue-broker", "secrets-broker", "--bogus"])) + .expect("leading role tokens are a list") + .expect_err("a stray token is an error"); + assert!(stray.contains("--bogus"), "{stray}"); + } + + #[test] + fn serve_list_leaves_single_role_invocations_alone() { + // One role: not a list. + assert!(parse_serve_list(&args(&["queue-broker"])).is_none()); + // A role plus its own tail (the search role's flags, a help + // flag after a broker role): not a list; the single-role + // paths keep their own argument rules for these. + assert!(parse_serve_list(&args(&["search", "--port", "1234"])).is_none()); + assert!(parse_serve_list(&args(&["queue-broker", "--help"])).is_none()); + // No role at all: not a list. + assert!(parse_serve_list(&args(&["--help"])).is_none()); + assert!(parse_serve_list(&args(&[])).is_none()); + } + + #[test] + fn serve_set_covers_every_serve_token() { + // Drew's "equivalent of all" criterion (#5698, carried by + // #6264): the serve list can express the complete current + // serve set — exactly the role tokens required_capability + // accepts for the serve domain. + for token in ["queue-broker", "secrets-broker", "search", "proxy"] { + let role = ServeRole::from_token(token).expect("serve token has a role"); + assert!(SERVE_SET.contains(&role), "{token} missing from SERVE_SET"); + assert_eq!(role.token(), token); + } + assert_eq!(SERVE_SET.len(), 4); + } + #[test] fn queue_domain_version_rejects_trailing_arguments() { // #5603: the queue domain's --version shortcut in run_domain From ebb9019d40b1709f6c9f3652e1d7714fd97ddf8c Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 21:21:30 -0600 Subject: [PATCH 3/3] =?UTF-8?q?fix(fleet):=20Codex=20round=20on=20#8394=20?= =?UTF-8?q?=E2=80=94=20co-hosted=20proxy=20never=20idle-exits;=20bounded?= =?UTF-8?q?=20startup=20retry=20for=20the=20Turso=20token?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P1: serve list runs the proxy via fleet_proxy::serve::run_cohosted (idle-exit disabled); standalone run() keeps the auto-spawned lifetime. P2: queue_broker resolves the Turso token via resolve_with_startup_retry (250ms backoff, 30s budget) so a cold co-hosted secrets-broker no longer races it into exit 3; two unit tests pin the retry contract. --- pkgs/fleet/crates/fleet-proxy/src/serve.rs | 27 +++++- .../crates/fleet-queue/src/queue_broker.rs | 88 ++++++++++++++++++- pkgs/fleet/crates/fleet/src/main.rs | 5 +- 3 files changed, 113 insertions(+), 7 deletions(-) diff --git a/pkgs/fleet/crates/fleet-proxy/src/serve.rs b/pkgs/fleet/crates/fleet-proxy/src/serve.rs index f430847f1f..2bdb990ef5 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/serve.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/serve.rs @@ -818,7 +818,7 @@ fn serve_session(broker: &Broker, mut stream: UnixStream) { } } -fn keepalive_loop(broker: Arc) { +fn keepalive_loop(broker: Arc, idle_exit: bool) { let idle = broker.config.idle_exit_secs(); let health_req = Request { method: "GET".to_string(), @@ -831,10 +831,15 @@ fn keepalive_loop(broker: Arc) { loop { std::thread::sleep(Duration::from_secs(IDLE_TICK_S)); let now = now_secs(); - if now.saturating_sub(broker.last_used.load(Ordering::Relaxed)) > idle { + if idle_exit + && now.saturating_sub(broker.last_used.load(Ordering::Relaxed)) > idle + { // The Python exits via os._exit from its keepalive // loop; the same abruptness is fine — the broker holds - // nothing that needs draining. + // nothing that needs draining. Standalone brokers only: + // a co-hosted proxy (run_cohosted) must never exit the + // shared process out from under its sibling roles + // (#8394 Codex P1). std::process::exit(0); } if now.saturating_sub(last_health) >= KEEPALIVE_S { @@ -844,12 +849,26 @@ fn keepalive_loop(broker: Arc) { } } +/// Run the broker co-hosted with other serve roles in one process +/// (`fleet serve [ ...]`, #6264): same broker, but the +/// idle-exit is disabled — the proxy's standalone lifetime contract +/// (auto-spawned, exits when idle) must not terminate the sibling +/// roles sharing the process (design #5698 point 5, #8394 Codex P1). +/// The serve-list supervisor owns this process's lifetime instead. +pub fn run_cohosted(config: &Config) -> i32 { + run_inner(config, false) +} + /// Run the broker in the foreground. Returns the process exit code. /// /// Startup mirrors the Python exactly: if the socket file exists /// and a connect succeeds, a live broker owns it — exit 0 quietly. /// If the connect fails, the file is stale — unlink and bind. pub fn run(config: &Config) -> i32 { + run_inner(config, true) +} + +fn run_inner(config: &Config, idle_exit: bool) -> i32 { let socket_path = config.broker_socket(); if let Some(parent) = socket_path.parent() { let _ = std::fs::create_dir_all(parent); @@ -922,7 +941,7 @@ pub fn run(config: &Config) -> i32 { } { let broker = Arc::clone(&broker); - std::thread::spawn(move || keepalive_loop(broker)); + std::thread::spawn(move || keepalive_loop(broker, idle_exit)); } // CONNECT-UDP (RFC 9298) spike (#6109): only when the // config opts in — the flag defaults off and nothing in diff --git a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs index 241b9aa319..fb84ffe7c2 100644 --- a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs +++ b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs @@ -1254,12 +1254,18 @@ pub fn run() -> i32 { token: secrets_token.clone(), agent: agent.clone(), })]); - match resolver.resolve(crate::turso_queue::TURSO_TOKEN_SECRET_NAME) { + match resolve_with_startup_retry( + &resolver, + crate::turso_queue::TURSO_TOKEN_SECRET_NAME, + Duration::from_secs(30), + ) { Ok(v) => v.expose().to_string(), Err(e) => { crate::log::info( "queue-broker", - &format!("turso backend token resolve failed: {e}"), + &format!( + "turso backend token resolve failed after 30s of retries: {e}" + ), ); return 3; } @@ -1658,3 +1664,81 @@ mod tests { ); } } + +/// Resolve `name` through `resolver`, retrying until `budget` +/// elapses. Startup only: a co-hosted or freshly started +/// secrets-broker binds before its first vault refresh completes +/// and answers 503 while its cache is cold, so a one-shot resolve +/// races its readiness and the whole serve list exits (#8394 +/// Codex P2). Bounded: once the budget is spent the last error is +/// returned and the caller fails exactly as the one-shot did. +fn resolve_with_startup_retry( + resolver: &Resolver, + name: &str, + budget: Duration, +) -> Result { + let deadline = std::time::Instant::now() + budget; + loop { + match resolver.resolve(name) { + Ok(v) => return Ok(v), + Err(e) => { + if std::time::Instant::now() >= deadline { + return Err(e); + } + std::thread::sleep(Duration::from_millis(250)); + } + } + } +} + +#[cfg(test)] +mod startup_retry_tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// A source that answers Unavailable for the first `fail_first` + /// calls, then resolves — the cold secrets-broker shape. + struct FlakySource { + calls: AtomicUsize, + fail_first: usize, + } + + impl SecretSource for FlakySource { + fn source_name(&self) -> &'static str { + "flaky-test" + } + fn resolve(&self, name: &str) -> Result { + if self.calls.fetch_add(1, Ordering::SeqCst) < self.fail_first { + return Err(SecretError::Unavailable { + source: "flaky-test", + name: name.to_string(), + detail: "cold cache".to_string(), + }); + } + Ok(SecretValue::from_resolved("tok".to_string())) + } + } + + #[test] + fn startup_retry_outlasts_a_cold_source() { + let resolver = Resolver::new(vec![Box::new(FlakySource { + calls: AtomicUsize::new(0), + fail_first: 3, + })]); + let v = resolve_with_startup_retry(&resolver, "some.token", Duration::from_secs(5)) + .expect("retry should reach the warmed source"); + assert_eq!(v.expose(), "tok"); + } + + #[test] + fn startup_retry_gives_up_within_budget() { + let resolver = Resolver::new(vec![Box::new(FlakySource { + calls: AtomicUsize::new(0), + fail_first: usize::MAX, + })]); + let start = std::time::Instant::now(); + let r = resolve_with_startup_retry(&resolver, "some.token", Duration::from_millis(300)); + assert!(r.is_err()); + assert!(start.elapsed() < Duration::from_secs(5)); + } +} diff --git a/pkgs/fleet/crates/fleet/src/main.rs b/pkgs/fleet/crates/fleet/src/main.rs index efc74ff43b..d0c8814978 100644 --- a/pkgs/fleet/crates/fleet/src/main.rs +++ b/pkgs/fleet/crates/fleet/src/main.rs @@ -610,7 +610,10 @@ fn run_serve_role(role: ServeRole, config: &fleet_config::Config) -> i32 { ServeRole::Proxy => { #[cfg(feature = "proxy-serve")] { - fleet_proxy::serve::run(config) + // Co-hosted: the proxy's idle-exit is disabled so an + // idle proxy cannot exit the shared process (#8394 + // Codex P1); the supervisor above owns the lifetime. + fleet_proxy::serve::run_cohosted(config) } #[cfg(not(feature = "proxy-serve"))] {