Repository navigation
fix(docker): re-adopt live sandboxes across gateway restarts via supervisor generation handover - #42
Conversation
…rvisor generation handover An ungraceful gateway exit leaves the Docker sandbox running; the next gateway start replaces the supervisor sidecar. The replacement could never re-attach, so the boundary's recovery deadline expired and the workload was terminated. Layered causes, fixed in order: - Boundary registry pinned the first SupervisorInstanceId, so any replacement process got WrongSupervisorInstance. The Docker driver now persists a per-sandbox supervisor generation bound to the sandbox id and auth epoch; the boundary fences generation N (active and pending connections) before staging N+1, rejects stale generations, mismatched bindings and fenced connections, and logs both generations and the cause. - The replacement supervisor generated an ephemeral proxy CA, so the start_agent replay mismatched. The driver now provisions a durable proxy CA in driver state and hands it to every supervisor. - A SIGKILLed single-replica gateway left fresh supervisor owner records; startup now releases them (sqlite / single replica only). - Startup re-attach is bounded (3 min) and fails as recoverable Error/ReattachTimedOut instead of hanging the startup sweep. - The OCSF shorthand layer dropped all non-message fields, hiding causes such as `error`; it now renders them as key=value. Adds a repeated SIGKILL-restart Docker E2E (3 restarts) and makes the e2e harness give CLI children and the restarted gateway a null stdin: the OpenSSH client under `sandbox create` set O_NONBLOCK on the inherited stdin, which made a later `sandbox exec` fail with EAGAIN. Refs aegis-r6ljc Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
[hugo] REQUEST_CHANGES on Blocking:
Smallest safe fix: leave the generic fallback message-only and render the required D1 lifecycle fields through a dedicated safe event/message, or allow-list only the D1 fields ( Accepted at this head:
Local focused receipts (exit 0):
PR is OPEN/CLEAN/MERGEABLE; GitHub reports no check runs. Pre-change retained sandboxes, multi-replica handover, and supervisor-volume loss remain explicit follow-up/release gates; do not describe the 180s startup sweep as replacing the boundary's separate 30s authenticated reconnect window. |
raghusubramanyam
left a comment
There was a problem hiding this comment.
[vega]
Conformance: CONDITIONAL PASS (source + host suites)
Head SHA: ad6391b279597238d61fa292830b06728df5c68d | Objective / Bar: First working copy / integration candidate (D1 aegis-r6ljc + OpenShell half of Connect S5 + D4 log-sink fix + D5 L1; exact-head H5 integrated run remains the runtime qualification gate)
Findings:
- Required now: none.
- Generation-handover state machine (
crates/openshell-sandbox-backend/src/sandbox_auth.rs:245-355,boundary_protocol.rs:273-319): all validation runs before state mutation so rejected attaches never fence the current supervisor; higher generation fences both active and pending connections (FencedSupervisorGeneration) before stagingN+1; stale (StaleSupervisorGeneration), missing (MissingSupervisorGeneration), mismatched sandbox/epoch/zero (SupervisorGenerationMismatch), and same-generation impostor (WrongSupervisorInstance) all fail closed. - Boundary server (
crates/openshell-sandbox/src/boundary_server.rs:1730-1890):commit_attach_generationfreezes the workload (begin_supervisor_recovery) and closes the fenced connection before acceptingN+1;transport_disconnectedof the fenced connection does not trigger a duplicate recovery;start_agentreplay mismatches log field names only (never values) underCK_start_agent_replay_rejected; handover accepts/rejects emitCK_supervisor_handover_accepted/CK_supervisor_attach_rejectedwith both generations and redacted cause. - Structured log sink (
crates/openshell-ocsf/src/tracing_layers/shorthand_layer.rs:95-157):MessageVisitornow preserves non-message fields askey=valuesoerror/cause/generations reachdocker logs. - Docker driver (
crates/openshell-driver-docker/src/lib.rs:2199-2207, 4669-4857):FinishStartRAII drop guard prevents lifecycle-fence deadlock when gateway startup timeout cancelsstart_sandbox;advance_docker_supervisor_generationpersistssupervisor-generation.jsonatomically before updatingruntime-descriptor.json;ensure_docker_proxy_capersistsproxy-ca.keybeforeproxy-ca.crt(cert without key fails closed) and mounts both0600into the supervisor bundle. - Gateway server (
crates/openshell-server/src/lib.rs:886-899,supervisor_owner.rs:216-249,compute/mod.rs:2944-3095): single-replica startup releases stale owner records via compare-and-delete before binding the listener (strictly gated onstore.is_single_replica(), which returnstrueonly forStore::Sqlite); startup re-attach is bounded bySTARTUP_REATTACH_TIMEOUT(180 s) ->Errorwith typed reasonReattachTimedOut+CK_sandbox_startup_reattach_failed. - E2E integrity (
e2e/rust/tests/docker_gateway_restart_readopt.rs): exercises realdocker, realManagedGateway::kill(SIGKILL) /start, realopenshellCLI, real/run/openshell/health.sockprobe, S5 AT-S9 (StartedAt+RestartCountunchanged), pre/post-restartsandbox exec, and rawdocker logshandover proof (1->2->3->4); no production boundaries stubbed or mocked.
- Generation-handover state machine (
- Track next: [Enhancement]
crates/openshell-driver-docker/src/lib.rs:4698-4765—advance_docker_supervisor_generation_indocuments that a missing counter for an existing record fails closed, but currently treatssupervisor-generation.jsonNotFoundasgeneration: 1without first checking whetherruntime-descriptor.jsonalready hassupervisor_generation: Some(_). The boundary still rejectsgeneration: 1, so fencing is not bypassed, but readingruntime-descriptor.jsonfirst and refusingNotFoundwhenruntime_descriptor.supervisor_generation.is_some()makes the driver itself fail closed immediately. Suggest tracking bead. - Track next: [Enhancement]
crates/openshell-sandbox/src/boundary_server.rs:1330-1365—redact_causesplits only on' 'and checksword.starts_with("eyJ"); splitting on whitespace and redacting inlineeyJ...substrings (e.g.token=eyJ...) hardens against formatted error strings. Also, validatingsupervisor_generationbeforedispatch(Request::Attach)(boundary_server.rs:1280-1297) prevents a malformed first-ever attach inAwaitingAttachfrom transitioningAwaitingAttach -> Bound(handover on existingBound/Ready/Runningsandboxes is already read-only inself.attach). - Track next: [Enhancement]
crates/openshell-driver-docker/src/lib.rs:4044-4057, 4842-4857—write_docker_boundary_filecreates temp files under process umask beforeset_file_owner_only(pre-existing pattern inside the0700state dir); creating with0o600+sync_allbefore rename further hardensproxy-ca.keypersistence. - Track next: [Enhancement] Known limits documented in PR body (suggest tracking beads where not already tracked): multi-replica owner handover, investigating the 3 transient Linux
boundary_execfailures from the earlier uid-1000 run, and supervisor-volume disappearance root cause.
Ownership/reuse:
- Supervisor generation handover, durable proxy CA, single-replica owner release, bounded startup re-attach, and OCSF shorthand field logging ->
OpenShell(@ad6391b2, baselightforge-main5d1f63e0) ->extendexistingSandboxConnectionRegistry,BoundaryRuntime,DockerComputeDriver,SupervisorOwnerIndex,ComputeRuntime, andOcsfShorthandLayer. Landscape scan 24h: no overlapping OpenShell PRs; coordinates with Connect S5 andaegis-ie3nn.18/W3 (stale_runtime_identitystays in Connect).
Validation:
- Independently verified at exact head
ad6391b2:git diff --check origin/lightforge-main...HEAD: cleancargo fmt --all -- --check: cleancargo test -p openshell-sandbox-backend --lib: 58 passed, 0 failed (all 7 new interleaving/fencing tests)cargo test -p openshell-driver-docker --lib: 124 passed, 0 failed, 1 ignored (all 3 new generation/CA tests)cargo test -p openshell-ocsf --lib: 163 passed, 0 failed (test_non_ocsf_fallback_includes_structured_fieldspassed)cargo test -p openshell-server --lib -- startup_reattach_that_never_completes_fails_with_typed_reason single_replica_restart_releases_owner_of_exited_gateway: 2 passed, 0 failed
- Author receipts reviewed (not independently re-executed in this review): Linux
openshell-sandboxsuite (223 passed, 5x), fullopenshell-server(1785 passed), sibling drivers (podman/k8s/vm), clippy-D warnings, anddocker_gateway_restart_readopt3-SIGKILL-restart Docker E2E (1->2->3->4). - CI status: no GitHub Actions check runs reported on
ad6391b2(unknown/none configured). - Runtime gate: exact integration-head WP-6 H5 run (Connect desktop + OpenShell closure + Shell + Phoenix + global-e2e) remains the end-to-end qualification gate.
Blast radius:
- Protocol (
SandboxRuntimeDescriptor,Request::Attachwith backwards-compatible#[serde(default)]supervisor_generation: Option<SupervisorGeneration>), auth registry, Linux boundary server, Docker driver + sibling driver struct initializers (kubernetes/podman/vmsetNone), server startup & owner index, OCSF shorthand layer, and Rust E2E harness (openshell_cmd+ManagedGatewaynull stdin).
Simplification:
- none (clean, well-scoped fixes directly addressing each of the 4 layered root causes without speculative multi-replica or live-credential-reload machinery).
Hugo review on #42 (issuecomment-7188173452): the non-OCSF fallback rendered every structured field, and existing call sites record values that are not secret-free (supervisor `command = ?command` carries the full command vector). Fields are now opt-in: only the supervisor-lifecycle diagnostics (code, phase, sandbox_id, runtime/supervisor generations, fenced_active, auth_epoch, cause, reason, released) render. Values have control characters replaced and are bounded at 512 bytes, so an event stays one line. Negative tests cover a command vector with a bearer token, token and error fields, newline/CR injection, and the length bound. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Fixed at The non-OCSF fallback in
Any other field is dropped. That covers the existing supervisor New negative tests
The restart E2E asserts
agy Vega's non-blocking track-next items (review 6071652978) are recorded for a follow-up:
|
|
The 3-SIGKILL restart E2E at |
|
[hugo] Conformance: PASS Findings:
Validation:
Ownership/reuse and blast radius are unchanged from the prior exact-head review; this delta only narrows the existing OCSF shorthand sink. Simplification: none; the explicit allow-list is the smallest safe correction and avoids a second logging path. |
raghusubramanyam
left a comment
There was a problem hiding this comment.
[vega]
Conformance: CONDITIONAL PASS (source + host suites)
Head SHA: 6efaf2943e7218850b49d8fab24a00fef66c4ef6 | Objective / Bar: First working copy / integration candidate (D1 aegis-r6ljc + OpenShell half of Connect S5 + D4 log-sink fix + D5 L1; exact-head H5 integrated run remains the runtime qualification gate)
Findings:
- Required now: none.
- Hugo's blocking log-disclosure finding (
issuecomment-7188173452onad6391b2) is cleanly resolved incrates/openshell-ocsf/src/tracing_layers/shorthand_layer.rs:134-187:OcsfShorthandLayernon-OCSF fallback is now strictly opt-in viaFALLBACK_FIELD_ALLOW_LIST(code,phase,sandbox_id,runtime_generation,supervisor_generation,previous_supervisor_generation,current_supervisor_generation,requested_supervisor_generation,fenced_active,auth_epoch,cause,reason,released).- Non-allowlisted fields (including
command,token,error) are dropped before formatting (push_fieldreturns immediately). - Allow-listed values have control characters (
\n,\r, etc.) flattened to spaces and are truncated at a UTF-8 char boundary to 512 bytes (MAX_FALLBACK_FIELD_BYTES), preventing log-line forgery and unbounded lines. - Verified by 3 unit tests covering allow-listed lifecycle fields, secret-bearing
command/token/errorrejection, and newline/CR forgery + 512 B truncation.
- Delta
ad6391b2..6efaf294touches onlyshorthand_layer.rs; prior source/interleaving verification from review6071652978holds unchanged.
- Hugo's blocking log-disclosure finding (
- Track next: [Enhancement] Prior non-blocking follow-ups from review
6071652978remain recorded for follow-up (driver-side missing-counter check againstruntime-descriptor.json,redact_causewhitespace/inline-JWT hardening, pre-dispatch generation validation inAwaitingAttach,0o600+sync_alltemp write forproxy-ca.key, and PR-documented known limits).
Ownership/reuse:
- Unchanged from review
6071652978(OpenShell@6efaf294->extendOcsfShorthandLayer+ existing handover/driver/server components).
Validation:
- Independently verified at exact head
6efaf294:git diff --check origin/lightforge-main...HEAD: clean (1-file deltaad6391b2..6efaf294)cargo fmt --all -- --check: cleancargo test -p openshell-ocsf --lib: 165 passed, 0 failedcargo clippy -p openshell-ocsf --all-targets -- -D warnings: clean
- Author receipts reviewed (not independently re-executed in this pass): rebuilt 3-SIGKILL restart E2E at
6efaf294(local/readopt/*:allowlist) 1 passed (E2E_EXIT=0),docker logshandover1->2->3->4, nocommand=/token=leaked. - CI status: no GitHub Actions check runs reported on
6efaf294(unknown/none configured). - Runtime gate: exact integration-head WP-6 H5 run remains the end-to-end qualification gate.
Blast radius:
- Scoped exclusively to
OcsfShorthandLayernon-OCSF fallback rendering (shorthand_layer.rs), which narrows disclosure back to an explicit 13-field lifecycle allow-list while keeping all D1/D4 handover diagnostics intact.
Simplification:
- none.
WP-6 H6 live runtime receipt: run
|
| Repo | Pin |
|---|---|
Connect integration integration/wp6-agy-h6b2 |
64fa3f38 = ai-openshell#472 a57e3609 + ai-openshell#474 52f1ebb2 + ai-openshell#461 af0133d4 |
OpenShell closure integration/wp6-agy-h6 |
e2e20ace = #42 6efaf294 + #43 f72b22d8 + #44 64fc5dcf. Images: gateway f31ba45a, sandbox 720f7bbd, supervisor 63dd0bd0 |
| Shell | b08afb13 |
| Phoenix | e89345f7 |
| global-e2e control | dcee6fe1 |
| SDK linux-arm64 | 09de4309 (sha256 520f4a9a…) |
The SDK differs from attempts 2 and 3, which used 2642ce34. That binary predates SDK ai-openshell#160 --lane, while Shell D-070 calls session-start --lane connect. h6c is kept as the record of that pin skew.
Diagnostics on: AEGIS_CONNECT_GATEWAY_DIAGNOSTIC_LOG=1, OPENSHELL_LOG_LEVEL=debug. Run with native-run/run-native-gates.sh --diag --restarts 3 (aegis-api-phoenix#3900).
| Gate | Result |
|---|---|
| 1 inputs | passed: pins equal the checkouts, artifact SHA-256 values match, 0 FIFO wrappers, umask 022 |
| accept | passed: runtime-setup, bootstrap, first-session, restart-session; mind smoke post-enroll and post-restart |
| D1 restart re-adoption, 3 restarts | passed: same sandbox container 53f47c46 and StartedAt 21:00:04.395Z across all restarts; supervisor generation 2→3→4→5, advancing by exactly one each time; a distinct healthy sidecar per restart; Ready, and exec rc=0 after each restart |
| D1b shutdown disposition | CK_gateway_shutdown_disposition_selected mode=retain-running-sandboxes reason=runtime_restart on all 5 Gateway stops (preflight, accept and 3 proof restarts); no sweep |
| ai-openshell#471 | passed: first_session_passed, no sandbox_session_not_registered, no policy-generation stale close |
| ai-openshell#474 diagnostic log | home/logs/gateway.log plus 3 rotations, each ≤1.05 MB (bounded), mode 0600; 4 [redacted] substitutions; 0 hits from a credential-pattern scan (Authorization/Cookie/Bearer/token/secret/password, JWT, sk-, ghp_, PEM); no CK_gateway_output_log_unavailable; readiness unchanged |
| 5 down | down result=verified, rc=0; no namespace containers or volumes left; custody-unproven agent/identity volumes kept (ai-openshell#85); 0 lingering wrappers |
Receipts are private (0600) on the build host under out/wp6-agy-20261127h6d/ (inputs.txt, accept.log, restart/restart-proof-receipt.json, 471-receipt.json, postdown-receipt.txt, restart/gateway.log*).
|
[hugo] Conformance: PASS The previously deferred D1 runtime gate is closed by WP-6 H6d No required finding remains. GitHub reports no CI/check runs; the exact-head local suites from the source review plus the production-boundary H6d receipt satisfy this PR's evidence bar. Merge sequencing: merge #42 first as a merge commit into Comment-only review: no approval, merge, or label change performed. |
Summary
If the gateway dies without a graceful shutdown (SIGKILL, host process crash), the Docker sandbox container keeps running. At the next start the gateway replaces the supervisor sidecar (
start_sandbox_with_lifecycle_fence->ensure_control_process_for_container->spawn_docker_control_process). Before this change, the replacement supervisor could never re-attach to the running boundary. The boundary's 30 s recovery deadline then expired, and it terminated the workload ("sandbox session is terminal").This PR implements the approved supervisor generation handover. With it, the gateway re-adopts a sandbox across repeated ungraceful restarts: the sandbox id and container stay the same, the workload is not restarted, and
sandbox execkeeps working.Refs aegis-r6ljc; OpenShell half of Connect S5 (re-attach on start). Evidence: lightforgedev/aegis-connect-phoenix#470 (closed as duplicate of r6ljc).
Root cause (layered; each fixed blocker exposed the next)
Base references are at
5d1f63e0.crates/openshell-sandbox-backend/src/sandbox_auth.rs:182-187(SandboxConnectionRegistry::attach) stores the firstSupervisorInstanceId. That id is random per process (crates/openshell-sandbox-backend/src/runtime.rs:1092). Every replacement sidecar was rejected withWrongSupervisorInstance("sandbox runtime is already bound to another supervisor process",sandbox_auth.rs:342). The client retried every 25 ms (ATTACH_REQUEST_TIMEOUT,runtime.rs:50) until the boundary recovery deadline expired (crates/openshell-sandbox/src/boundary_server.rs:1773).crates/openshell-supervisor-network/src/host.rs:119, "ephemeral CA generated"). The replacement'sstart_agentreplay was therefore rejected: "start_agent inputs do not match the running boundary" (boundary_server.rs:2422).OWNER_TTL45 s,crates/openshell-server/src/supervisor_owner.rs:15;can_supersedeat:258).ConnectSupervisorreturned Unavailable "supervisor session owned by another gateway replica" (supervisor_session.rs:947), and the supervisor exited.crates/openshell-ocsf/src/tracing_layers/shorthand_layer.rs:124-136(MessageVisitor) dropped every field exceptmessage. Theerrorfield of "Boundary gRPC exchange failed" therefore never reacheddocker logs.The stop sweep is not involved: the repro uses SIGKILL, and the container keeps running.
Generation-handover contract
{sandbox_id, auth_epoch, generation}for every supervisor process it starts. It persists the counter atomically insupervisor-generation.jsonand records it in the runtime descriptor. A corrupt counter, or one belonging to another sandbox, fails closed.crates/openshell-driver-docker/src/lib.rs:4669advance_docker_supervisor_generation, called at:5128SupervisorGenerationis defined atcrates/openshell-sandbox-backend/src/boundary_protocol.rs:273SandboxConnectionRegistry::attach_supervisor,sandbox_auth.rs:245). All checks run before any state changes, so a rejected attach never fences the current supervisor.SupervisorGenerationMismatch.StaleSupervisorGeneration.WrongSupervisorInstance).FencedSupervisorGeneration {fenced, current}.MissingSupervisorGeneration.commit_attach_generationis atboundary_server.rs:1730. If it fences the active connection, the boundary enters normal recovery (begin_supervisor_recovery,:1877): the workload freezes until N+1 confirms. The boundary logsCK_supervisor_handover_acceptedorCK_supervisor_attach_rejectedwith the phase, sandbox id, runtime generation, previous and new supervisor generations, and the redacted cause.ensure_docker_proxy_ca,lib.rs:4781; key written before certificate). It stages the CA into the supervisor volume and passes it viaOPENSHELL_PROXY_CA_CERT/_KEY, so every generation replays identicalstart_agentinputs.supervisor_owner.rs:211, called atcrates/openshell-server/src/lib.rs:890). It does this only when the store is single-replica.Re-attach deadline and
ReattachTimedOutRe-attaching each retained sandbox during the startup sweep is bounded by
STARTUP_REATTACH_TIMEOUT= 3 min (180 s) (crates/openshell-server/src/compute/mod.rs:4742). On expiry:ReattachTimedOut(:4744);CK_sandbox_startup_reattach_failed(phase=gateway_startup,reason);The Docker start fence is released by a drop guard, so an abandoned start cannot leave the fence held.
Log-field fix
The shorthand layer now renders non-message fields as
key=valueafter the message, like the default fmt layer (shorthand_layer.rs:131, testtest_non_ocsf_fallback_includes_structured_fields).Proof from collected
docker logsbytes: the E2E reads rawdocker logs <sandbox container>after each restart. It asserts that a handover line exists carryingcode="CK_supervisor_handover_accepted",previous_supervisor_generation=Some(N)andsupervisor_generation=Some(N+1). Lines collected at this head:During diagnosis, the same layer surfaced the cause for blocker 1, which had been hidden. Collected from
docker logswith the field fix but before the handover fix:E2E harness fix (not a product bug)
sandbox execfailed after restart 1 with "Resource temporarily unavailable (os error 35)", which is EAGAIN on macOS. Verified cause:openshell_cmd()let every CLI child inherit the test runner's stdin.sandbox create/connectsetsO_NONBLOCKon that shared open file description. A watcher on the pipe caught the flag flipping whileopenshell sandbox connect->sshwas running.sandbox execreads a non-TTY stdin to EOF, so the read returned EAGAIN.The failure also reproduces before any restart when the runner's stdin is a pipe, and it never reproduces when stdin is
/dev/null. So it is unrelated to re-adoption. The fix is in the harness:openshell_cmd()(e2e/rust/src/harness/binary.rs:55) and the restarted gateway now get a null stdin. With a pipe stdin, the flag no longer flips and the E2E is green.Tests
The deterministic interleaving tests are in
sandbox_auth.rs(registry; host) andboundary_server.rs(Linux).next_generation_fences_confirmed_generation_before_stagingnext_generation_fences_unconfirmed_generation_and_rejects_its_late_confirmfenced_generation_cannot_reattach_or_confirmcurrent_generation_reconnects_only_as_same_processgeneration_must_be_bound_to_sandbox_and_epochrejected_handover_does_not_fence_current_generationgeneration_handover_replaces_legacy_supervisorsupervisor_generation_handover_fences_previous_generationsupervisor_generation_handover_after_transport_losslogged_causes_are_redacted_and_boundedeach_supervisor_spawn_issues_a_strictly_larger_generation,corrupt_or_foreign_supervisor_generation_fails_closed,proxy_ca_is_provisioned_once_and_reusedstartup_reattach_that_never_completes_fails_with_typed_reason, plus the owner release test insupervisor_owner.rsResults at this head, macOS arm64 host plus a Linux arm64 container:
docker_gateway_restart_readopt(--features e2e-docker, 3 SIGKILL restarts)/run/openshell/health.sockprobed; Ready;sandbox execreturns pre-restart state; volumes retained; handover log fields. Also a baseline exec before the restarts, and delete removes the volumes. Green with/dev/nullstdin and with a held-open pipe stdin.openshell-sandboxlib (Linux, as non-rootubuntu)stdout_logging: 1 passed.openshell-sandbox-backendopenshell-driver-dockeropenshell-serveropenshell-ocsfopenshell-driver-podman/-kubernetes/-vmcargo fmt --all -- --check, e2e fmt-D warnings--all-targets(host);openshell-sandboxon aarch64-linux, with and withoutperf-harness;e2e/rust --all-targets; readopt test withe2e-dockerOne earlier Linux full run, as uid 1000 without a passwd entry, had 3 failures: two
boundary_execprocess-group tests andcanonical_exit_preserves_pending_network_accept_and_exec. They passed in isolation and in 5 later full runs. I did not investigate this further; it looks like pre-existing timing sensitivity.Known limits
start_agentreplay. The fix applies to new sandboxes.OWNER_TTL, and a replacement can still time out asReattachTimedOut.🤖 Generated with Claude Code