diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 51c2396b..c19ff461 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -68,6 +68,8 @@ jobs: run: python3 scripts/smoke-static-cli.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next - name: Static CLI HTTP cancellation failure isolation run: python3 scripts/smoke-worker-cancel.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Static CLI HTTP crash recovery without request replay + run: python3 scripts/smoke-worker-cancel.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next --restart - uses: actions/upload-artifact@v4 with: name: strata-next-linux-x86_64-musl diff --git a/control-plane/src/config.rs b/control-plane/src/config.rs index 7a68ad7a..d46b7cb8 100644 --- a/control-plane/src/config.rs +++ b/control-plane/src/config.rs @@ -24,6 +24,7 @@ struct FileEngine { #[serde(default)] args: Vec, startup_timeout_s: Option, + max_restarts: Option, tokenizer_dir: Option, } @@ -66,11 +67,20 @@ impl Config { if !(1..=3600).contains(&startup_timeout_s) { return Err("startup_timeout_s must be between 1 and 3600".into()); } + let max_restarts = optional_env("STRATA_MAX_WORKER_RESTARTS")? + .map(|value| value.parse::()) + .transpose()? + .or_else(|| file.engine.as_ref().and_then(|engine| engine.max_restarts)) + .unwrap_or(3); + if max_restarts > 3 { + return Err("max_restarts must be between 0 and 3".into()); + } let worker = match executable { Some(executable) if !executable.is_empty() => Some(WorkerConfig { executable, args, startup_timeout: Duration::from_secs(startup_timeout_s), + max_restarts, }), Some(_) => return Err("engine executable cannot be empty".into()), None if !args.is_empty() => return Err("engine args require an executable".into()), diff --git a/control-plane/src/worker.rs b/control-plane/src/worker.rs index de991331..864dc594 100644 --- a/control-plane/src/worker.rs +++ b/control-plane/src/worker.rs @@ -49,6 +49,7 @@ impl GenerationResult { pub enum WorkerState { Unconfigured, Starting, + Restarting, Ready, Stopping, Failed, @@ -73,6 +74,7 @@ pub struct WorkerConfig { pub executable: OsString, pub args: Vec, pub startup_timeout: Duration, + pub max_restarts: u32, } pub async fn run( @@ -91,7 +93,72 @@ pub async fn run_with_requests( mut shutdown: watch::Receiver, mut requests: mpsc::Receiver, ) { - update(&status, WorkerState::Starting, None).await; + if config.max_restarts > 3 { + eprintln!("worker max_restarts must be between 0 and 3"); + update(&status, WorkerState::Failed, None).await; + return; + } + for attempt in 0..=config.max_restarts { + match run_session(&config, &status, &mut shutdown, &mut requests).await { + SessionExit::Stopped | SessionExit::StartupFailed => return, + SessionExit::RuntimeFailed if attempt == config.max_restarts => return, + SessionExit::RuntimeFailed => {} + } + update(&status, WorkerState::Restarting, None).await; + let delay = Duration::from_secs(2 << attempt); + eprintln!( + "Strata engine restart {}/{} in {} seconds", + attempt + 1, + config.max_restarts, + delay.as_secs() + ); + while let Ok(command) = requests.try_recv() { + send_failure( + command.result, + "worker failed; request was not replayed".to_owned(), + ) + .await; + } + let backoff = tokio::time::sleep(delay); + tokio::pin!(backoff); + let mut requests_closed = requests.is_closed() && requests.is_empty(); + loop { + tokio::select! { + biased; + _ = shutdown.changed() => { + update(&status, WorkerState::Stopping, None).await; + return; + } + _ = &mut backoff => break, + command = requests.recv(), if !requests_closed => { + match command { + Some(command) => send_failure(command.result, + "worker is restarting; request was not replayed".to_owned()).await, + None => requests_closed = true, + } + } + } + } + } +} + +enum SessionExit { + Stopped, + StartupFailed, + RuntimeFailed, +} + +async fn run_session( + config: &WorkerConfig, + status: &RwLock, + shutdown: &mut watch::Receiver, + requests: &mut mpsc::Receiver, +) -> SessionExit { + if *shutdown.borrow() { + update(status, WorkerState::Stopping, None).await; + return SessionExit::Stopped; + } + update(status, WorkerState::Starting, None).await; let mut child = match Command::new(&config.executable) .arg("--serve") .args(&config.args) @@ -104,8 +171,8 @@ pub async fn run_with_requests( Ok(child) => child, Err(error) => { eprintln!("failed to start Strata engine: {error}"); - update(&status, WorkerState::Failed, None).await; - return; + update(status, WorkerState::Failed, None).await; + return SessionExit::StartupFailed; } }; @@ -115,59 +182,69 @@ pub async fn run_with_requests( let mut lines = BufReader::new(stdout).lines(); let startup_deadline = tokio::time::sleep(config.startup_timeout); tokio::pin!(startup_deadline); + let mut requests_closed = false; let max_context = loop { let line = tokio::select! { + biased; _ = shutdown.changed() => { - update(&status, WorkerState::Stopping, None).await; + update(status, WorkerState::Stopping, None).await; stop(&mut child, &mut stdin).await; - return; + return SessionExit::Stopped; } _ = &mut startup_deadline => { eprintln!("Strata engine did not become ready before the startup timeout"); stop(&mut child, &mut stdin).await; - update(&status, WorkerState::Failed, None).await; - return; + update(status, WorkerState::Failed, None).await; + return SessionExit::StartupFailed; + } + command = requests.recv(), if !requests_closed => { + match command { + Some(command) => send_failure(command.result, + "worker is starting; request was not replayed".to_owned()).await, + None => requests_closed = true, + } + continue; } line = lines.next_line() => line, }; match line { Ok(Some(line)) if line.starts_with("READY") => { if let Some(max_context) = parse_ready(&line) { - update(&status, WorkerState::Ready, Some(max_context)).await; + update(status, WorkerState::Ready, Some(max_context)).await; break max_context; } eprintln!("Strata engine sent an invalid READY line"); stop(&mut child, &mut stdin).await; - update(&status, WorkerState::Failed, None).await; - return; + update(status, WorkerState::Failed, None).await; + return SessionExit::StartupFailed; } Ok(Some(_)) => {} Ok(None) => { eprintln!("Strata engine exited before READY"); - update(&status, WorkerState::Failed, None).await; - return; + terminate(&mut child, &mut stdin).await; + update(status, WorkerState::Failed, None).await; + return SessionExit::StartupFailed; } Err(error) => { eprintln!("failed to read Strata engine output: {error}"); stop(&mut child, &mut stdin).await; - update(&status, WorkerState::Failed, None).await; - return; + update(status, WorkerState::Failed, None).await; + return SessionExit::StartupFailed; } } }; - let mut requests_closed = false; loop { tokio::select! { _ = shutdown.changed() => { - update(&status, WorkerState::Stopping, None).await; + update(status, WorkerState::Stopping, None).await; stop(&mut child, &mut stdin).await; - return; + return SessionExit::Stopped; }, result = child.wait() => { eprintln!("Strata engine exited: {result:?}"); - update(&status, WorkerState::Failed, None).await; - return; + update(status, WorkerState::Failed, None).await; + return SessionExit::RuntimeFailed; }, command = requests.recv(), if !requests_closed => { match command { @@ -176,15 +253,15 @@ pub async fn run_with_requests( result = generate(&mut stdin, &mut lines, command, max_context) => { if let Err(error) = result { eprintln!("Strata engine protocol failed: {error}"); - update(&status, WorkerState::Failed, None).await; + update(status, WorkerState::Failed, None).await; terminate(&mut child, &mut stdin).await; - return; + return SessionExit::RuntimeFailed; } } _ = shutdown.changed() => { - update(&status, WorkerState::Stopping, None).await; + update(status, WorkerState::Stopping, None).await; stop_active(&mut child, &mut stdin).await; - return; + return SessionExit::Stopped; } } } @@ -344,6 +421,7 @@ mod tests { executable: script, args: vec![mode.to_owned()], startup_timeout: Duration::from_secs(timeout_s), + max_restarts: 0, } } @@ -716,4 +794,196 @@ mod tests { drop(stop_tx); std::fs::remove_file(marker).unwrap(); } + + fn restart_fixture( + mode: &str, + label: &str, + max_restarts: u32, + ) -> (WorkerConfig, std::path::PathBuf) { + let root = + std::env::temp_dir().join(format!("strata-restart-{label}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir(&root).unwrap(); + let mut config = fixture_config(mode, 5); + config.max_restarts = max_restarts; + config.args.push(root.display().to_string()); + (config, root) + } + + fn command( + token_ids: Vec, + max_new: u32, + ) -> ( + GenerationCommand, + oneshot::Receiver, String>>, + ) { + let (sender, receiver) = oneshot::channel(); + ( + GenerationCommand { + request: Generate { + token_ids, + max_new, + temperature: None, + top_p: None, + }, + result: GenerationResult::Buffered(sender), + }, + receiver, + ) + } + + #[tokio::test] + async fn crash_restarts_worker_without_replaying_active_or_queued_requests() { + let (config, root) = restart_fixture("restart-once", "once", 1); + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (stop_tx, stop_rx) = watch::channel(false); + let (commands_tx, commands_rx) = mpsc::channel(1); + let task = tokio::spawn(run_with_requests( + config, + status.clone(), + stop_rx, + commands_rx, + )); + wait_for(&status, WorkerState::Ready).await; + let (first, failed) = command(vec![10, 20], 3); + commands_tx.send(first).await.unwrap(); + timeout(Duration::from_secs(5), async { + while !root.join("active").exists() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + let (queued, rejected) = command(vec![99], 1); + commands_tx.send(queued).await.unwrap(); + std::fs::write(root.join("release"), "").unwrap(); + assert!( + timeout(Duration::from_secs(5), failed) + .await + .unwrap() + .is_err() + ); + assert!( + timeout(Duration::from_secs(5), rejected) + .await + .unwrap() + .unwrap() + .unwrap_err() + .contains("not replayed") + ); + wait_for(&status, WorkerState::Restarting).await; + let (during_backoff, rejected) = command(vec![99], 1); + commands_tx.send(during_backoff).await.unwrap(); + assert!( + timeout(Duration::from_secs(1), rejected) + .await + .unwrap() + .unwrap() + .unwrap_err() + .contains("restarting") + ); + wait_for(&status, WorkerState::Starting).await; + assert_eq!(status.read().await.max_context, None); + let (during_startup, rejected) = command(vec![99], 1); + commands_tx.send(during_startup).await.unwrap(); + assert!( + timeout(Duration::from_secs(1), rejected) + .await + .unwrap() + .unwrap() + .unwrap_err() + .contains("starting") + ); + wait_for(&status, WorkerState::Ready).await; + let (fresh, result) = command(vec![99], 1); + commands_tx.send(fresh).await.unwrap(); + let events = timeout(Duration::from_secs(5), result) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(events[0], Event::Token(42)); + assert_eq!( + std::fs::read_to_string(root.join("boots")) + .unwrap() + .lines() + .count(), + 2 + ); + assert_eq!( + std::fs::read_to_string(root.join("requests")).unwrap(), + "GEN 3 10,20\nGEN 1 99\n" + ); + stop_tx.send(true).unwrap(); + timeout(Duration::from_secs(5), task) + .await + .unwrap() + .unwrap(); + std::fs::remove_dir_all(root).unwrap(); + } + + #[tokio::test] + async fn repeated_crashes_exhaust_lifetime_restart_budget() { + let (config, root) = restart_fixture("restart-loop", "loop", 2); + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (_stop_tx, stop_rx) = watch::channel(false); + timeout( + Duration::from_secs(10), + run(config, status.clone(), stop_rx), + ) + .await + .unwrap(); + assert_eq!(status.read().await.state, WorkerState::Failed); + assert_eq!(status.read().await.max_context, None); + assert_eq!( + std::fs::read_to_string(root.join("boots")) + .unwrap() + .lines() + .count(), + 3 + ); + std::fs::remove_dir_all(root).unwrap(); + } + + #[tokio::test] + async fn shutdown_during_backoff_prevents_respawn() { + let (config, root) = restart_fixture("restart-loop", "shutdown", 3); + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (stop_tx, stop_rx) = watch::channel(false); + let task = tokio::spawn(run(config, status.clone(), stop_rx)); + wait_for(&status, WorkerState::Restarting).await; + stop_tx.send(true).unwrap(); + timeout(Duration::from_secs(1), task) + .await + .unwrap() + .unwrap(); + assert_eq!(status.read().await.state, WorkerState::Stopping); + assert_eq!( + std::fs::read_to_string(root.join("boots")) + .unwrap() + .lines() + .count(), + 1 + ); + std::fs::remove_dir_all(root).unwrap(); + } + + #[tokio::test] + async fn startup_failure_is_not_restarted() { + let (config, root) = restart_fixture("restart-bad", "startup", 3); + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (_stop_tx, stop_rx) = watch::channel(false); + timeout(Duration::from_secs(5), run(config, status.clone(), stop_rx)) + .await + .unwrap(); + assert_eq!(status.read().await.state, WorkerState::Failed); + assert_eq!( + std::fs::read_to_string(root.join("boots")) + .unwrap() + .lines() + .count(), + 1 + ); + std::fs::remove_dir_all(root).unwrap(); + } } diff --git a/control-plane/tests/fixtures/mock_engine.sh b/control-plane/tests/fixtures/mock_engine.sh index 2709dc91..f6dc06dd 100755 --- a/control-plane/tests/fixtures/mock_engine.sh +++ b/control-plane/tests/fixtures/mock_engine.sh @@ -67,5 +67,38 @@ case "$2" in esac done ;; + restart-once) + printf 'boot\n' >> "$3/boots" + if [ ! -e "$3/crashed" ]; then + printf 'READY 262144 stop\n' + IFS= read -r line || exit 3 + printf '%s\n' "$line" >> "$3/requests" + printf 'T 31\n' + : > "$3/active" + while [ ! -e "$3/release" ]; do sleep 0.01; done + : > "$3/crashed" + exit 7 + fi + sleep 1 + printf 'READY 262144 stop\n' + while IFS= read -r line; do + case "$line" in + 'GEN 1 99') + printf '%s\n' "$line" >> "$3/requests" + printf 'T 42\nDONE 1 1 1.0 2.0 stop\n' ;; + QUIT) exit 0 ;; + *) printf 'ERR unexpected request\n' ;; + esac + done + ;; + restart-loop) + printf 'boot\n' >> "$3/boots" + printf 'READY 262144 stop\n' + exit 7 + ;; + restart-bad) + printf 'boot\n' >> "$3/boots" + printf 'READY invalid\n' + ;; *) exit 2 ;; esac diff --git a/deploy/README.md b/deploy/README.md index d2a3aa47..1f5bb45d 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -3,3 +3,13 @@ Linux CI builds a statically linked musl CLI/control-plane preview and publishes it as a prerelease artifact on version tags. This is not yet a complete GPU runtime: the C++/CUDA engine is not linked into that executable. The host must have a compatible NVIDIA driver already installed (CUDA 13.0 GA baseline: 580.65.06 or newer). The `strata-next doctor` command checks the installed version. Model weights belong on an external volume. A complete GPU deployment image has not been built yet. For a local static CLI image smoke test, build `deploy/Dockerfile.static-cli` with a Linux/musl target. The final image is `scratch` plus the CLI binary. It is a packaging test, not the deployment image for inference. + +## Worker recovery + +The Rust supervisor defaults to three lifetime restarts after a post-READY +worker failure, with 2/4/8-second backoff. Configure `engine.max_restarts` or +`STRATA_MAX_WORKER_RESTARTS` from 0 to 3; zero disables recovery. Failed and +queued generations are not replayed. Readiness stays false until the new +worker handshake completes. A startup failure or an exhausted budget leaves +the service unhealthy for inference until an operator restarts it; `/health` +remains available. See [the API contract](../docs/api-contract.md). diff --git a/docs/api-contract.md b/docs/api-contract.md index 91618dee..0b7564a6 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -17,8 +17,7 @@ for at most 20 seconds. Tokens or progress emitted after `STOP` are discarded and do not extend the deadline. A terminal line before the deadline permits the next queued request. If the worker does not terminate in time, readiness is revoked, the process is killed and reaped, and queued receivers are closed. -The supervisor never reuses an unaligned output stream. Automatic worker -restart is not implemented; recovery requires restarting the runtime. +The supervisor never reuses an unaligned output stream. Both text and function-call SSE relays observe the HTTP consumer closing even while the engine produces no events. They then drop their generation receiver @@ -26,3 +25,19 @@ so cancellation reaches the supervisor immediately. A sanitized shell worker that consumes `STOP` without reporting `DONE` covers this failure path. This regression does not qualify full-model soak stability. + +## Worker recovery policy + +After a failure of a worker that previously sent `READY`, the supervisor can +start a fresh process. The default lifetime budget is three restarts, with +delays of 2, 4 and 8 seconds. Set `engine.max_restarts` in the JSON config or +`STRATA_MAX_WORKER_RESTARTS` to an integer from 0 through 3; zero disables +recovery. Environment overrides the file. Successful requests do not replenish +the lifetime budget. Initial or replacement startup failure stops recovery. + +An active failed generation is not retried. Queued commands are failed during +recovery; requests arriving while restarting or starting are rejected. The +worker reports `restarting` during backoff, then `starting`, with no context or +readiness until a new positive `READY` handshake. Shutdown interrupts backoff. +After the lifetime budget is exhausted, the runtime must be restarted by its +operator. This policy does not qualify real-model reload/soak stability. diff --git a/docs/build-validation.md b/docs/build-validation.md index 41f23ddd..1e89e1f1 100644 --- a/docs/build-validation.md +++ b/docs/build-validation.md @@ -277,3 +277,32 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru Actions has not run because the project still has no GitHub repository. Automatic restart, real-model replay and soak stability remain open; no production profile switch or throughput improvement is claimed. + + +## 2026-10-04 — bounded native worker recovery + +- Added an outer supervisor recovery loop after a post-READY crash or protocol + failure. Default lifetime budget: three restarts, with 2/4/8-second backoff; + `engine.max_restarts` / `STRATA_MAX_WORKER_RESTARTS` accepts 0 through 3. + Zero disables recovery. Startup failures stop the loop. Successful requests + do not replenish its budget. No failed generation is automatically replayed. +- Active and queued requests fail; commands received during backoff or startup + are rejected. Readiness has no context in `restarting`/`starting` and returns + only after a fresh positive handshake. Shutdown interrupts backoff. +- All **102 Rust tests**, format, Clippy with warnings denied, Python syntax and + diff checks passed. New failure fixtures cover crash-once recovery, active + and queued request isolation, rejected commands during backoff/startup, + perpetual crash budget exhaustion, startup failure and shutdown preventing + respawn. Existing cooperative cancellation and output fixtures remain green. +- The actual static Linux x86_64 CLI passed both HTTP smoke modes. Recovery + took **2.013 seconds** with a one-restart budget. The failed request and a + request during recovery got 503; a fresh post-READY request got 200 with + expected text `A`. Exactly two process starts and two generations were + observed: the failed generation was not replayed. With recovery disabled, + STOP failure isolation again passed at **20.002 seconds**, with queued 503, + Failed readiness, reaped worker and health 200. +- Static ELF: **16,984,160 bytes**, no INTERP/NEEDED; SHA-256: + `eb90708ccce588e16bfab4af2a1346de1c9033a7bd57664c457c746907dfcf76`. + Both HTTP checks use sanitized fixtures; no real model/GPU load or soak is + claimed. CI definitions now include recovery; hosted Actions has not run. + Production console profiles have not been switched. diff --git a/scripts/smoke-worker-cancel.py b/scripts/smoke-worker-cancel.py index 90ac332a..a9bcef7b 100644 --- a/scripts/smoke-worker-cancel.py +++ b/scripts/smoke-worker-cancel.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Exercise STOP failure isolation through real HTTP, without model weights.""" +"""Exercise STOP isolation and optional crash recovery through real HTTP.""" import http.client import json @@ -38,6 +38,7 @@ def tokenizer(root): def main(): binary = pathlib.Path(sys.argv[1]).resolve() + recovery = len(sys.argv) == 3 and sys.argv[2] == "--restart" with tempfile.TemporaryDirectory(prefix="strata-cancel-http-") as directory: root = pathlib.Path(directory) tokenizer(root) @@ -56,6 +57,25 @@ printf 'T 66\n' while IFS= read -r line; do case "$line" in QUIT) exit 0 ;; esac done +""") + if recovery: + engine.write_text("""#!/bin/sh +printf '%s' "$$" > "$2" +printf 'boot\n' >> "$3.boots" +printf 'READY 262144 stop\n' +while IFS= read -r line; do + case "$line" in + 'GEN '*) + printf '%s\n' "$line" >> "$3.requests" + if [ ! -e "$3.crashed" ]; then + : > "$3.crashed" + printf 'T 65\n' + exit 7 + fi + printf 'T 65\nDONE 1 1 1.0 2.0 stop\n' ;; + QUIT) exit 0 ;; + esac +done """) engine.chmod(0o700) with socket.socket() as probe: @@ -66,6 +86,7 @@ done "STRATA_ENGINE_EXE": str(engine), "STRATA_ENGINE_ARGS_JSON": json.dumps([str(pid_path), str(stopped)]), "STRATA_TOKENIZER_DIR": str(root), "STRATA_STARTUP_TIMEOUT_S": "5", + "STRATA_MAX_WORKER_RESTARTS": "1" if recovery else "0", } def request(method, path, body=None, timeout=30): @@ -92,6 +113,46 @@ done time.sleep(0.02) payload = {"model": "fixture", "input": "hello", "max_output_tokens": 3, "reasoning": {"effort": "none"}, "stream": True} + if recovery: + payload["stream"] = False + began = time.monotonic() + conn, response = request("POST", "/v1/responses", json.dumps(payload)) + assert response.status == 503, (response.status, response.read()) + assert json.loads(response.read())["error"]["code"] == "worker_not_ready" + conn.close() + conn, response = request("GET", "/ready") + state = json.loads(response.read()) + assert response.status == 503 and state["worker"] == "restarting" + assert state["max_context"] is None + conn.close() + conn, response = request("POST", "/v1/responses", json.dumps(payload)) + assert response.status == 503 + response.read() + conn.close() + while True: + conn, response = request("GET", "/ready") + ready = response.status == 200 + response.read() + conn.close() + if ready: + break + assert time.monotonic() - began < 8, "worker did not recover" + time.sleep(0.02) + elapsed = time.monotonic() - began + conn, response = request("POST", "/v1/responses", json.dumps(payload)) + assert response.status == 200 + answer = json.loads(response.read()) + assert answer["output"][0]["content"][0]["text"] == "A" + assert answer["status"] == "completed" + conn.close() + assert pathlib.Path(str(stopped) + ".boots").read_text().splitlines() == ["boot", "boot"] + assert len(pathlib.Path(str(stopped) + ".requests").read_text().splitlines()) == 2 + print(json.dumps({"restart_seconds": round(elapsed, 3), + "failed_request": 503, "during_recovery": 503, + "fresh_request": 200, "fresh_text": "A", + "process_starts": 2, "generations": 2, + "failed_generation_replayed": False})) + return conn, response = request("POST", "/v1/responses", json.dumps(payload)) assert response.status == 200 while b"response.output_text.delta" not in response.readline():