From d0afe7ace5e215ec545bccaaa87bd5cd4a134238 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 11:31:13 +0200 Subject: [PATCH] feat: confirm model readiness during native service installation (#38) --- control-plane/src/main.rs | 2 +- control-plane/src/service_install.rs | 120 +++++++++++++++++++++++++-- deploy/README.md | 21 +++++ scripts/smoke-service-unit.py | 22 ++++- 4 files changed, 158 insertions(+), 7 deletions(-) diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index bee83bac..a6cf6d3b 100644 --- a/control-plane/src/main.rs +++ b/control-plane/src/main.rs @@ -765,7 +765,7 @@ async fn main() -> Result<(), Box> { print!("{}", include_str!("../third_party/ggml/LICENSE")); Ok(()) } - _ => Err("usage: strata-next [service-switch --catalog FILE [--from ID] --to ID --state-dir ABSOLUTE_DIR|api-key init --file ABSOLUTE_PATH|serve [--config FILE]|provision --config FILE [--defer-memory-check]|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|drain-stop|resume --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()), + _ => Err("usage: strata-next [service-switch --catalog FILE [--from ID] --to ID --state-dir ABSOLUTE_DIR|api-key init --file ABSOLUTE_PATH|serve [--config FILE]|provision --config FILE [--defer-memory-check]|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|drain-stop|resume --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|--start-ready --ready-url ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|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 ce8e69b0..07891f4a 100644 --- a/control-plane/src/service_install.rs +++ b/control-plane/src/service_install.rs @@ -2,6 +2,7 @@ use std::path::{Path, PathBuf}; const USAGE: &str = "usage: strata-next service-install --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--enable] [--start]"; +const INSTALL_READY_USAGE: &str = "service-install --start-ready requires --ready-url LOOPBACK_ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]; do not combine with --start"; #[derive(Debug)] struct Options { @@ -70,6 +71,65 @@ fn validate_name(name: &str) -> Result<(), String> { } } +fn install_options(args: &[String]) -> Result<(Options, Option>), String> { + let mut service = Vec::new(); + let mut readiness = Vec::new(); + let mut start_ready = false; + let mut args = args.iter(); + while let Some(flag) = args.next() { + if flag == "--start-ready" { + if start_ready { + return Err(INSTALL_READY_USAGE.into()); + } + start_ready = true; + } else if matches!( + flag.as_str(), + "--ready-url" | "--ready-model" | "--ready-key-file" | "--ready-timeout-s" + ) { + readiness.push(flag.replacen("--ready-", "--", 1)); + readiness.push(args.next().ok_or(INSTALL_READY_USAGE)?.clone()); + } else { + service.push(flag.clone()); + if matches!( + flag.as_str(), + "--config" | "--working-dir" | "--env-file" | "--unit" + ) { + service.push(args.next().ok_or(USAGE)?.clone()); + } + } + } + let mut options = parse(&service)?; + if start_ready { + if options.start { + return Err(INSTALL_READY_USAGE.into()); + } + crate::wait_ready::validate(&readiness)?; + options.start = true; + } else if !readiness.is_empty() { + return Err(INSTALL_READY_USAGE.into()); + } + Ok((options, start_ready.then_some(readiness))) +} + +fn ready_control_args(options: &Options, readiness: &[String]) -> Vec { + let mut args = vec![ + "start-ready".into(), + "--config".into(), + options.config.to_string_lossy().into_owned(), + "--working-dir".into(), + options.working_dir.to_string_lossy().into_owned(), + "--unit".into(), + options.unit.clone(), + ]; + if let Some(file) = &options.env_file { + args.extend(["--env-file".into(), file.to_string_lossy().into_owned()]); + } + for [flag, value] in readiness.as_chunks::<2>().0 { + args.extend([flag.replacen("--", "--ready-", 1), value.clone()]); + } + args +} + const CONTROL_USAGE: &str = "usage: strata-next service-control status|start|stop|restart|enable|disable|start-ready|restart-ready|drain-stop|resume --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, Option>), String> { @@ -260,7 +320,11 @@ fn active_pid(manager: &serde_json::Value) -> Result { } pub async fn run(args: &[String]) -> Result { - let options = parse(args)?; + let (options, readiness) = install_options(args)?; + // Validate private credentials and client policy before publishing anything. + if let Some(args) = &readiness { + let _ = crate::wait_ready::Waiter::new(args)?; + } let content = crate::service_unit::render( &std::env::current_exe().map_err(|e| e.to_string())?, &options.config, @@ -279,7 +343,7 @@ pub async fn run(args: &[String]) -> Result { if options.enable { actions.push("enable"); } - if options.start { + if options.start && readiness.is_none() { actions.push("start"); } for action in actions { @@ -302,9 +366,15 @@ pub async fn run(args: &[String]) -> Result { unix::verify_loaded_unit(&options.unit, &path).await?; } } - Ok( - serde_json::json!({"unit":options.unit,"path":path,"created":created,"reused":!created,"daemon_reloaded":true,"start_requested":options.start,"model_readiness":"not_checked","enable_requested":options.enable}), - ) + let mut result = serde_json::json!({"unit":options.unit,"path":path,"created":created,"reused":!created,"daemon_reloaded":true,"start_requested":options.start,"model_readiness":"not_checked","enable_requested":options.enable}); + if let Some(readiness) = readiness { + let started = control(&ready_control_args(&options, &readiness)).await + .map_err(|error| format!("{error}; installed unit retained at {}; inspect status before another lifecycle action",path.display()))?; + result["model_readiness"] = started["model_readiness"].clone(); + result["manager"] = started["manager"].clone(); + result["readiness"] = started["readiness"].clone(); + } + Ok(result) } #[cfg(not(unix))] Err("service-install requires Linux".into()) @@ -723,6 +793,46 @@ mod unix { mod tests { use super::*; #[test] + fn ready_install_is_explicit_and_control_compatible() { + let base = ["--config", "/config", "--working-dir", "/work"] + .map(str::to_owned) + .to_vec(); + let ready = [ + "--start-ready", + "--ready-url", + "http://127.0.0.1:8080", + "--ready-model", + "test", + ] + .map(str::to_owned); + let mut args = base.clone(); + args.extend(ready.clone()); + let (options, readiness) = install_options(&args).unwrap(); + assert!(options.start && !options.enable); + let control = ready_control_args(&options, &readiness.unwrap()); + assert_eq!(control_options(&control).unwrap().0, "start-ready"); + for suffix in [ + vec!["--start"], + vec!["--start-ready"], + vec!["--ready-timeout-s", "0"], + vec!["--ready-model", "duplicate"], + ] { + let mut bad = args.clone(); + bad.extend(suffix.into_iter().map(str::to_owned)); + assert!(install_options(&bad).is_err()); + } + let mut without = base.clone(); + without.extend(ready[1..].iter().cloned()); + assert!(install_options(&without).is_err()); + let mut missing = base.clone(); + missing.push("--start-ready".into()); + assert!(install_options(&missing).is_err()); + assert!(install_options(&base).unwrap().1.is_none()); + let mut old = base; + old.push("--start".into()); + assert!(install_options(&old).unwrap().0.start); + } + #[test] fn control_only_explicit_scoped_actions() { let args = ["--config", "/a", "--working-dir", "/b"]; for action in ["status", "start", "stop", "restart", "enable", "disable"] { diff --git a/deploy/README.md b/deploy/README.md index a137af43..dfe63da4 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -1042,3 +1042,24 @@ A failed cold start stops only the verified target and records `cold_failed`, allowing a later explicit selection. An interrupted or unconfirmed operation still requires reconciliation. This does not discover unmanaged runtimes or import other inference backends. + +### Install and wait for model readiness in one command + +```sh +strata-next service-install --config /home/operator/strata/runtime.json \ + --working-dir /home/operator/strata --unit strata-next-main.service \ + --start-ready --ready-url http://127.0.0.1:8080 --ready-model MODEL_ID \ + --ready-key-file /home/operator/strata/api.key --ready-timeout-s 600 +``` + +`--start-ready` verifies credentials before publishing the unit, installs or +reuses the exact unit, and waits for authenticated model readiness tied to its +systemd PID. Repeating it reuses a running service without restarting it. +`--enable` remains independently opt-in. The existing `--start` checks only the +manager operation; it cannot be combined with `--start-ready`. + +A readiness timeout or identity error returns failure and retains the unit and +service for explicit inspection through `service-control status`. It does not +silently stop, restart or replay the action. Readiness options require +`--start-ready`. Actual model loading still uses the configured serving pipeline; +this CLI option does not qualify a GPU/model combination by itself. diff --git a/scripts/smoke-service-unit.py b/scripts/smoke-service-unit.py index bad35c9f..00833a24 100644 --- a/scripts/smoke-service-unit.py +++ b/scripts/smoke-service-unit.py @@ -241,6 +241,13 @@ exit {42 if fail_action else 0} except urllib.error.HTTPError as error: assert error.code == 503 error.close() + # Installer readiness is bounded and never treats no-worker health as ready. + before=ctl('show','--property=MainPID','--value',unit_name).stdout.strip() + bad=run(*install_args,'--start-ready','--ready-url',f'http://127.0.0.1:{port}', + '--ready-model','service-smoke-env','--ready-timeout-s','1',check=False) + assert bad.returncode!=0 and 'retained' in bad.stderr,bad.stderr + assert link.read_text()==generated + assert ctl('show','--property=MainPID','--value',unit_name).stdout.strip()==before def native_ctl(action): result = run(str(binary), 'service-control', action, *install_args[2:], check=False) assert result.returncode == 0, (action, result.stderr, ctl('show', '--property=NeedDaemonReload', '--property=UnitFileState', unit_name).stdout) @@ -322,10 +329,22 @@ exit {42 if fail_action else 0} 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) + # Recreate only the stopped owned fixture to prove fresh install+ready. + assert native_ctl('status')['manager']['main_pid']==0 + assert link.read_text()==generated + link.unlink();ctl('daemon-reload') + bad=run(*install_args,'--start-ready',*ready_args[:4], + '--ready-key-file',str(root/'missing-key'),check=False) + assert bad.returncode!=0 and not link.exists() + first=json.loads(run(*install_args,'--start-ready',*ready_args).stdout) + assert first['created'] and first['start_requested'] + pid = first['manager']['main_pid'] assert first['model_readiness'] == 'ready' and first['readiness']['server_pid'] == pid inference() + repeated=json.loads(run(*install_args,'--start-ready',*ready_args).stdout) + assert repeated['reused'] and repeated['manager']['main_pid']==pid + assert repeated['readiness']['server_pid']==pid 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')]]: @@ -416,6 +435,7 @@ exit {42 if fail_action else 0} assert stopped['manager']['main_pid']==0 and stopped['admission']['drained'] print('Managed drain-stop/resume passed: active and queued exact A before stop, new admission blocked, timeout preserves process and work, explicit same-PID resume, idle drain-stop') native_ctl('stop') + print('Native install-ready passed: fresh authenticated ready install, same PID/A reuse, invalid key before publication, unconfigured timeout leaves service unchanged') 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: