From e2af9d89164ca8b11b079873f706ea89f5b394a3 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 09:40:03 +0200 Subject: [PATCH] feat: start managed services with exact process readiness (#34) * feat: verify managed service readiness against its native process * test: use valid private key length in managed readiness fixture * test: declare nonreasoning output in managed readiness fixture --- control-plane/src/app.rs | 2 + control-plane/src/main.rs | 2 +- control-plane/src/service_install.rs | 132 ++++++++++++++++++++++++--- control-plane/src/wait_ready.rs | 122 ++++++++++++++++++++----- deploy/README.md | 31 ++++++- scripts/smoke-service-unit.py | 102 ++++++++++++++++++++- 6 files changed, 352 insertions(+), 39 deletions(-) diff --git a/control-plane/src/app.rs b/control-plane/src/app.rs index 7758c76d..cf6a4faf 100644 --- a/control-plane/src/app.rs +++ b/control-plane/src/app.rs @@ -49,6 +49,7 @@ struct HealthResponse { #[derive(Serialize)] struct StatusResponse { service: &'static str, + server_pid: u32, model: Option, version: &'static str, worker: WorkerState, @@ -207,6 +208,7 @@ fn status_body( ) -> StatusResponse { StatusResponse { service: "strata-control", + server_pid: std::process::id(), model, version: env!("CARGO_PKG_VERSION"), worker: worker.state, diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index 275b8c1c..a7fd2c6d 100644 --- a/control-plane/src/main.rs +++ b/control-plane/src/main.rs @@ -754,7 +754,7 @@ async fn main() -> Result<(), Box> { print!("{}", include_str!("../third_party/ggml/LICENSE")); Ok(()) } - _ => Err("usage: strata-next [api-key init --file ABSOLUTE_PATH|serve [--config FILE]|provision --config FILE|check-config [--config FILE]|wait-ready --url LOOPBACK_ORIGIN --model ID [--key-file FILE] [--timeout-s N]|service-control status|start|stop|restart|enable|disable --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service]|service-unit --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE]|service-install --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--enable] [--start]|doctor|engine-info|engine-help|--ggml-license|model prepare-native-pack MANIFEST --source-dir DIR --output DIR|model smoke-fixture --output FILE.kar|model fetch MANIFEST --output DIR|model verify MANIFEST --output DIR|model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model export-tensor-f32 FILE.gguf TENSOR --output FILE.f32|model inspect FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model derive-mixed-identity FILE.gguf|model derive-sharded-identity MANIFEST --source-dir DIR|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N|model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model inspect-kar FILE.kar|model plan-kar-memory FILE.kar --level N --budget-mib M|model plan-kar-overlay-memory --base BASE.kar --overlay OVERLAY.kar --base-level N --overlay-level N --budget-mib M|model resolve-kar-overlay --base FILE.kar --overlay FILE.kar|model checksum-kar-preview FILE.kar TENSOR LEVEL|model checksum-kar-row FILE.kar TENSOR LEVEL --row ROW_ID|model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]|model verify-iq3-preview FILE.kar --source FILE.gguf|model verify-mixed-preview FILE.kar --source FILE.gguf|model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N --ple-part-elements E|model extract-tokenizer FILE.gguf --output DIR|model tokenize TOKENIZER_DIR TEXT [--special]|model tokenize TOKENIZER_DIR --stdin [--special]|model detokenize TOKENIZER_DIR IDS]".into()), + _ => Err("usage: strata-next [api-key init --file ABSOLUTE_PATH|serve [--config FILE]|provision --config FILE|check-config [--config FILE]|wait-ready --url LOOPBACK_ORIGIN --model ID [--key-file FILE] [--timeout-s N]|service-control status|start|stop|restart|enable|disable|start-ready|restart-ready --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--ready-url LOOPBACK_ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|service-unit --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE]|service-install --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--enable] [--start]|doctor|engine-info|engine-help|--ggml-license|model prepare-native-pack MANIFEST --source-dir DIR --output DIR|model smoke-fixture --output FILE.kar|model fetch MANIFEST --output DIR|model verify MANIFEST --output DIR|model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model export-tensor-f32 FILE.gguf TENSOR --output FILE.f32|model inspect FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model derive-mixed-identity FILE.gguf|model derive-sharded-identity MANIFEST --source-dir DIR|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N|model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model inspect-kar FILE.kar|model plan-kar-memory FILE.kar --level N --budget-mib M|model plan-kar-overlay-memory --base BASE.kar --overlay OVERLAY.kar --base-level N --overlay-level N --budget-mib M|model resolve-kar-overlay --base FILE.kar --overlay FILE.kar|model checksum-kar-preview FILE.kar TENSOR LEVEL|model checksum-kar-row FILE.kar TENSOR LEVEL --row ROW_ID|model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]|model verify-iq3-preview FILE.kar --source FILE.gguf|model verify-mixed-preview FILE.kar --source FILE.gguf|model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N --ple-part-elements E|model extract-tokenizer FILE.gguf --output DIR|model tokenize TOKENIZER_DIR TEXT [--special]|model tokenize TOKENIZER_DIR --stdin [--special]|model detokenize TOKENIZER_DIR IDS]".into()), } } diff --git a/control-plane/src/service_install.rs b/control-plane/src/service_install.rs index a00532fe..8130b64b 100644 --- a/control-plane/src/service_install.rs +++ b/control-plane/src/service_install.rs @@ -70,21 +70,55 @@ fn validate_name(name: &str) -> Result<(), String> { } } -const CONTROL_USAGE: &str = "usage: strata-next service-control status|start|stop|restart|enable|disable --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service]"; +const CONTROL_USAGE: &str = "usage: strata-next service-control status|start|stop|restart|enable|disable|start-ready|restart-ready --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--ready-url LOOPBACK_ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]"; -fn control_options(args: &[String]) -> Result<(&str, Options), String> { +fn control_options(args: &[String]) -> Result<(&str, Options, Option>), String> { let (action, args) = args.split_first().ok_or(CONTROL_USAGE)?; if !matches!( action.as_str(), - "status" | "start" | "stop" | "restart" | "enable" | "disable" + "status" + | "start" + | "stop" + | "restart" + | "enable" + | "disable" + | "start-ready" + | "restart-ready" ) { return Err(CONTROL_USAGE.into()); } - let options = parse(args).map_err(|e| if e == USAGE { CONTROL_USAGE.into() } else { e })?; + let mut service_args = Vec::new(); + let mut readiness_args = Vec::new(); + let mut args = args.iter(); + while let Some(flag) = args.next() { + if matches!( + flag.as_str(), + "--ready-url" | "--ready-model" | "--ready-key-file" | "--ready-timeout-s" + ) { + readiness_args.push(flag.replacen("--ready-", "--", 1)); + readiness_args.push(args.next().ok_or(CONTROL_USAGE)?.clone()); + } else { + service_args.push(flag.clone()); + if matches!( + flag.as_str(), + "--config" | "--working-dir" | "--env-file" | "--unit" + ) { + service_args.push(args.next().ok_or(CONTROL_USAGE)?.clone()); + } + } + } + let ready = matches!(action.as_str(), "start-ready" | "restart-ready"); + if ready { + crate::wait_ready::validate(&readiness_args)?; + } else if !readiness_args.is_empty() { + return Err(CONTROL_USAGE.into()); + } + let options = + parse(&service_args).map_err(|e| if e == USAGE { CONTROL_USAGE.into() } else { e })?; if options.start || options.enable { return Err(CONTROL_USAGE.into()); } - Ok((action, options)) + Ok((action, options, ready.then_some(readiness_args))) } #[cfg(unix)] @@ -100,10 +134,14 @@ fn unit_directory() -> Result { } pub async fn control(args: &[String]) -> Result { - let (action, options) = control_options(args)?; + let (action, options, readiness_args) = control_options(args)?; if !cfg!(target_os = "linux") { return Err("service-control requires Linux with a running systemd user manager".into()); } + let waiter = readiness_args + .as_ref() + .map(|args| crate::wait_ready::Waiter::new(args)) + .transpose()?; #[cfg(unix)] { let content = crate::service_unit::render( @@ -122,7 +160,12 @@ pub async fn control(args: &[String]) -> Result { unix::check_activation_link(&path)?; } if action != "status" { - unix::systemctl(action, &options.unit, std::time::Duration::from_secs(60)).await + let manager_action = match action { + "start-ready" => "start", + "restart-ready" => "restart", + other => other, + }; + unix::systemctl(manager_action, &options.unit, std::time::Duration::from_secs(60)).await .map_err(|e| format!("{e}; manager action may be pending; inspect service-control status before retrying"))?; } if matches!(action, "enable" | "disable") { @@ -137,15 +180,43 @@ pub async fn control(args: &[String]) -> Result { let manager = unix::status(&options.unit).await.map_err(|e| { format!("{e}; {action} outcome needs reconciliation; no action was replayed") })?; - Ok( - serde_json::json!({"unit":options.unit,"action":action,"manager":manager, - "action_requested":action != "status", "model_readiness":"not_checked"}), - ) + let mut result = serde_json::json!({"unit":options.unit,"action":action,"manager":manager, + "action_requested":action != "status", "model_readiness":"not_checked"}); + if let Some(waiter) = waiter { + let pid = active_pid(&manager)?; + let readiness = waiter.wait(Some(pid)).await.map_err(|error| format!( + "{error}; {action} was requested; service left for explicit reconciliation, no lifecycle action was replayed" + ))?; + unix::same_file(&path, content.as_bytes()) + .map_err(|_| "unit changed during readiness wait; reconcile explicitly")?; + unix::verify_loaded_unit(&options.unit, &path).await?; + let current = unix::status(&options.unit).await?; + if active_pid(¤t)? != pid { + return Err( + "managed process changed during readiness wait; reconcile explicitly".into(), + ); + } + result["manager"] = current; + result["model_readiness"] = serde_json::json!("ready"); + result["readiness"] = readiness; + } + Ok(result) } #[cfg(not(unix))] Err("service-control requires Linux".into()) } +fn active_pid(manager: &serde_json::Value) -> Result { + if manager["active_state"] != "active" || manager["sub_state"] != "running" { + return Err("managed service is not running; readiness cannot be confirmed".into()); + } + manager["main_pid"] + .as_u64() + .and_then(|n| u32::try_from(n).ok()) + .filter(|n| *n > 0) + .ok_or_else(|| "managed service has no valid active PID".into()) +} + pub async fn run(args: &[String]) -> Result { let options = parse(args)?; let content = crate::service_unit::render( @@ -668,4 +739,43 @@ mod tests { assert!(control_options(&invalid_control).is_err()); assert_eq!(options.unit, "strata-next.service"); } + #[test] + fn managed_readiness_options_and_active_process_are_strict() { + let base = ["start-ready", "--config", "/a", "--working-dir", "/b"]; + let mut args = base.map(str::to_owned).to_vec(); + assert!(control_options(&args).is_err()); + args.extend( + [ + "--ready-url", + "http://127.0.0.1:8080", + "--ready-model", + "fixture", + ] + .map(str::to_owned), + ); + assert!(control_options(&args).unwrap().2.is_some()); + args[0] = "restart-ready".into(); + assert!(control_options(&args).is_ok()); + for action in ["status", "start", "restart", "enable"] { + args[0] = action.into(); + assert!(control_options(&args).is_err()); + } + args[0] = "start-ready".into(); + args.extend(["--ready-timeout-s", "0"].map(str::to_owned)); + assert!(control_options(&args).is_err()); + let good = + serde_json::json!({"active_state":"active", "sub_state":"running", "main_pid":123}); + assert_eq!(active_pid(&good).unwrap(), 123); + for (key, value) in [ + ("main_pid", serde_json::json!(0)), + ("main_pid", serde_json::json!(4294967296u64)), + ("main_pid", serde_json::json!("123")), + ("active_state", serde_json::json!("inactive")), + ("sub_state", serde_json::json!("dead")), + ] { + let mut bad = good.clone(); + bad[key] = value; + assert!(active_pid(&bad).is_err()); + } + } } diff --git a/control-plane/src/wait_ready.rs b/control-plane/src/wait_ready.rs index 01ef5f4f..089bddd7 100644 --- a/control-plane/src/wait_ready.rs +++ b/control-plane/src/wait_ready.rs @@ -73,11 +73,16 @@ fn parse(args: &[String]) -> Result { }) } +pub(crate) fn validate(args: &[String]) -> Result<(), String> { + parse(args).map(|_| ()) +} + async fn probe( client: &Client, url: &Url, key: Option<&HeaderValue>, model: &str, + expected_pid: Option, ) -> Result { let mut request = client.get(url.clone()); if let Some(key) = key { @@ -128,6 +133,11 @@ async fn probe( { return Err("readiness service or model does not match the requested deployment".into()); } + if expected_pid + .is_some_and(|pid| value.get("server_pid").and_then(Value::as_u64) != Some(u64::from(pid))) + { + return Err("readiness endpoint does not match the managed server PID".into()); + } let ready = value .get("ready") .and_then(Value::as_bool) @@ -148,39 +158,66 @@ async fn probe( Ok(ready) } -pub async fn run(args: &[String]) -> Result { - let options = parse(args)?; - let key = options - .key_file - .as_ref() - .map(|file| { - let token = crate::auth::read_token(Path::new(file)) - .map_err(|_| "unable to read a valid private API key file")?; - let mut header = - HeaderValue::from_str(&format!("Bearer {token}")).map_err(|_| "invalid API key")?; - header.set_sensitive(true); - Ok::<_, String>(header) +pub(crate) struct Waiter { + options: Options, + key: Option, + client: Client, +} + +impl Waiter { + pub(crate) fn new(args: &[String]) -> Result { + let options = parse(args)?; + let key = options + .key_file + .as_ref() + .map(|file| { + let token = crate::auth::read_token(Path::new(file)) + .map_err(|_| "unable to read a valid private API key file")?; + let mut header = HeaderValue::from_str(&format!("Bearer {token}")) + .map_err(|_| "invalid API key")?; + header.set_sensitive(true); + Ok::<_, String>(header) + }) + .transpose()?; + let client = Client::builder() + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .connect_timeout(Duration::from_secs(3)) + .timeout(Duration::from_secs(3)) + .build() + .map_err(|_| "unable to initialize readiness HTTP client")?; + Ok(Self { + options, + key, + client, }) - .transpose()?; - let client = Client::builder() - .no_proxy() - .redirect(reqwest::redirect::Policy::none()) - .connect_timeout(Duration::from_secs(3)) - .timeout(Duration::from_secs(3)) - .build() - .map_err(|_| "unable to initialize readiness HTTP client")?; - // Includes connect, headers, every body chunk, and all retry sleeps. A peer - // sending bytes more often than a socket timeout cannot prolong this budget. - tokio::time::timeout(options.timeout, async { + } + + pub(crate) async fn wait(self, expected_pid: Option) -> Result { + let Self { + options, + key, + client, + } = self; + // Includes connect, headers, every body chunk, and all retry sleeps. A peer + // sending bytes more often than a socket timeout cannot prolong this budget. + tokio::time::timeout(options.timeout, async { let mut attempts = 0u64; loop { attempts += 1; - if probe(&client, &options.url, key.as_ref(), &options.model).await? { - return Ok(json!({"ready":true, "service":"strata-control", "model":options.model, "attempts":attempts})); + if probe(&client, &options.url, key.as_ref(), &options.model, expected_pid).await? { + let mut result = json!({"ready":true, "service":"strata-control", "model":options.model, "attempts":attempts}); + if let Some(pid) = expected_pid { result["server_pid"] = json!(pid); } + return Ok(result); } tokio::time::sleep(Duration::from_millis(250)).await; } }).await.map_err(|_| "readiness deadline expired; model did not become ready within timeout-s")? + } +} + +pub async fn run(args: &[String]) -> Result { + Waiter::new(args)?.wait(None).await } #[cfg(test)] @@ -193,6 +230,41 @@ mod tests { .to_vec() } + #[tokio::test] + async fn managed_readiness_requires_exact_numeric_pid_but_plain_wait_is_compatible() { + for reported in [ + None, + Some(json!(123)), + Some(json!(124)), + Some(json!("123")), + Some(json!(0)), + ] { + let mut body = json!({"service":"strata-control", "model":"fixture", "ready":true, "worker":"ready"}); + if let Some(value) = reported.clone() { + body["server_pid"] = value; + } + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let router = axum::Router::new().route( + "/status", + axum::routing::get(move || async move { axum::Json(body) }), + ); + let server = tokio::spawn(async move { + axum::serve(listener, router).await.unwrap(); + }); + let managed = Waiter::new(&args(&url)).unwrap().wait(Some(123)).await; + assert_eq!(managed.is_ok(), reported == Some(json!(123))); + if let Ok(value) = managed { + assert_eq!(value["server_pid"], 123); + } + let plain = run(&args(&url)).await.unwrap(); + assert_eq!(plain["ready"], true); + assert!(plain.get("server_pid").is_none()); + server.abort(); + let _ = server.await; + } + } + #[test] fn validates_origin_and_budgets_before_network_or_credentials() { for url in ["http://127.0.0.1:18082", "http://[::1]:18082/"] { diff --git a/deploy/README.md b/deploy/README.md index e90f1a93..62b230c1 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -67,7 +67,8 @@ The native executable can install and operate its per-user service directly: --unit strata-next-prod.service ``` -`service-control` accepts `status`, `start`, `stop`, `restart`, `enable` or `disable`. Supply the same +`service-control` accepts `status`, `start`, `stop`, `restart`, `enable`, `disable`, +`start-ready` or `restart-ready`. Supply the same executable, config, working directory, optional `--env-file` and unit name used at installation. The CLI verifies the existing private unit's exact generated content and the user manager's fragment path/no drop-ins before operating on it. @@ -80,6 +81,34 @@ The JSON result includes `manager.active_state`, `manager.sub_state`, `manager.main_pid`, `manager.unit_file_state` and `model_readiness: "not_checked"`. Use native `wait-ready` for actual model readiness. No journal or environment contents are returned. +For a managed start that also verifies model readiness, use: + +```sh +/absolute/path/strata-next service-control start-ready \ + --config /absolute/path/config.json --working-dir /absolute/path/workdir \ + --unit strata-next-prod.service \ + --ready-url http://127.0.0.1:18082 --ready-model MODEL_ID \ + --ready-key-file /absolute/path/api.key --ready-timeout-s 120 +``` + +`restart-ready` explicitly restarts first; `start-ready` reuses an already running +service. Both require a literal loopback HTTP origin and model ID. The key file is +optional for an unauthenticated profile. Options and private key validity are +checked before any manager command. After the manager action, the bounded HTTP +wait checks service/model/worker readiness and `server_pid` against the managed +MainPID. Before returning `model_readiness: "ready"`, it rechecks the exact unit, +loaded definition, active state and unchanged MainPID. `/status` and `/ready` +include `server_pid`; standalone `wait-ready` still accepts endpoints without it. + +This process correlation requires the same local PID namespace. A PID is neither +authentication nor a durable process epoch, and readiness is a point-in-time +observation. The readiness timeout (1–3600 seconds, default 300) starts after the +manager action; manager query/action limits still apply separately. On a wait or +identity failure, the CLI returns an error and leaves the service for explicit +reconciliation. It does not repeat the action, stop an unrelated endpoint or +perform automatic rollback. Hosted checks use an isolated synthetic worker, +including cold/repeated start, restart, exact output A, mismatched PID and timeout. + To opt in to startup in future user-manager sessions, add `--enable` to `service-install`. It is independent of `--start`: enabling alone does not start or restart the runtime. For an installed unit use `service-control enable` or diff --git a/scripts/smoke-service-unit.py b/scripts/smoke-service-unit.py index 52be8cc0..18daa63f 100644 --- a/scripts/smoke-service-unit.py +++ b/scripts/smoke-service-unit.py @@ -5,6 +5,9 @@ Requires Linux/systemd. --lifecycle needs a running user manager. It never touches an existing inference service. Activation tests use only the temporary owned unit. """ import argparse +import http.server +import importlib.util +import threading import json import os from pathlib import Path @@ -130,6 +133,40 @@ exit {42 if fail_action else 0} if action != 'status': assert lines[1] == f'--user|--no-pager|{action}|--|{unit_name}' assert fault_unit.read_bytes() == retained + # Readiness inputs and private credentials are checked before any manager call. + for ready_args in [[], ['--ready-url', 'http://192.0.2.1', '--ready-model', 'fixture'], + ['--ready-url', 'http://127.0.0.1:1', '--ready-model', 'fixture', '--ready-key-file', str(root/'absent-key')]]: + commands.write_text('') + bad = run(str(binary), 'service-control', 'restart-ready', *fault_args[2:], *ready_args, + env=fault_env, check=False) + assert bad.returncode != 0 and not commands.read_text(), bad.stderr + # Change identity only after the HTTP response. Success requires a fresh + # manager/file check and cannot replay start to hide the mismatch. + for changed in ('pid', 'fragment', 'unit'): + manager(); commands.write_text('') + class ChangingEndpoint(http.server.BaseHTTPRequestHandler): + def do_GET(self): + if changed == 'pid': + manager(status='ActiveState=active\nSubState=running\nMainPID=124\nUnitFileState=disabled\n') + elif changed == 'fragment': manager(fragment='/changed.service') + else: fault_unit.write_text('changed during wait') + data = json.dumps({'service':'strata-control', 'model':'fixture', 'server_pid':123, + 'ready':True, 'worker':'ready'}).encode() + self.send_response(200); self.send_header('Content-Length', str(len(data))) + self.end_headers(); self.wfile.write(data) + def log_message(self, *_): pass + changed_http = http.server.ThreadingHTTPServer(('127.0.0.1', 0), ChangingEndpoint) + changed_thread = threading.Thread(target=changed_http.serve_forever, daemon=True); changed_thread.start() + try: + bad = run(str(binary), 'service-control', 'start-ready', *fault_args[2:], + '--ready-url', f'http://127.0.0.1:{changed_http.server_port}', '--ready-model', 'fixture', + '--ready-timeout-s', '2', env=fault_env, check=False) + assert bad.returncode != 0, bad.stdout + actions = [line.split('|')[2] for line in commands.read_text().splitlines()] + assert actions.count('start') == 1 and all(a in ('start','show') for a in actions), actions + finally: + changed_http.shutdown(); changed_http.server_close(); changed_thread.join(timeout=5) + fault_unit.write_bytes(retained) for fragment, drop_ins in [('/different.service', ''), (None, '/unexpected.conf')]: manager(fragment, drop_ins); commands.write_text('') assert control('restart', check=False).returncode != 0 @@ -210,7 +247,7 @@ exit {42 if fail_action else 0} status = native_ctl('status') assert status['manager']['active_state'] == 'active' and status['model_readiness'] == 'not_checked' pid = status['manager']['main_pid'] - assert pid == int(original_pid) + assert pid == int(original_pid) and state['server_pid'] == pid assert native_ctl('start')['manager']['main_pid'] == pid assert status['manager']['unit_file_state'] == 'disabled' activation = link.parent / 'default.target.wants' / unit_name @@ -259,6 +296,69 @@ exit {42 if fail_action else 0} assert native_ctl('status')['manager']['active_state'] == 'inactive' assert native_ctl('start')['manager']['main_pid'] > 0 native_ctl('stop') + # Configure only this stopped, owned fixture for synthetic inference. + spec = importlib.util.spec_from_file_location('worker_fixture', Path(__file__).with_name('smoke-worker-cancel.py')) + fixture = importlib.util.module_from_spec(spec) + spec.loader.exec_module(fixture) + tokens = root / 'tokens'; tokens.mkdir(); fixture.tokenizer(tokens) + engine = root / 'ready-worker.sh' + engine.write_text("#!/bin/sh\nprintf 'READY 262144 stop\\n'\nwhile IFS= read -r line; do\n case \"$line\" in\n 'GEN '*) printf 'T 65\\nDONE 1 7 1.0 2.0 stop\\n' ;;\n QUIT) exit 0 ;;\n esac\ndone\n") + engine.chmod(0o700) + key_file = root / 'api.key'; key_file.write_text('service-fixture-private-key-0123456789'); key_file.chmod(0o600) + config.write_text(json.dumps({'bind': f'127.0.0.1:{port}', 'model': 'service-smoke', + 'api_key_file': str(key_file), 'engine': {'executable': str(engine), 'tokenizer_dir': str(tokens)}})) + ready_args = ['--ready-url', f'http://127.0.0.1:{port}', '--ready-model', 'service-smoke-env', + '--ready-key-file', str(key_file), '--ready-timeout-s', '10'] + def ready_control(action, options=ready_args, check=True): + value = run(str(binary), 'service-control', action, *install_args[2:], *options, check=False) + if check: assert value.returncode == 0, value.stderr + return value + def inference(): + request = urllib.request.Request(f'http://127.0.0.1:{port}/v1/responses', + data=json.dumps({'model':'service-smoke-env', 'input':'fixture', 'max_output_tokens':8, 'reasoning':{'effort':'none'}}).encode(), + headers={'Content-Type':'application/json', 'Authorization':'Bearer service-fixture-private-key-0123456789'}) + with urllib.request.urlopen(request, timeout=5) as response: + value = json.load(response) + assert value['status'] == 'completed', value + assert value['output'][0]['content'][0]['text'] == 'A', value + first = json.loads(ready_control('start-ready').stdout) + pid = first['manager']['main_pid'] + assert first['model_readiness'] == 'ready' and first['readiness']['server_pid'] == pid + inference() + assert json.loads(ready_control('start-ready').stdout)['manager']['main_pid'] == pid + for bad_options in [ready_args + ['--ready-timeout-s', '0'], + ready_args[:4] + ['--ready-key-file', str(root/'missing-key')]]: + assert ready_control('restart-ready', bad_options, check=False).returncode != 0 + assert native_ctl('status')['manager']['main_pid'] == pid + response_body = {'service':'strata-control', 'model':'service-smoke-env', + 'ready':True, 'worker':'ready', 'server_pid':1} + class OtherEndpoint(http.server.BaseHTTPRequestHandler): + def do_GET(self): + data = json.dumps(response_body).encode() + self.send_response(200); self.send_header('Content-Length', str(len(data))) + self.end_headers(); self.wfile.write(data) + def log_message(self, *_): pass + other_http = http.server.ThreadingHTTPServer(('127.0.0.1', 0), OtherEndpoint) + thread = threading.Thread(target=other_http.serve_forever, daemon=True); thread.start() + try: + wrong = ready_args.copy(); wrong[1] = f'http://127.0.0.1:{other_http.server_port}' + bad = ready_control('start-ready', wrong, check=False) + assert bad.returncode != 0 and 'managed server PID' in bad.stderr, bad.stderr + response_body.update(server_pid=pid, ready=False, worker='starting') + wrong[-1] = '1' + began = time.monotonic() + bad = ready_control('start-ready', wrong, check=False) + assert bad.returncode != 0 and 'deadline expired' in bad.stderr and time.monotonic()-began < 5, bad.stderr + assert native_ctl('status')['manager']['main_pid'] == pid + inference() + finally: + other_http.shutdown(); other_http.server_close(); thread.join(timeout=5) + restarted = json.loads(ready_control('restart-ready').stdout) + new_pid = restarted['manager']['main_pid'] + assert new_pid != pid and restarted['readiness']['server_pid'] == new_pid and not Path(f'/proc/{pid}').exists() + inference() + native_ctl('stop') + print('Managed start-ready/restart-ready passed: authenticated exact PID, cold/reuse/restart, exact A, invalid inputs before mutation, wrong endpoint refusal, bounded timeout without replay') print('Native systemd install/reuse/conflict/lifecycle passed: literal paths, explicit config, environment, health/readiness plus native status/start/restart/stop/reuse, opt-in enable/disable PID preservation and identity/link refusal') finally: # Remove only the activation link for our randomly named unit, if it