You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix: isolate agent process cleanup by session ownership - #2606
Stopping or restarting one agent session previously ran container-wide command-pattern pkill, which could kill same-type peers sharing its workspace container. Every launch now has a unique ownership marker and captured root PID/starttime. When supported, a private Linux session and supervisor also retain ownership of env-cleared orphans. Minimal images without setsid --wait still start using marker and ancestry ownership. Cleanup checks PID starttime before signals and surviving children after Docker client exit.
Coordinator approved PR #2606 at exact head a554048af0bed6e910efc3268761dbd101132dae on 2026-11-09 (SAM event 90be1871-159b-4b60-a965-92f736eda3ce) and marked it ready. Approval permits hold-label removal, refreshing the frozen evidence check, and squash merge of that exact head after checking late CodeRabbit findings and production deployment contention. Any new code commit requires re-approval. Third PR in chain after #2595 and #2601 verified production. No production resource mutations. Task archive notes follow in a separate draft PR. Coordinator accepted process.go at 717 lines (703 on main) because container logic moved into process_container.go.
Validation
Full ACP suite with race detection passed 49.083s, 83.1% coverage at a554048af0bed6e910efc3268761dbd101132dae; Go vet passed.
Missing setsid, unsupported --wait, missing grep/tr and combined missing-tool real launch/Stop/replacement controls preserve peer responses and clean owned children.
Removing the setsid fallback makes both required launch controls fail. Reverting batch-identity and transient-cache fixes makes deterministic replacement and recovery controls fail; restored code passes.
All three local reviewers confirm the final helper-extraction commit preserves behavior and assertions.
All final-head technical CI and E2E pass: CI42605803027 attempt2, E2E42605803047. The single VM Agent Test rerun passed (job129129654314) after an untouched reporter timing-sensitive test failed on attempt1; follow-up idea01M7002939CVCF8EKZ8D69YMAC tracks it. Only the mandatory needs-human-review hold-related evidence check remains failed.
Detailed static analysis
The previous Sonar gate passed but its detailed report included parser/test-fixture complexity findings. Commit a554048af0bed6e910efc3268761dbd101132dae extracts the unchanged marker join and fixture/assertion helpers. Final Sonar analysis passes with zero new issues; no logic or shell-script changes in this commit.
Staging Verification (REQUIRED for all code changes — merge-blocking)
Final-head staging deployment green
Live app verified via Playwright
Coordinator-revised live acceptance: real Stop closes owner runtime; existing peer and replacement return replies without peer recovery. Orphan/TERM-resistant child cleanup proven by local real-process and mutation controls.
First attempt provisioned one fresh node, confirmed exact VM-agent version/heartbeat, then deleted it and independently verified D1 cleanup
Staging Verification Evidence
Final revised run PASS at unchanged a554048af0bed6e910efc3268761dbd101132dae, reusing successful deployment42685635571. Coordinator explicitly accepted the split: live Stop/peer/replacement replies; local real-process/mutation controls for orphan, env-cleared and TERM-resistant children.
Fresh small node 01M70YK4S42HT7EBJM0DN90QH5 reported the exact candidate and heartbeat20:08:45UTC; workspace 01M70YK52QJQVBM6VS4JJTVYHK reached running. Two Claude sessions reached ready. Real API StopA plus observed owner runtime WebSocket closure20:09:45; existing peerB replied20:09:56; replacementA replied20:10:21; same peerB replied again20:10:24. Full post-ready message history rejects restart/recovery/crash/socket closure, preventing an automatic-recovery false pass. Filtered node logs contained one stop entry; logs support the result and do not independently prove ownership scope. No raw logs persisted. Playwright loaded dashboard/projects/settings: allHTTP200, zero page errors.
NodeDELETE200 at20:10:41UTC. Independent D1 at20:11:07UTC confirmed own node and workspace absent and zero active staging nodes. Slot released to coordinator. Total fixture lifetime~6minutes, within29-minute hard limit. Harness and sanitized evidence persisted under library /task-evidence/session-cleanup/ (bug3-live-v3.cjs, pr2606-live-state-v3.json, pr2606-v3-node-d1.json, pr2606-v3-cleanup-d1.json).
The following records preserve earlier unsuccessful fixture attempts:
Final-head deployment 42685635571 passed including smoke tests at a554048af0bed6e910efc3268761dbd101132dae. Cloudflare Worker version ef35ee74-2f46-4e20-9e7a-34a1c5b60684 served that commit at 100%. Fresh small node 01M70XX5T7KNCV8PGK7HTE02GD reported the exact candidate and heartbeat at 19:55:40 UTC; workspace 01M70XX6318CQM1629EH28JKHT reached running. Both same-type Claude sessions reached ready.
Earlier attempt did not prove acceptance: the harness timed out waiting for the child-PID terminal assertion before any Stop/replacement checks ran. This does not establish peer survival or cleanup correctness. Node deletion returned HTTP 200 at 19:58:26 UTC; independent D1 at 19:59:17 UTC confirmed the node absent, workspace deleted, and zero active staging nodes. Released staging to the coordinator; no automatic retry. Investigating harness observability before requesting another slot.
First deployment 42601667824 passed at a8ed52ea5a2f13a58f71a7db7e9f6b0ed31713b7. Cloudflare Worker served that commit at 100% (version ff0a58da-211d-4409-b396-efae52546c01). Fresh node 01M6ZZ7WTT8PH9RKW41BX1P33N reported the same agent version and heartbeat at 10:59:34.827 UTC.
The fixture's four-minute workspace-ready deadline expired before devcontainer setup completed. No two-session acceptance assertions ran. Its finally block deleted the node (HTTP200 at11:00:53); independent D1 at11:01:52 confirmed node and workspace absent and zero active staging nodes. Slot released to coordinator; no automatic retry.
Coordinator re-queued this task after eviction and phase2, around12:00UTC or later, and directed a new deployment/test on final head. The corrected fixture polls actual workspace status for up to12minutes across bounded prepare/readiness commands, then verifies the same workspace in a bounded command with explicit node deletion in finally. Each managed command reserves cleanup time. Planned resources remain0.2vCPU/0.5GBRAM/5GB disk, two claude-code sessions. Wait for a new slot grant before any deployment/provisioning. No UI source changes; visual audit N/A.
End-to-End Verification
Data Flow Trace
DockerExecLauncher.Start → startDockerExecProcess → cached capability probe → per-launch marker + optional setsid --wait sh → readiness handshake records root PID/starttime and optional SID before adapter exec → AgentProcess.Stop → /proc metadata/ownership snapshot → ancestry and kernel-session selection → TERM/KILL guarded by PID starttime. Tests enter through real StartProcess/Stop with a Docker transport shim executing actual processes and production scripts against live /proc. The shim refuses legacy pkill so a regression fails without killing this agent.
Cleanup latency and outer-limit throughput
A snapshot now uses one batched grep -Fxlz plus shell builtin stat reads, replacing ~4,000 tr/grep forks per phase at 2,000 processes. The real capture entry point scanned 2,001 synthetic Linux process records plus ~8 MiB of environments in 0.819s (~2,443 processes/s), below the default 3s per-command deadline. This avoids spawning 2,001 host processes under the test host PID quota. Three captures imply ~2.46s at that measured throughput, with no scheduled retry. The conservative default Stop ceiling is 25s (3 snapshots × 3s + 2 signal commands × 3s + 10s host wait; phases overlap). Startup adds up to a 3s cached probe and 3s readiness wait. Slow scans time out visibly without broadening ownership. NUL-safe grep is optional; tr is unused.
Untested Gaps
Coordinator-revised real Docker/staging two-agent acceptance passed as described above. Live orphan/TERM-resistant child cases use the accepted local real-process/mutation evidence split. Without setsid, an env-cleared orphan whose ancestry was already lost before capture is outside the fallback fence. Missing grep retains root/ancestry and any proven SID; missing /proc launches directly and reports unavailable cleanup ownership. Local tests cover same-type peer response after stop/restart, TERM-resistant child clearing its env, marked orphan after exec, combined env-cleared orphan before Stop, profile-marker collision and stale PID exclusion. Deliberate children that both clear ownership metadata and create another Linux session before any capture are outside the detectable ownership fence; this is cleanup correctness within one user's VM, not an adversarial sandbox boundary.
Post-Mortem
What broke
Stopping one session could terminate peers of the same agent type in the workspace container.
Root cause
Cleanup matched adapter/release command names without session identity. Host docker-client exit was also mistaken for container-tree exit.
Class of bug
Resource cleanup scoped by implementation type instead of resource ownership.
Why it wasn't caught
Pattern tests validated which argv matched without exercising two live same-type sessions sharing a container.
Process fix included in this PR
Replace obsolete pattern tests with real process lifetime and peer-survival regressions. Review caught and fixed the combined env-cleared/pre-Stop-orphan case through launch-time kernel session ownership. Existing rules cover ownership and real entry-point testing; no duplicate standing guidance added.
Post-mortem file
tasks/active/2026-11-09-session-owned-agent-cleanup.md; archival notes reserved for a separate draft PR.
Specialist Review Evidence (Required for agent-authored PRs)
New compatibility head re-reviewed and findings addressed before merge
Reviewer
Status
Outcome
go-specialist
ADDRESSED
PASS at a554048; exact marker-join loop and test operation order preserved; previous ownership/cache findings fixed
test-engineer + task-completion-validator
ADDRESSED
PASS at a554048; fixture/assertion semantics unchanged, independent replacement test0.028s; staging acceptance still pending
PASS at a554048; no ownership/signaling/configuration behavior change; version evidence not mistaken for acceptance
CodeRabbit Review Evidence (Required for agent-authored PRs)
CodeRabbit requested through trusted workflow
Waited about15minutes and resolved findings or recorded absence
Applied coderabbit-review and dispatched trusted workflow 42690460714, which succeeded. CodeRabbit replied at20:11:09UTC that review was rate limited; no review currently exists. Required wait completed: reconciled at20:27UTC after the accepted fallback resumed this chat, more than15minutes after the request. No CodeRabbit review or inline findings arrived; rate-limit response remains the outcome. No repeated trigger. Draft/coordinator hold preserved.
Exceptions
User requires early draft PR and needs-human-review, exact-head coordinator approval, no direct main commits, separate archival draft PR, coordinated staging slot. Public documentation paragraph only; no UI changes.
ACP Docker launch and Stop/Wait lifecycle; LocalLauncher retains existing behavior. Per-launch identity is internal, not an HTTP/schema/UI change. Snapshot commands run as container root to inspect same-container processes, emit only metadata and never return env values. Per-command timeout configurable with ProcessConfig.ContainerSignalTimeout. Host Docker uses absolute configurable ProcessConfig.DockerExecutable (default/usr/bin/docker) instead of PATH lookup; tests inject their transport explicitly.
Documentation & Specs
Public VM-agent reference explains per-session cleanup. Task contains investigation, acceptance, test evidence and release constraints.
Constitution & Risk Check
Principles X/XI: standard Linux session identity plus existing marker/ancestry; no service, cgroup, persistent PID file, or mandatory new external dependency. Preserve privileged nested containers and user-owned VM boundary.
Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.
Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.
Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Stopping or restarting one agent session previously ran container-wide command-pattern pkill, which could kill same-type peers sharing its workspace container. Every launch now has a unique ownership marker and captured root PID/starttime. When supported, a private Linux session and supervisor also retain ownership of env-cleared orphans. Minimal images without
setsid --waitstill start using marker and ancestry ownership. Cleanup checks PID starttime before signals and surviving children after Docker client exit.Coordinator approved PR #2606 at exact head
a554048af0bed6e910efc3268761dbd101132daeon 2026-11-09 (SAM event90be1871-159b-4b60-a965-92f736eda3ce) and marked it ready. Approval permits hold-label removal, refreshing the frozen evidence check, and squash merge of that exact head after checking late CodeRabbit findings and production deployment contention. Any new code commit requires re-approval. Third PR in chain after #2595 and #2601 verified production. No production resource mutations. Task archive notes follow in a separate draft PR. Coordinator acceptedprocess.goat 717 lines (703 on main) because container logic moved intoprocess_container.go.Validation
a554048af0bed6e910efc3268761dbd101132dae; Go vet passed.Detailed static analysis
The previous Sonar gate passed but its detailed report included parser/test-fixture complexity findings. Commit
a554048af0bed6e910efc3268761dbd101132daeextracts the unchanged marker join and fixture/assertion helpers. Final Sonar analysis passes with zero new issues; no logic or shell-script changes in this commit.Staging Verification (REQUIRED for all code changes — merge-blocking)
Staging Verification Evidence
Final revised run PASS at unchanged
a554048af0bed6e910efc3268761dbd101132dae, reusing successful deployment42685635571. Coordinator explicitly accepted the split: live Stop/peer/replacement replies; local real-process/mutation controls for orphan, env-cleared and TERM-resistant children.Fresh small node
01M70YK4S42HT7EBJM0DN90QH5reported the exact candidate and heartbeat20:08:45UTC; workspace01M70YK52QJQVBM6VS4JJTVYHKreached running. Two Claude sessions reached ready. Real API StopA plus observed owner runtime WebSocket closure20:09:45; existing peerB replied20:09:56; replacementA replied20:10:21; same peerB replied again20:10:24. Full post-ready message history rejects restart/recovery/crash/socket closure, preventing an automatic-recovery false pass. Filtered node logs contained one stop entry; logs support the result and do not independently prove ownership scope. No raw logs persisted. Playwright loaded dashboard/projects/settings: allHTTP200, zero page errors.NodeDELETE200 at20:10:41UTC. Independent D1 at20:11:07UTC confirmed own node and workspace absent and zero active staging nodes. Slot released to coordinator. Total fixture lifetime~6minutes, within29-minute hard limit. Harness and sanitized evidence persisted under library
/task-evidence/session-cleanup/(bug3-live-v3.cjs,pr2606-live-state-v3.json,pr2606-v3-node-d1.json,pr2606-v3-cleanup-d1.json).The following records preserve earlier unsuccessful fixture attempts:
Final-head deployment 42685635571 passed including smoke tests at
a554048af0bed6e910efc3268761dbd101132dae. Cloudflare Worker versionef35ee74-2f46-4e20-9e7a-34a1c5b60684served that commit at 100%. Fresh small node01M70XX5T7KNCV8PGK7HTE02GDreported the exact candidate and heartbeat at 19:55:40 UTC; workspace01M70XX6318CQM1629EH28JKHTreached running. Both same-type Claude sessions reached ready.Earlier attempt did not prove acceptance: the harness timed out waiting for the child-PID terminal assertion before any Stop/replacement checks ran. This does not establish peer survival or cleanup correctness. Node deletion returned HTTP 200 at 19:58:26 UTC; independent D1 at 19:59:17 UTC confirmed the node absent, workspace deleted, and zero active staging nodes. Released staging to the coordinator; no automatic retry. Investigating harness observability before requesting another slot.
First deployment 42601667824 passed at
a8ed52ea5a2f13a58f71a7db7e9f6b0ed31713b7. Cloudflare Worker served that commit at 100% (version ff0a58da-211d-4409-b396-efae52546c01). Fresh node 01M6ZZ7WTT8PH9RKW41BX1P33N reported the same agent version and heartbeat at 10:59:34.827 UTC.The fixture's four-minute workspace-ready deadline expired before devcontainer setup completed. No two-session acceptance assertions ran. Its finally block deleted the node (HTTP200 at11:00:53); independent D1 at11:01:52 confirmed node and workspace absent and zero active staging nodes. Slot released to coordinator; no automatic retry.
Coordinator re-queued this task after eviction and phase2, around12:00UTC or later, and directed a new deployment/test on final head. The corrected fixture polls actual workspace status for up to12minutes across bounded prepare/readiness commands, then verifies the same workspace in a bounded command with explicit node deletion in finally. Each managed command reserves cleanup time. Planned resources remain0.2vCPU/0.5GBRAM/5GB disk, two claude-code sessions. Wait for a new slot grant before any deployment/provisioning. No UI source changes; visual audit N/A.
End-to-End Verification
Data Flow Trace
DockerExecLauncher.Start→startDockerExecProcess→ cached capability probe → per-launch marker + optionalsetsid --wait sh→ readiness handshake records root PID/starttime and optional SID before adapter exec →AgentProcess.Stop→/procmetadata/ownership snapshot → ancestry and kernel-session selection → TERM/KILL guarded by PID starttime. Tests enter through real StartProcess/Stop with a Docker transport shim executing actual processes and production scripts against live /proc. The shim refuses legacy pkill so a regression fails without killing this agent.Cleanup latency and outer-limit throughput
A snapshot now uses one batched
grep -Fxlzplus shell builtin stat reads, replacing ~4,000 tr/grep forks per phase at 2,000 processes. The real capture entry point scanned 2,001 synthetic Linux process records plus ~8 MiB of environments in 0.819s (~2,443 processes/s), below the default 3s per-command deadline. This avoids spawning 2,001 host processes under the test host PID quota. Three captures imply ~2.46s at that measured throughput, with no scheduled retry. The conservative default Stop ceiling is 25s (3 snapshots × 3s + 2 signal commands × 3s + 10s host wait; phases overlap). Startup adds up to a 3s cached probe and 3s readiness wait. Slow scans time out visibly without broadening ownership. NUL-safe grep is optional; tr is unused.Untested Gaps
Coordinator-revised real Docker/staging two-agent acceptance passed as described above. Live orphan/TERM-resistant child cases use the accepted local real-process/mutation evidence split. Without setsid, an env-cleared orphan whose ancestry was already lost before capture is outside the fallback fence. Missing grep retains root/ancestry and any proven SID; missing /proc launches directly and reports unavailable cleanup ownership. Local tests cover same-type peer response after stop/restart, TERM-resistant child clearing its env, marked orphan after exec, combined env-cleared orphan before Stop, profile-marker collision and stale PID exclusion. Deliberate children that both clear ownership metadata and create another Linux session before any capture are outside the detectable ownership fence; this is cleanup correctness within one user's VM, not an adversarial sandbox boundary.
Post-Mortem
What broke
Stopping one session could terminate peers of the same agent type in the workspace container.
Root cause
Cleanup matched adapter/release command names without session identity. Host docker-client exit was also mistaken for container-tree exit.
Class of bug
Resource cleanup scoped by implementation type instead of resource ownership.
Why it wasn't caught
Pattern tests validated which argv matched without exercising two live same-type sessions sharing a container.
Process fix included in this PR
Replace obsolete pattern tests with real process lifetime and peer-survival regressions. Review caught and fixed the combined env-cleared/pre-Stop-orphan case through launch-time kernel session ownership. Existing rules cover ownership and real entry-point testing; no duplicate standing guidance added.
Post-mortem file
tasks/active/2026-11-09-session-owned-agent-cleanup.md; archival notes reserved for a separate draft PR.Specialist Review Evidence (Required for agent-authored PRs)
CodeRabbit Review Evidence (Required for agent-authored PRs)
Applied
coderabbit-reviewand dispatched trusted workflow 42690460714, which succeeded. CodeRabbit replied at20:11:09UTC that review was rate limited; no review currently exists. Required wait completed: reconciled at20:27UTC after the accepted fallback resumed this chat, more than15minutes after the request. No CodeRabbit review or inline findings arrived; rate-limit response remains the outcome. No repeated trigger. Draft/coordinator hold preserved.Exceptions
User requires early draft PR and needs-human-review, exact-head coordinator approval, no direct main commits, separate archival draft PR, coordinated staging slot. Public documentation paragraph only; no UI changes.
Agent Preflight (Required)
Classification
External References
Linux fork/exec preserve kernel session membership: https://www.man7.org/linux/man-pages/man7/credentials.7.html . Linux PID removal waits until no PID-type references remain: https://github.com/torvalds/linux/blob/master/kernel/pid.c (
__change_pid). The optional secret-exec runner uses setsid, but arbitrary devcontainer images need not provide it: this launch path probes and falls back safely.Codebase Impact Analysis
ACP Docker launch and Stop/Wait lifecycle; LocalLauncher retains existing behavior. Per-launch identity is internal, not an HTTP/schema/UI change. Snapshot commands run as container root to inspect same-container processes, emit only metadata and never return env values. Per-command timeout configurable with ProcessConfig.ContainerSignalTimeout. Host Docker uses absolute configurable ProcessConfig.DockerExecutable (default/usr/bin/docker) instead of PATH lookup; tests inject their transport explicitly.
Documentation & Specs
Public VM-agent reference explains per-session cleanup. Task contains investigation, acceptance, test evidence and release constraints.
Constitution & Risk Check
Principles X/XI: standard Linux session identity plus existing marker/ancestry; no service, cgroup, persistent PID file, or mandatory new external dependency. Preserve privileged nested containers and user-owned VM boundary.