diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index a6cf6d3b..1066c1fa 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|--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()), + _ => Err("usage: strata-next [service-switch --catalog FILE [--from ID] --to ID --state-dir ABSOLUTE_DIR|service-switch reconcile --catalog FILE --state-dir DIR --expected-journal-sha SHA256|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_switch.rs b/control-plane/src/service_switch.rs index 0702f9b6..f38087f9 100644 --- a/control-plane/src/service_switch.rs +++ b/control-plane/src/service_switch.rs @@ -224,6 +224,13 @@ mod storage { } impl Journal { pub(super) fn open(path: &Path, value: Value) -> Result { + Self::open_inner(path, value, false) + } + pub(super) fn reconciliation(path: &Path) -> Result { + read(&path.join("transaction.json"), true, 65536)?; + Self::open_inner(path, json!({}), true) + } + fn open_inner(path: &Path, value: Value, reconciliation: bool) -> Result { if !path.is_absolute() || path.file_name().is_none() { return Err("state directory must be absolute and non-root".into()); } @@ -269,17 +276,19 @@ mod storage { Ok(_) => { let prior: Value = serde_json::from_slice(&read(&previous, true, 65536)?) .map_err(|_| "invalid prior transaction; reconcile explicitly")?; - if prior["schema_version"] != 1 - || !matches!( - prior["phase"].as_str(), - Some( - "committed" - | "rolled_back" - | "preflight_failed" - | "cold_failed" - | "reused" - ) - ) + if !reconciliation + && (prior["schema_version"] != 1 + || !matches!( + prior["phase"].as_str(), + Some( + "committed" + | "rolled_back" + | "preflight_failed" + | "cold_failed" + | "reused" + | "reconciled" + ) + )) { return Err("unfinished or unknown switch transaction; inspect services and archive journal only after explicit reconciliation".into()); } @@ -364,6 +373,9 @@ async fn prepare(profile: &Profile, budget: u64) -> Result<(), String> { } pub async fn run(args: &[String]) -> Result { + if args.first().is_some_and(|arg| arg == "reconcile") { + return reconcile(&args[1..]).await; + } let args = arguments(args)?; if !cfg!(target_os = "linux") { return Err("service-switch requires Linux systemd user services".into()); @@ -536,10 +548,156 @@ pub async fn run(args: &[String]) -> Result { Err("service-switch requires Linux".into()) } +fn reconcile_arguments(args: &[String]) -> Result, String> { + const HELP: &str = "usage: service-switch reconcile --catalog FILE --state-dir DIR --expected-journal-sha SHA256"; + let mut result = BTreeMap::new(); + let (pairs, remainder) = args.as_chunks::<2>(); + if !remainder.is_empty() { + return Err(HELP.into()); + } + for [flag, value] in pairs { + if !matches!( + flag.as_str(), + "--catalog" | "--state-dir" | "--expected-journal-sha" + ) || result.insert(flag.clone(), value.clone()).is_some() + { + return Err(HELP.into()); + } + } + if result.len() != 3 { + return Err(HELP.into()); + } + let sha = &result["--expected-journal-sha"]; + if sha.len() != 64 + || !sha + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + return Err("expected journal SHA must be 64 lowercase hex digits".into()); + } + Ok(result) +} + +async fn reconcile(args: &[String]) -> Result { + let args = reconcile_arguments(args)?; + if !cfg!(target_os = "linux") { + return Err("reconciliation requires Linux systemd user services".into()); + } + #[cfg(unix)] + { + use storage::{Journal, read}; + let state = Path::new(&args["--state-dir"]); + let mut journal = Journal::reconciliation(state)?; + let path = state.join("transaction.json"); + let bytes = read(&path, true, 65536)?; + let sha = hex::encode(Sha256::digest(&bytes)); + if sha != args["--expected-journal-sha"] { + return Err("journal acknowledgment mismatch; no reconciliation recorded".into()); + } + let prior: Value = + serde_json::from_slice(&bytes).map_err(|_| "invalid transaction journal")?; + if prior["schema_version"] != 1 + || !matches!( + prior["phase"].as_str(), + Some( + "preparing" + | "draining_previous" + | "starting_target" + | "stopping_failed_target" + | "restoring_previous" + | "needs_reconciliation" + ) + ) + { + return Err("reconciliation requires a known interrupted phase".into()); + } + let catalog_bytes = read(Path::new(&args["--catalog"]), true, 65536)?; + if prior["catalog_sha256"] != hex::encode(Sha256::digest(&catalog_bytes)) { + return Err("catalog differs from interrupted transaction".into()); + } + let catalog: Catalog = + serde_json::from_slice(&catalog_bytes).map_err(|_| "invalid native catalog")?; + if catalog.schema_version != 1 || catalog.profiles.is_empty() || catalog.profiles.len() > 16 + { + return Err("invalid catalog schema/count".into()); + } + let target = prior["to"] + .as_str() + .and_then(|id| catalog.profiles.get(id)) + .ok_or("journal target absent from catalog")?; + let digests = validate_auto(&catalog, target)?; + for (id_field, sha_field) in [ + ("from", "previous_config_sha256"), + ("to", "target_config_sha256"), + ] { + if let Some(id) = prior[id_field].as_str() { + if !digests + .get(id) + .is_some_and(|digest| prior[sha_field].as_str() == Some(digest.as_str())) + { + return Err( + "recorded configuration differs; reconcile configuration explicitly first" + .into(), + ); + } + } else if !prior[id_field].is_null() { + return Err("invalid recorded profile identity".into()); + } + } + let current = discover(&catalog).await?; + let readiness = if let Some((id, pid)) = ¤t { + Some( + crate::wait_ready::Waiter::new(&catalog.profiles[id].readiness())? + .wait(Some(*pid)) + .await?, + ) + } else { + None + }; + if discover(&catalog).await? != current + || validate_auto(&catalog, target)? != digests + || read(&path, true, 65536)? != bytes + { + return Err("state changed during reconciliation; no record written".into()); + } + journal.value = json!({"schema_version":1,"catalog_sha256":prior["catalog_sha256"], + "prior_journal_sha256":sha,"prior_phase":prior["phase"],"from":prior["from"],"to":prior["to"], + "verified_profile":current.as_ref().map(|(id,_)|id),"verified_pid":current.as_ref().map(|(_,pid)|pid)}); + journal.phase("reconciled")?; + Ok( + json!({"reconciled":true,"lifecycle_action_requested":false,"profile":current.as_ref().map(|(id,_)|id), + "pid":current.as_ref().map(|(_,pid)|pid),"prior_journal_sha256":sha,"readiness":readiness}), + ) + } + #[cfg(not(unix))] + Err("reconciliation requires Linux".into()) +} + #[cfg(test)] mod tests { use super::*; #[test] + fn reconciliation_requires_explicit_exact_digest_arguments() { + let args = vec![ + "--catalog".into(), + "/catalog".into(), + "--state-dir".into(), + "/state".into(), + "--expected-journal-sha".into(), + "a".repeat(64), + ]; + assert!(reconcile_arguments(&args).is_ok()); + for digest in ["a".repeat(63), "A".repeat(64), "z".repeat(64)] { + let mut bad = args.clone(); + bad[5] = digest; + assert!(reconcile_arguments(&bad).is_err()); + } + assert!(reconcile_arguments(&args[..5]).is_err()); + let mut duplicate = args.clone(); + duplicate.extend(args[..2].iter().cloned()); + assert!(reconcile_arguments(&duplicate).is_err()); + } + #[test] fn explicit_distinct_profiles_and_strict_catalog() { assert!(arguments(&[]).is_err()); let mut args = [ diff --git a/deploy/README.md b/deploy/README.md index dfe63da4..e522109a 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -198,7 +198,9 @@ An unfinished/unknown journal prevents another switch. After interruption, inspect both units with `service-control status` and their native lifecycle endpoints. Explicitly keep the selected service, or stop the target and restore the previous one using the existing native controls; resume admission if needed. -Archive the private journal only after confirming the intended state, then retry. +For known interrupted phases, use the SHA-bound `service-switch reconcile` command +below to verify and record that state before a new explicit selection. Unknown +or corrupt records remain blocked for manual investigation. This version does not automatically recover across command/process crashes. PID checks require the same namespace; all artifact paths must remain immutable through the transaction. Tests qualify actual isolated Linux services with CPU @@ -1063,3 +1065,23 @@ 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. + +### Reconcile an interrupted profile selection + +After inspecting `service-control status` for the catalog units, acknowledge the +exact private transaction record and verify the current state without replaying +any lifecycle command: + +```sh +sha256sum /home/operator/strata/switch-state/transaction.json +strata-next service-switch reconcile --catalog /home/operator/strata/catalog.json \ + --state-dir /home/operator/strata/switch-state --expected-journal-sha SHA256_FROM_ABOVE +``` + +Reconciliation requires the original catalog and recorded config digests, a +known interrupted phase, and either all units inactive or exactly one ready +native process. It rejects ambiguous, failed or transitional states. The result +records the prior journal digest/phase and current profile/PID; it does not +start, stop, drain, resume or prepare a model. A later explicit selection can +then proceed. Wrong acknowledgments or changed configurations leave the journal +unchanged. Keep external administration serialized with these operations. diff --git a/scripts/smoke-native-switch.py b/scripts/smoke-native-switch.py index 22031ff5..7ab91030 100644 --- a/scripts/smoke-native-switch.py +++ b/scripts/smoke-native-switch.py @@ -3,6 +3,7 @@ Synthetic CPU workers only. Never inspect or modify any existing unit. """ import fcntl +import hashlib import importlib.util import json import os @@ -114,6 +115,44 @@ def main(): assert result.returncode!=0 and 'reconciliation' in result.stderr assert status('next')['main_pid']==restored and status('old')['main_pid']==0 inference('next') + # Explicit SHA acknowledgment reconciles stable state without lifecycle replay. + record=state/'transaction.json'; before=record.read_bytes() + digest=hashlib.sha256(before).hexdigest() + def reconcile(sha,check=True): + return run(str(binary),'service-switch','reconcile','--catalog',str(catalog), + '--state-dir',str(state),'--expected-journal-sha',sha,check=check) + assert reconcile('0'*64,check=False).returncode!=0 + assert record.read_bytes()==before and status('next')['main_pid']==restored + original_catalog=catalog.read_bytes();catalog.write_bytes(original_catalog+b' ') + assert reconcile(digest,check=False).returncode!=0 + catalog.write_bytes(original_catalog);assert record.read_bytes()==before + changed=Path(profiles['next']['config']); original_config=changed.read_bytes() + changed.write_bytes(original_config+b' ') + assert reconcile(digest,check=False).returncode!=0 + changed.write_bytes(original_config);assert record.read_bytes()==before + extra=Path(profiles['preflight']['config']); extra_before=extra.read_bytes() + extra_config=json.loads(original_config);extra_config['bind']='127.0.0.1:0' + extra.write_text(json.dumps(extra_config));control('preflight','start') + extra_pid=status('preflight')['main_pid'];assert extra_pid>0 + result=reconcile(digest,check=False) + assert result.returncode!=0 and 'multiple catalog' in result.stderr,result.stderr + assert record.read_bytes()==before and status('next')['main_pid']==restored + control('preflight','stop');extra.write_bytes(extra_before) + reconciled=json.loads(reconcile(digest).stdout) + assert reconciled['reconciled'] and not reconciled['lifecycle_action_requested'] + assert reconciled['pid']==restored and reconciled['profile']=='next' + assert status('next')['main_pid']==restored;inference('next') + terminal=record.read_bytes(); assert json.loads(terminal)['prior_journal_sha256']==digest + assert reconcile(digest,check=False).returncode!=0 and record.read_bytes()==terminal + assert json.loads(select('old').stdout)['profile']=='old';inference('old') + # All-inactive reconciliation also allows a later explicit cold start. + control('old','stop') + prior=json.loads(record.read_bytes());prior['phase']='starting_target' + record.write_text(json.dumps(prior));digest=hashlib.sha256(record.read_bytes()).hexdigest() + reconciled=json.loads(reconcile(digest).stdout) + assert reconciled['pid'] is None and reconciled['profile'] is None + assert json.loads(select('next').stdout)['cold_started'];inference('next') + print('Native reconciliation passed: wrong SHA/catalog/config preserve record, stable PID/A retained, no lifecycle replay, subsequent switch and all-inactive cold selection') print('Native switch passed: cold failure cleanup/retry, cold start, same-target PID/A reuse, multiple-active refusal, preparation preserves PID/A, OS lock, automatic old-to-next and failed-target rollback/A, durable interrupted refusal; CPU only') finally: for unit,path,generated in reversed(owned):