diff --git a/crates/protrus-gate/src/lib.rs b/crates/protrus-gate/src/lib.rs index ee9005c..028aa40 100644 --- a/crates/protrus-gate/src/lib.rs +++ b/crates/protrus-gate/src/lib.rs @@ -1294,7 +1294,35 @@ impl DeploymentService { revision: &Revision, attempt: &str, ) -> Result { - let record = self + self.restart_crashed(module_id, revision, attempt, true)? + .ok_or_else(|| { + DeploymentError::InvalidState(format!( + "{module_id} revision {} is no longer the active revision", + revision.0 + )) + }) + } + /// `redeploy_after_crash` for a runtime its owner has already reaped, as the OCI pair watcher + /// drops the dead pair before it asks for recovery: there is nothing left to stop. Only this + /// module is brought back; the other modules' runtimes are untouched, as Protean's container + /// watcher restarts only the container that exited. `None` when the revision is no longer the + /// active one (uninstalled or replaced since), so there is nothing to restore. + pub fn redeploy_reaped_after_crash( + &self, + module_id: &ModuleId, + revision: &Revision, + attempt: &str, + ) -> Result, DeploymentError> { + self.restart_crashed(module_id, revision, attempt, false) + } + fn restart_crashed( + &self, + module_id: &ModuleId, + revision: &Revision, + attempt: &str, + stop: bool, + ) -> Result, DeploymentError> { + let Some(record) = self .store .load(module_id) .map_err(Self::store_error)? @@ -1303,15 +1331,14 @@ impl DeploymentService { && record.observed_state == ObservedState::Active && &record.revision == revision }) - .ok_or_else(|| { - DeploymentError::InvalidState(format!( - "{module_id} revision {} is no longer the active revision", - revision.0 - )) - })?; - self.backend - .drain_and_stop(&record) - .map_err(|error| DeploymentError::Runtime(error.to_string()))?; + else { + return Ok(None); + }; + if stop { + self.backend + .drain_and_stop(&record) + .map_err(|error| DeploymentError::Runtime(error.to_string()))?; + } self.deactivate_data_plane(&record); let result = self.deploy(self.stored_request( &record, @@ -1329,7 +1356,7 @@ impl DeploymentService { Err(error) => format!("failed: {error}"), }, ); - result + result.map(Some) } /// The deploy request that brings a stored record back: its own revision, routes, and signed @@ -2719,6 +2746,48 @@ mod tests { assert_eq!(*stops.lock().unwrap(), 2); } #[test] + fn a_reaped_crash_brings_back_only_that_module() { + let stops = Arc::new(Mutex::new(0)); + let service = DeploymentService::new( + MemoryStore::default(), + CountingBackend { + stops: stops.clone(), + }, + Arc::new(RouteRegistry::default()), + GatePipeline::default(), + ); + service.deploy(request("crashed", 1, "/crashed")).unwrap(); + let mut neighbour = request("neighbour", 1, "/neighbour"); + neighbour.record.module_id = ModuleId::parse("neighbour").unwrap(); + service.deploy(neighbour).unwrap(); + let crashed = ModuleId::parse("hello").unwrap(); + + let outcome = service + .redeploy_reaped_after_crash(&crashed, &Revision(1), "pair-a") + .unwrap() + .expect("the active revision is brought back"); + assert_eq!(outcome.record.observed_state, ObservedState::Active); + assert_eq!(*stops.lock().unwrap(), 0, "the reaped runtime is not stopped again"); + let neighbour = service + .store + .load(&ModuleId::parse("neighbour").unwrap()) + .unwrap() + .unwrap(); + assert_eq!( + (neighbour.observed_state, neighbour.sticky_reason), + (ObservedState::Active, None), + "the other module is not redeployed" + ); + + // Nothing to restore once the revision is no longer the active one. + assert!( + service + .redeploy_reaped_after_crash(&crashed, &Revision(7), "pair-b") + .unwrap() + .is_none() + ); + } + #[test] fn successful_replacement_stops_the_previous_active_target() { let stops = Arc::new(Mutex::new(0)); let service = DeploymentService::new( diff --git a/crates/protrus-host/src/lib.rs b/crates/protrus-host/src/lib.rs index 5697233..8547e32 100644 --- a/crates/protrus-host/src/lib.rs +++ b/crates/protrus-host/src/lib.rs @@ -55,7 +55,7 @@ use std::{ path::PathBuf, sync::{ Arc, Mutex, - atomic::{AtomicBool, Ordering}, + atomic::{AtomicBool, AtomicU64, Ordering}, }, thread::{self, JoinHandle}, time::Duration, @@ -2215,8 +2215,8 @@ where /// Crash callback for the production OCI runtime factory. It first drops the /// dead pair's local lifecycle and proxy state, then asks the deployment owner -/// to reconcile only persisted signed records. The watcher never launches a -/// replacement directly. +/// to bring that module back from its persisted signed record. The watcher +/// never launches a replacement directly. pub struct ReapingDeploymentReconcileTrigger where S: ModuleStore, @@ -2253,16 +2253,17 @@ where E: OciEngine + Clone, R: OciLaunchResolver, { + /// Brings back only the crashed module from its persisted signed record. Reconciling every + /// stored record here would prepare the live pairs of the other modules again, which fails + /// with "runtime already exists" and leaves them degraded. fn reconcile_stored(&self) -> Result<(), String> { + static ATTEMPTS: AtomicU64 = AtomicU64::new(0); self.factory.reap_crashed(&self.record)?; - let outcomes = self - .service - .reconcile_stored() - .map_err(|error| error.to_string())?; - if let Some(error) = outcomes.into_iter().find_map(Result::err) { - return Err(error.to_string()); - } - Ok(()) + let attempt = format!("pair-{}", ATTEMPTS.fetch_add(1, Ordering::Relaxed)); + self.service + .redeploy_reaped_after_crash(&self.record.module_id, &self.record.revision, &attempt) + .map(|_| ()) + .map_err(|error| error.to_string()) } } diff --git a/crates/protrus-host/tests/mcp_scenarios.rs b/crates/protrus-host/tests/mcp_scenarios.rs index ef227ae..dbd03d0 100644 --- a/crates/protrus-host/tests/mcp_scenarios.rs +++ b/crates/protrus-host/tests/mcp_scenarios.rs @@ -2,7 +2,7 @@ //! `examples/scenarios`, run against the production `protrus-host` binary over HTTP. The runner only //! speaks MCP and HTTP; it builds signed deploy inputs the way a client would. use ed25519_dalek::SigningKey; -use protrus_artifact::{ArtifactBundle, ManifestV1, SignedArtifact}; +use protrus_artifact::{ArtifactBundle, ArtifactRepository, ManifestV1, SignedArtifact}; use protrus_core::{DesiredState, ModuleId, ModuleRecord, ObservedState, Revision}; use serde::Deserialize; use serde_json::{Value, json}; @@ -190,6 +190,188 @@ fn kill_worker(sockets: &Path, module: &str) { assert!(status.success(), "kill -9 {}", pids[0]); } +/// Docker resources an OCI scenario creates: the internal worker network and every container +/// named for one of its modules (`protrus--` and its `-gateway`). +struct OciCleanup { + network: String, + modules: Vec, +} + +impl Drop for OciCleanup { + fn drop(&mut self) { + for module in &self.modules { + for name in containers(module, true) { + let _ = Command::new("docker").args(["rm", "-f", &name]).output(); + } + } + let _ = Command::new("docker") + .args(["network", "rm", &self.network]) + .output(); + } +} + +/// Names of the containers that serve `module` (`protrus--`), newest revision +/// last; with `all`, stopped containers and gateways too. +fn containers(module: &str, all: bool) -> Vec { + let mut args = vec!["ps", "--format", "{{.Names}}"]; + if all { + args.push("-a"); + } + let output = Command::new("docker").args(args).output().expect("run docker ps"); + let prefix = format!("protrus-{module}-"); + let mut names: Vec<(u64, String)> = String::from_utf8_lossy(&output.stdout) + .lines() + .filter_map(|name| { + let rest = name.strip_prefix(&prefix)?; + let revision = rest.parse().ok().or_else(|| { + all.then(|| rest.strip_suffix("-gateway")?.parse().ok()).flatten() + })?; + Some((revision, name.to_owned())) + }) + .collect(); + names.sort(); + names.into_iter().map(|(_, name)| name).collect() +} + +/// A Docker image id for `tag`, building it from `dockerfile` first unless `prebuilt` names one. +fn docker_image(tag: &str, dockerfile: &Path, context: &Path, prebuilt: Option) -> String { + let tag = match prebuilt { + Some(prebuilt) => prebuilt, + None => { + let status = Command::new("docker") + .args(["build", "-q", "-t", tag, "-f"]) + .arg(dockerfile) + .arg(context) + .status() + .expect("run docker build"); + assert!(status.success(), "docker build {tag}"); + tag.to_owned() + } + }; + let output = Command::new("docker") + .args(["image", "inspect", &tag, "--format", "{{.Id}}"]) + .output() + .expect("run docker image inspect"); + assert!(output.status.success(), "docker image inspect {tag}"); + String::from_utf8(output.stdout).unwrap().trim().to_owned() +} + +/// The OCI images, built once per test process. `PROTRUS_OCI_WORKER_IMAGE` names a prebuilt +/// worker image (the production one compiles the workspace in Docker). +fn oci_images() -> &'static (String, String) { + static IMAGES: OnceLock<(String, String)> = OnceLock::new(); + IMAGES.get_or_init(|| { + let root = repository_root(); + let fixture = root.join("poc/worker-container-fixture"); + let worker = docker_image( + &format!("protrus-runtime-worker:scenario-{}", std::process::id()), + &fixture.join("Dockerfile.runtime"), + &root, + std::env::var("PROTRUS_OCI_WORKER_IMAGE").ok(), + ); + let gateway = docker_image( + &format!("protrus-runtime-gateway:scenario-{}", std::process::id()), + &fixture.join("Dockerfile"), + &fixture, + None, + ); + (worker, gateway) + }) +} + +/// Prepares what an OCI host needs before it starts, as an operator would: the images, an +/// internal worker network, a control secret the worker user can read, and the signed gateway +/// profile published to the host's artifact store. Returns the placeholder values. +fn oci_setup( + directory: &Path, + sockets: &Path, + key: &SigningKey, + modules: Vec, +) -> (Vec<(&'static str, String)>, OciCleanup) { + use std::os::unix::fs::PermissionsExt; + let (worker_image, gateway_image) = oci_images().clone(); + let network = format!("protrus-scenario-{}", sockets.file_name().unwrap().to_str().unwrap()); + let status = Command::new("docker") + .args(["network", "create", "--internal", &network]) + .status() + .expect("run docker network create"); + assert!(status.success(), "docker network create {network}"); + let cleanup = OciCleanup { + network: network.clone(), + modules, + }; + // The worker container runs as 65532 and opens its control socket under this directory. + std::fs::create_dir_all(sockets).unwrap(); + std::fs::set_permissions(sockets, std::fs::Permissions::from_mode(0o777)).unwrap(); + let secret = sockets.join("secret"); + std::fs::write(&secret, "scenario-control-secret").unwrap(); + std::fs::set_permissions(&secret, std::fs::Permissions::from_mode(0o444)).unwrap(); + let profile = SignedArtifact::sign( + ArtifactBundle { + manifest: ManifestV1 { + api_version: "protrus/v1".into(), + kind: "gateway-profile".into(), + id: ModuleId::parse("gateway-profile").unwrap(), + version: "1".into(), + component_abi_version: 1, + scope: None, + routes: vec![], + capabilities: vec![], + dependencies: Vec::new(), + }, + files: BTreeMap::from([( + "gateway-image.digest".into(), + gateway_image.as_bytes().to_vec(), + )]), + }, + SIGNER, + key, + ) + .unwrap(); + let profile = protrus_artifact::FsArtifactRepository::new(directory.join("state")) + .publish(&profile) + .expect("publish the gateway profile"); + ( + vec![ + ("${worker_image}", worker_image), + ("${gateway_image}", gateway_image), + ("${gateway_profile}", profile.0), + ("${control_secret}", secret.to_str().unwrap().to_owned()), + ("${network}", network), + ], + cleanup, + ) +} + +/// The newest running container of `module`: 200 with its `docker inspect` object, or 404. +fn inspect_container(module: &str) -> Observed { + let Some(name) = containers(module, false).pop() else { + return Observed { + status: 404, + ..Observed::default() + }; + }; + let output = Command::new("docker") + .args(["inspect", &name]) + .output() + .expect("run docker inspect"); + let inspected: Value = serde_json::from_slice(&output.stdout).unwrap_or(Value::Null); + Observed { + status: 200, + body: inspected[0].to_string(), + ..Observed::default() + } +} + +/// `docker kill` of the newest running container of `module`, as the runbook's crash. +fn kill_container(module: &str) { + let name = containers(module, false) + .pop() + .unwrap_or_else(|| panic!("no running container for {module}")); + let status = Command::new("docker").args(["kill", &name]).status().unwrap(); + assert!(status.success(), "docker kill {name}"); +} + struct ChildGuard(Child); impl Drop for ChildGuard { @@ -539,10 +721,22 @@ fn run(manifest: &str) { NEXT_SOCKETS.fetch_add(1, Ordering::Relaxed) )); let _sockets = SocketDirectory(sockets.clone()); - let host = serde_json::to_string(&scenario.host) + let mut host = serde_json::to_string(&scenario.host) .unwrap() .replace("${sockets}", sockets.to_str().unwrap()) .replace("${worker_program}", env!("CARGO_BIN_EXE_protrus-worker")); + let _oci = (scenario.host["execution_mode"] == "oci").then(|| { + let modules = scenario + .artifacts + .values() + .map(|spec| spec.module.clone()) + .collect(); + let (values, cleanup) = oci_setup(&directory.0, &sockets, &key, modules); + for (placeholder, value) in values { + host = host.replace(placeholder, &value); + } + cleanup + }); let mut config: Value = serde_json::from_str(&host).unwrap(); let object = config.as_object_mut().expect("host is an object"); object.insert("state_root".into(), json!(directory.0.join("state"))); @@ -622,6 +816,11 @@ fn run(manifest: &str) { } else if let Some(module) = action["kill_worker"].as_str() { kill_worker(&sockets, module); Observed::default() + } else if let Some(module) = action["container"].as_str() { + inspect_container(module) + } else if let Some(module) = action["kill_container"].as_str() { + kill_container(module); + Observed::default() } else if let Some(millis) = action["wait_ms"].as_u64() { thread::sleep(Duration::from_millis(millis)); Observed::default() @@ -745,3 +944,9 @@ fn java_mcp_configuration_scenario() { fn java_mcp_config_reload_scenario() { run("config-reload-mcp.json"); } + +#[test] +#[ignore = "builds the production Linux worker image and runs signed OCI pairs in Docker"] +fn java_mcp_container_scenario() { + run("container-mcp.json"); +} diff --git a/docs/design/05-worker-protocol.md b/docs/design/05-worker-protocol.md index b3db524..0f9d1e2 100644 --- a/docs/design/05-worker-protocol.md +++ b/docs/design/05-worker-protocol.md @@ -123,7 +123,12 @@ drain/stop 전에 `mark_retiring()`을 호출하면 exit를 무시하고, pair c 전달한다. host는 이 callback을 `DeploymentService::reconcile_stored()`에 연결할 수 있지만, OCI crate는 runtime factory나 deployment store를 소유하지 않으므로 직접 container를 재생성하지 않는다. `protrus-host`의 `watch_oci_factory_pair`는 crash를 관측하면 먼저 factory의 exact revision entry와 proxy target을 best-effort로 -reap한 뒤 stored reconciliation을 호출한다. 따라서 stale local runtime entry가 replacement Prepare를 막지 않는다. +reap한 뒤, 그 module 하나만 persisted signed record에서 다시 배포한다 +(`DeploymentService::redeploy_reaped_after_crash`, 그 revision이 아직 ACTIVE일 때만). 따라서 stale local runtime +entry가 replacement Prepare를 막지 않는다. Java container watcher도 종료된 container만 다시 띄운다. +2026-11-05 이전 build는 여기서 `reconcile_stored()` 전체를 호출해, 살아 있는 다른 module의 pair까지 다시 +Prepare하다 `runtime already exists`로 DEGRADED·sticky로 만들고 그 module의 uninstall을 실패시켰다 +(container 시나리오 S7 opt-in에서 발견, `a_reaped_crash_brings_back_only_that_module`). 실행 binary의 scheduler/event-loop wiring은 host application이 소유한다. `OciHttpWorkerRuntime::container()`은 그 launcher가 watcher를 구성할 수 있게 immutable worker+gateway pair identity만 제공하며, OCI engine operation은 노출하지 않는다. Java `worker.container.auto-restart`와 같이 auto-restart flag는 exit가 관측된 순간에 샘플한다. disabled 상태의 diff --git a/docs/design/20-verification-architecture.md b/docs/design/20-verification-architecture.md index fcd362e..ec8f493 100644 --- a/docs/design/20-verification-architecture.md +++ b/docs/design/20-verification-architecture.md @@ -131,6 +131,7 @@ developer command. Shell scripts can wrap the command but do not become the only | runbook | manifest | 결과 | 남은 차이 | | --- | --- | --- | --- | | `SCENARIO-inprocess-mcp.md` | `inprocess-mcp.json` | S1·S2·S4·S5·S8·cleanup 통과 | S1 입력은 query 대신 body(설계 25 §2 non-parity), S3 unit-test gate 미이식(설계 30 P\*) | +| `SCENARIO-container-mcp.md` | `container-mcp.json` | S1·S2(`docker inspect`: read-only rootfs, `CapDrop=[ALL]`, `no-new-privileges`, pids·memory 상한)·S4(gate 거부 시 container 없음)·S5·S6·S7(기본 off: 자가 복구 없음, update로 복구)·S7 opt-in(`worker.container.auto-restart`로 그 module만 새 container, 이웃 module은 그대로)·cleanup(container 제거) 통과 | S3 unit-test gate 미이식(설계 30 P\*). packing(`worker.modules-per-worker`, P\*)이 없어 module마다 worker/gateway pair 하나라 kill은 그 module만 내린다(Java `modules-per-worker=1`과 같다). Docker가 필요해 `#[ignore]`다 | | `SCENARIO-worker-mcp.md` | `worker-mcp.json` | S1·S4·S5·S6·S7(기본 off: 자가 복구 없음, update로 복구, 죽은 worker의 module도 uninstall된다)·S7 opt-in(`worker.auto-restart`를 MCP로 켜면 같은 revision으로 스스로 복구)·cleanup 통과 | S2 isolation 혼재·worker packing은 P\*라 module마다 worker 하나다 | | `SCENARIO-configuration.md` | `configuration-mcp.json` | C3(approval)·C4(request-timeout, key가 live인지와 그 아래 요청 처리)·C5(metrics)·C6(strict-schema)·C7(mcp.session.enabled)·C8(debug gate)·C11(mcp.enabled)·C12·C13·C14(trace)·C33(서명 필수)·C34(protected-resource metadata) 통과 | C4의 timeout 발화는 component에 clock·sleep이 없어 단위 테스트로 대신한다. C1·C2·C9는 test/review gate 미이식, C17–C32는 P\*·JVM 전용·Docker | @@ -139,6 +140,12 @@ developer command. Shell scripts can wrap the command but do not become the only configuration처럼 launch 설정이 다른 항목은 manifest `runs`로 host를 run마다 따로 띄운다(각 run의 `config`가 bootstrap `config`에 더해진다). +container manifest는 runner가 operator처럼 미리 준비한 값을 쓴다: worker·gateway image(`PROTRUS_OCI_WORKER_IMAGE`가 +있으면 그 worker image, 없으면 `poc/worker-container-fixture/Dockerfile.runtime`으로 빌드), `--internal` network, +container 사용자(65532)가 읽는 control secret, host artifact store에 게시한 서명된 gateway profile. `container` step은 +module의 최신 running container를 `docker inspect`하고(없으면 404), `kill_container`는 그것을 `docker kill`한다. +실행: `PROTRUS_OCI_WORKER_IMAGE= cargo test -p protrus-host --test mcp_scenarios java_mcp_container_scenario -- --ignored`. + worker manifest는 `${sockets}`(macOS Unix socket 경로 길이 때문에 `/tmp` 아래 짧은 경로)와 `${worker_program}` (`protrus-worker` 바이너리)를 runner가 채운다. `kill_worker` step은 module의 control socket `-.sock`을 연 `protrus-worker` 프로세스를 `lsof`로 찾아 `kill -9`한다. diff --git a/examples/scenarios/container-mcp.json b/examples/scenarios/container-mcp.json new file mode 100644 index 0000000..54531ce --- /dev/null +++ b/examples/scenarios/container-mcp.json @@ -0,0 +1,141 @@ +{ + "scenario": "container-mcp", + "source": "java_mcp/SCENARIO-container-mcp.md", + "host": { + "execution_mode": "oci", + "control_socket_root": "${sockets}", + "control_secret_file": "${control_secret}", + "worker_image_digest": "${worker_image}", + "gateway_image_digest": "${gateway_image}", + "gateway_profile_artifact_digest": "${gateway_profile}", + "worker_network": "${network}", + "gateway_command": ["node", "/fixture/gateway.js"], + "allowed_capabilities": [], + "pair_watch_interval_ms": 500, + "config": {"mcp.enabled": true} + }, + "operator": {"principal": "scenario-operator", + "why": "The host binary opens reads and requires its configured identity for changes (design 17); Java's default authorizer allows all."}, + "artifacts": { + "wk-calc-1": {"module": "wk-calc", "version": "1", "component": "wk-calc", "revision": 1, + "routes": [{"method": "POST", "path": "/wk/square"}]}, + "wk-calc-2": {"module": "wk-calc", "version": "2", "component": "wk-calc-v2", "revision": 2, + "expected_revision": 1, "routes": [{"method": "POST", "path": "/wk/square"}]}, + "wk-calc-recover": {"module": "wk-calc", "version": "1", "component": "wk-calc", "revision": 4, + "expected_revision": 3, "routes": [{"method": "POST", "path": "/wk/square"}]}, + "ip-echo-1": {"module": "ip-echo", "version": "1", "component": "ip-echo", "revision": 1, + "routes": [{"method": "POST", "path": "/ip/echo"}]}, + "wk-forbidden-1": {"module": "wk-forbidden", "version": "1", "component": "wk-calc", "revision": 1, + "capabilities": ["net"], "routes": [{"method": "POST", "path": "/gf/ping"}]} + }, + "not_applicable": [ + {"id": "S3", "reason": "Java's unit-test gate (gate.tests-enabled) is not ported yet (design 30, P*)."}, + {"id": "S6 packing", "reason": "Containers are not packed (worker.modules-per-worker is P*, design 30): each module has its own worker/gateway pair, so a kill takes down only that module, as Java's modules-per-worker=1."}, + {"id": "S8", "reason": "Transport only; the in-process scenario covers it."} + ], + "steps": [ + {"id": "S1", "note": "deploy wk-calc into a container", + "do": {"mcp": "protean.deploy_module", "deploy": "wk-calc-1"}, + "expect": {"is_error": false, "text_contains": "Module wk-calc deployed (ACTIVE)", + "structured": {"id": "wk-calc", "mode": "container"}}}, + {"id": "S1", "note": "routed through the proxy into the container (Java: GET /wk/square?n=9; no query, design 25 §2)", + "do": {"http": "POST", "path": "/wk/square", "body": "9"}, + "expect": {"status": 200, "body": "square=81"}}, + {"id": "S1", "note": "out-of-process signature: a container runtime holds wk-calc", + "do": {"mcp": "protean.list_runtimes", "arguments": {}}, + "expect": {"is_error": false, "structured": {"runtimes": [{"mode": "container", "moduleIds": ["wk-calc"]}]}}}, + {"id": "S1", "note": "docker ps shows a container for the module", + "do": {"container": "wk-calc"}, + "expect": {"status": 200, "json": {"State": {"Running": true}}}}, + + {"id": "S2", "note": "the OS sandbox: read-only rootfs, all capabilities dropped, no-new-privileges, pids and memory caps", + "do": {"container": "wk-calc"}, + "expect": {"status": 200, "json": {"HostConfig": {"ReadonlyRootfs": true, "CapDrop": ["ALL"], + "SecurityOpt": ["no-new-privileges"], + "PidsLimit": 1024, "Memory": 536870912}}}}, + + {"id": "S4", "note": "forbidden capability fails closed before any container starts (Java: forbidden-API gate)", + "do": {"mcp": "protean.deploy_module", "deploy": "wk-forbidden-1"}, + "expect": {"is_error": true, + "text_contains": "[GATE_FAILED] promotion gate policy failed: capability net is not allowed", + "problem": {"code": "GATE_FAILED", "gate": "policy"}}}, + {"id": "S4", "do": {"http": "POST", "path": "/gf/ping", "body": ""}, + "expect": {"status": 404}}, + {"id": "S4", "note": "no container was started for it", + "do": {"container": "wk-forbidden"}, + "expect": {"status": 404}}, + + {"id": "S5", "note": "update to v2: a fresh container, then the route is repointed", + "do": {"mcp": "protean.update_module", "deploy": "wk-calc-2"}, + "expect": {"is_error": false, "text_contains": "Module wk-calc updated (v2)", + "structured": {"id": "wk-calc", "version": "2", "mode": "container"}}}, + {"id": "S5", "do": {"http": "POST", "path": "/wk/square", "body": "9"}, + "expect": {"status": 200, "body": "square=81 v2"}}, + {"id": "S5", "note": "history, newest first", + "do": {"mcp": "protean.module_versions", "arguments": {"id": "wk-calc"}}, + "expect": {"is_error": false, "structured": {"versions": [{"version": "2"}, {"version": "1"}]}}}, + {"id": "S5", "note": "rollback to version 1", + "do": {"mcp": "protean.rollback_module", "arguments": {"id": "wk-calc", "version": "1"}}, + "expect": {"is_error": false, "text_contains": "Module wk-calc rolled back"}}, + {"id": "S5", "do": {"http": "POST", "path": "/wk/square", "body": "9"}, + "expect": {"status": 200, "body": "square=81"}}, + + {"id": "S6", "note": "a second container module", + "do": {"mcp": "protean.deploy_module", "deploy": "ip-echo-1"}, + "expect": {"is_error": false, "structured": {"id": "ip-echo", "mode": "container"}}}, + {"id": "S6", "do": {"http": "POST", "path": "/ip/echo", "body": "hello"}, + "expect": {"status": 200, "body": "echo=hello"}}, + {"id": "S6", "note": "docker kill wk-calc's container", + "do": {"kill_container": "wk-calc"}, + "expect": {}}, + {"id": "S6", "note": "main survives", + "do": {"mcp": "protean.list_modules", "arguments": {}}, + "expect": {"is_error": false}}, + {"id": "S6", "note": "a module in another container survives", + "do": {"http": "POST", "path": "/ip/echo", "body": "hello"}, + "expect": {"status": 200, "body": "echo=hello"}}, + {"id": "S6", "note": "the victim is down (Java: 502)", + "do": {"http": "POST", "path": "/wk/square", "body": "9"}, + "expect": {"status": 502}}, + + {"id": "S7", "note": "worker.container.auto-restart off (default): no self-heal", + "do": {"wait_ms": 3000}, + "expect": {}}, + {"id": "S7", "do": {"http": "POST", "path": "/wk/square", "body": "9"}, + "expect": {"status": 502}}, + {"id": "S7", "note": "recover the victim with an update: a fresh container serves it (rollback made revision 3, design 17)", + "do": {"mcp": "protean.update_module", "deploy": "wk-calc-recover"}, + "expect": {"is_error": false, "structured": {"id": "wk-calc", "mode": "container"}}}, + {"id": "S7", "do": {"http": "POST", "path": "/wk/square", "body": "9"}, + "expect": {"status": 200, "body": "square=81"}}, + + {"id": "S7 opt-in", "note": "turn worker.container.auto-restart on at runtime (LIVE)", + "do": {"mcp": "config.set", "arguments": {"changes": {"worker.container.auto-restart": true}}}, + "expect": {"is_error": false}}, + {"id": "S7 opt-in", "note": "docker kill wk-calc's container again", + "do": {"kill_container": "wk-calc"}, + "expect": {}}, + {"id": "S7 opt-in", "note": "the module comes back on its own in a fresh container", + "do": {"http": "POST", "path": "/wk/square", "body": "9"}, "until_ms": 60000, + "expect": {"status": 200, "body": "square=81"}}, + {"id": "S7 opt-in", "note": "only the crashed module is restarted: the other container keeps serving untouched", + "do": {"http": "POST", "path": "/ip/echo", "body": "hello"}, + "expect": {"status": 200, "body": "echo=hello"}}, + {"id": "S7 opt-in", "do": {"mcp": "protean.get_module", "arguments": {"id": "ip-echo"}}, + "expect": {"is_error": false, "structured": {"observedState": "active", "stickyReason": null}}}, + {"id": "S7 opt-in", "do": {"mcp": "config.set", "arguments": {"changes": {"worker.container.auto-restart": false}}}, + "expect": {"is_error": false}}, + + {"id": "Cleanup", "do": {"mcp": "protean.uninstall_module", "arguments": {"id": "ip-echo"}}, + "expect": {"is_error": false}}, + {"id": "Cleanup", "do": {"mcp": "protean.uninstall_module", "arguments": {"id": "wk-calc"}}, + "expect": {"is_error": false}}, + {"id": "Cleanup", "do": {"mcp": "protean.list_modules", "arguments": {}}, + "expect": {"is_error": false, "module_ids_exclude": ["wk-calc", "ip-echo"]}}, + {"id": "Cleanup", "note": "docker ps: the module containers are gone", + "do": {"container": "wk-calc"}, "until_ms": 10000, + "expect": {"status": 404}}, + {"id": "Cleanup", "do": {"container": "ip-echo"}, "until_ms": 10000, + "expect": {"status": 404}} + ] +}