Repository navigation
fix(exec): settle process lifecycles and approval outcomes - #177940
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis PR preserves process cleanup ownership and accurately reports cancellation requests, committed automation changes, and approval outcomes. Example: An operator disables a running stream automation, but process cleanup fails after the disable commits.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this PR open: the lifecycle repair remains useful, prior findings are addressed, and no new actionable defect was found. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherAgent exec/process tools and Gateway cron mutations feed existing process, approval, database, and session owners, which return execution outcomes and persist committed results. flowchart TD
A[Agent request] --> B[Exec and process tools]
B --> C[Process supervisor]
C --> D[Cleanup and terminal result]
A --> E[Approval manager]
E --> F[Cron mutation owner]
F --> G[SQLite transaction]
G --> C
D --> H[Session result publication]
Technical reviewBest possible solution: Land the existing-owner lifecycle repair in stack order once its prerequisite and required current-head CI are clear. Do we have a high-confidence way to reproduce the issue? Current-main source shows transport completion being used without confirming process-tree cleanup; supplied regression scenarios exercise delayed cleanup and rejected or committed cron mutations, but this read-only review ran no reproduction. Is this the best way to solve the issue? The repair keeps process, approval, cron mutation, and transcript decisions with their existing owners; the extracted allocation code replaces its original implementation rather than adding competing policy. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 01264a1e04a1. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +492, Tests +1375, Docs +24, Other 0. Total +1891 across 61 files. Added test files: 4. View PR surface stats
LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (4 earlier review cycles)
Reviewed October 20, 2026, 2:42 AM ET / 06:42 UTC (Revision 5). |
92a87cb to
668cb15
Compare
e40a4a4 to
dc61fd5
Compare
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Preserve process ownership through cleanup and route committed stream updates through the existing lifecycle owner. Keep approval consumption and committed outcome diagnostics consistent for ordinary execution. Co-authored-by: Agustin Rivera <[email protected]>
e3d9b55 to
35e17b3
Compare
f93bc59 to
0f5116e
Compare
|
Preserve B's lifecycle changes while reconciling the continuation fixture with main and retaining its database-worker test routing.
|
Merged via squash auto-merge.
|
…177940) * fix(sessions): preserve durable input and current execution authority * fix(sessions): retain original source checks through input admission * test(sessions): preserve admission and history fixture contracts * test(ai): consume canonical npm pack JSON * fix(exec): settle process lifecycles and approval outcomes Preserve process ownership through cleanup and route committed stream updates through the existing lifecycle owner. Keep approval consumption and committed outcome diagnostics consistent for ordinary execution. Co-authored-by: Agustin Rivera <[email protected]> * test(exec): align lifecycle consumers with current owners * test(exec): preserve mock exports and isolate lifecycle effects --------- Co-authored-by: Agustin Rivera <[email protected]>
…99079) ## Problem When the agent starts a process that must keep running, OpenClaw stops it. - A completed host `exec` call cancels its whole process tree. This stops `cmd &` and `nohup cmd &`. On Linux, the child subreaper also adopts and stops processes that left with `setsid` or a double fork, such as `nginx` and `sshd`. - A one-shot `openclaw agent --local` run cancels every process in its exec scope when it exits. This also stops `background: true` services. - Result: on Linux, no start style survives the CLI. The agent reports success, and the service is gone before anything can use it. - `background: true` services also inherit the 1800 s exec timeout unless the model passes `timeoutSeconds: 0`. - The model-facing text was wrong. `background` said "Start an independent service now; survives request Stop", but the service did not survive the CLI. #150750 made the killing deliberate. Its real problem was that OpenClaw's own relay and owner processes stayed alive with the user's processes. It fixed that by stopping the user's processes too. ## Fix This is PR 1: stop killing, stay bounded. 1. **Hand off on a normal exit.** When the root command exits normally, the process-group owner (anchor) does not signal its group. It reads the process table, reports every live process the command left, stops observing lineage, and exits. On Linux it exits as the subreaper, so adopted processes go to init. If a released process still holds the command's stdout or stderr pipe, the anchor keeps draining that pipe until it closes, so the service never gets SIGPIPE or EPIPE when it logs. The cap bounds these drain anchors. 2. **Every survivor is accounted for.** The report has no size limit. It includes the owner's group members, the processes the Linux subreaper adopted (these are the owner's direct children, and they stay the command's), and all of their descendants, also those in a new session (for example the `sleep` under `setsid sh -c 'sleep 300 & wait'`). If the process table cannot be read, the anchor stops the tree like a cancellation instead of releasing processes it cannot name. 3. **Adopt survivors as sessions.** Each survivor becomes an ordinary background session in the process registry, under the session that ran the command. - The tool result names its PID and session ID. `process list` shows it, and `process kill` stops it. - It is pinned to its start time. Every signal re-checks that identity, so a reused PID is never signalled. - OpenClaw drops it within 5 s of its exit. Gateway stop stops it. 4. **A stop counts only when the exit is observed.** OpenClaw sends SIGTERM, then SIGKILL after the 5 s grace, then waits up to 2 s for the recorded identity to disappear. If a signal is denied (for example EPERM after a UID change) or the process does not disappear, the record stays, the session is marked as cleanup-uncertain, and the result says so. This applies to `process kill`, session reset and delete, Gateway stop and over-limit survivors. A later stop retries. 5. **Admission caps.** At most 16 services per session and 64 per Gateway. A service is a background session or an adopted survivor. - A `background: true` start reserves its slot before approval and startup and holds it until its session runs or startup fails, so concurrent starts cannot pass the limit. - Over the cap, a new `background: true` start fails with an error that names `process list` and `process kill`. - Over the cap, a foreground command's new survivors are stopped by identity, and the result lists their PIDs and the reason. A survivor whose stop is not confirmed stays tracked over the limit, so nothing escapes custody. - OpenClaw never stops an older process to make room. 6. **Stopping stays the same where it matters.** Timeout, no-output timeout, cancellation, request Stop, `process kill`, memory limit, host loss and launch failure still stop the whole tree, including Linux `setsid` and double-fork escapees. Scopes with `required-all` cleanup (the local TUI shell, managed workers, cron exit watchers, update repair, desktop helpers) keep strict cleanup on exit. 7. **Every reset path stops everything the session runs.** Chat `/new` and `/reset`, Gateway `sessions.reset` and session delete all call one shared step, `stopSessionResetProcesses`, after the session's subagents stop and before the replacement conversation is committed. It stops in-flight commands, `background: true` services and adopted survivors by identity. If a stop is not confirmed, the reset fails and asks to retry. Durable processes are not affected. 8. **One-shot exit hands services off.** At the end of `openclaw agent --local`: - `background: true` services and adopted survivors are handed off, and only in-flight work is cancelled. The order from #177940 stays: hand-off, then scope cleanup, then join. - The CLI prints what it left running (PID and command) to stderr. - If the CLI dies without cleanup, host loss still stops work that was not handed off. 9. **No built-in timeout for services.** `background: true` no longer inherits the 1800 s default. An explicit `timeoutSeconds` or a configured `tools.exec.timeoutSeconds` still applies. In a subagent or cron run that can wait for the command with `sessions_yield`, the default still bounds that wait, as current main requires. - `host=node` ignores `background` and runs synchronously through remote `system.run`, so it is not a service. It keeps the ordinary node timeouts (a 1800 s program timer and a longer Gateway invocation deadline, as designed in 6872be8). Without this, `exec {host:"node", background:true}` sent a zero program timer and a 10 s Gateway deadline, and the caller got an outcome-unknown failure before the command returned. 10. **The model sees the truth.** The tool result names every survivor and every stop, with PID and reason. The `background` description and the background-process docs state the real lifetime. The relay and the anchor still exit after every completed command, so #150750 does not regress. ## Proof "Base" is the behaviour without this change. "Previous head" is the head that review rated (`3549c2b`, then `bb2b295`). | # | Proof | Tier | Base / previous head | Head | |---|---|---|---|---| | 1 | 50 calls that each leave a survivor: 16 are adopted, 34 are stopped with the reason in the result, 0 relay or anchor processes remain (#150750); `process list` shows them; `process kill` stops one by identity; an exited one drops out within one reap interval; Gateway stop ends the rest | vitest-source, macOS | previous head: fails | pass | | 2 | One command leaves 20 survivors: 16 tracked, 4 stopped, every PID named, none alive and untracked; then `background: true` is refused and a new survivor is stopped | vitest-source, macOS | previous head: fails (only 16 reported) | pass | | 3 | Two concurrent `background: true` starts at 15 of 16: exactly one starts | vitest-source, macOS | previous head: fails (both start, 17 running) | pass | | 4 | A survivor's child in a new session is tracked; stopping the session ends both | vitest-source, macOS | previous head: fails (child untracked) | pass | | 5 | Real Linux run in `node:24-bookworm` (root, subreaper active) of `bash-tools.exec-group-cleanup.real.test.ts`, `subagent-reset.lifecycle.test.ts` and `worker.runtime.test.ts`: survivors, cap, reservation, descendant closure, `setsid sh -c 'sleep & wait'`, timeout of `setsid`/double-fork children, unconfirmed stops, chat/RPC reset | vitest-source, Linux container (fresh `pnpm install`, no skips) | `bb2b295`: 8 failed (every survivor test: the subreaper-adopted survivors were classed as helpers, so nothing was reported) | 96 of 96 passed, 0 skipped | | 6 | Signals to a survivor are denied (EPERM): reset fails, the session stays running with cleanup uncertainty in its output, the process is still tracked; after signals work, a retry stops it and settles the record | vitest-source, macOS | previous head: fails (reset reported success, record dropped) | pass | | 7 | Chat `/reset` (`initSessionState`) and Gateway `sessions.reset` each stop a running `background: true` service and a `cmd &` survivor before the new session is committed | vitest-source, macOS | previous head: chat path fails (both processes still alive); RPC path passes | pass, both paths | | 9 | Detached styles (`node &`, `nohup`, plain `&`, double fork) survive a completed call; a timeout still stops what the call started; one-shot cleanup hands off and prints services and stops in-flight work; handed-off servers that log every request answer 20 of 20 requests 10 s after the run | vitest-source, macOS | — | pass | | 10 | A timeout stops `setsid` and double-fork children | vitest-source, Linux container | — | pass (part of row 5) | | 11 | Supervisor, relay, anchor, exec, process tool, exec follow-up (`sessions_yield`), cron exit watchers (`required-all` extinction), session reset/delete, agent delete, TUI, desktop and chat session suites | vitest-source, macOS | — | see "Test results" below | | 12 | CLI lifecycle, real model: `openclaw agent --local` with five start styles; the server is probed 0, 3 and 10 s after the CLI exits, then sent 20 requests | source (`ocx src`), macOS | base (`669576890a1f`): 1 of 5 alive (only the double-fork daemon, which leaves the group); `background: true` answers 200 during the run, then dies at CLI exit | 5 of 5 alive, each answers 20 of 20 requests; the CLI prints every handed-off PID; 0 relay/anchor processes after the servers stop | | 13 | Gateway lifecycle, real model, one session: start `background: true`, `nohup &` and plain `&` servers; check them in the next turn; chat `/reset`; start again; RPC `sessions.reset`; start again; stop the Gateway | source (`ocx src -- gateway run`), macOS | base: `nohup &` and plain `&` die at the end of their own call; `background: true` survives chat `/reset` and RPC reset | all 3 survive across turns; chat `/reset` stops all 3; RPC reset stops all 3; Gateway stop stops all 3; 0 relay/anchor processes left | | 14 | Upgrade: latest stable `2026.11.3` runs on a state dir with `tools.exec.timeoutSeconds: 90`, then this head (`doctor --fix --non-interactive`, as update does) runs on the same state | stable: published npm package; head: source (`ocx src`), macOS | stable reads 90 | head still reads 90 after doctor; a `background: true` call gets a deadline 90 s after its start ("times out in 1m30s"); without a configured timeout, the same call on head has no deadline | | 15 | Linux: five styles plus a timeout case in `node:24-bookworm` as root, `openclaw agent --local`, Node runtime | dist-nodts, Linux (this head's `dist/` laid over the `2026.11.5-beta.3` install) | published `2026.11.5-beta.2`: 0 of 5 alive | 5 of 5 alive, each answers 20 of 20 requests 10 s after the CLI exits; the timeout case stops both the `setsid` server and the double-fork daemon | | 16 | `exec {host:"node", background:true}` through `createExecTool` to the node `system.run` invocation keeps the ordinary 1800 s program timer and 1805 s Gateway deadline, and completes | vitest-source, macOS | previous head: fails (program timer 0) | pass | <details> <summary>Redacted captures (CLI and Gateway, head and base)</summary> CLI, base `669576890a1f`, `nohup … &` (the agent's own check fails, then the probes): ```text exec: nohup python3 -m http.server 18972 --bind 127.0.0.1 --directory /tmp > /tmp/oc-srv-18972.log 2>&1 & result: completed 0, (no output) exec: sleep 2; curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:18972/ result: 000 (Command exited with code 7) reply: FAILED 18972 000 after_exit_plus=0s curl=000 · 3s curl=000 · 10s curl=000 · twenty_requests_after_10s=0/20 ``` CLI, head, `nohup … &`: ```text exec result: pid 70493 (…/Python -m http.server 18982 --bind 127.0.0.1 --directory /tmp) keeps running as background session mild-sage:2b822b901780: process list shows it and process kill mild-sage:2b822b901780 stops it. Its later output to this command's stdout/stderr is discarded; redirect it to a file to keep it. reply: STARTED 18982 200 stderr: [openclaw] Left running after this run (OpenClaw no longer tracks them; stop with kill <pid>): pid 70493 …/Python -m http.server 18982 --bind 127.0.0.1 --directory /tmp after_exit_plus=0s curl=200 · 3s curl=200 · 10s curl=200 · twenty_requests_after_10s=20/20 ``` Gateway, base: ```text [turn1] exit=0 reply=STARTED [after-start-1] port=18991 curl=200 [after-start-1] port=18992 curl=000 [after-start-1] port=18993 curl=000 [turn2] exit=0 reply=18991=200 18992=000 18993=000 [after-next-turn] port=18991 curl=200 [after-next-turn] port=18992 curl=000 [after-next-turn] port=18993 curl=000 [turn3] exit=0 reply=✅ Session reset. [after-chat-reset] port=18991 curl=200 [after-chat-reset] port=18992 curl=000 [after-chat-reset] port=18993 curl=000 [turn4] exit=0 reply=STARTED [after-start-2] port=18991 curl=200 [after-start-2] port=18992 curl=000 [after-start-2] port=18993 curl=000 [rpc-reset] ok=true [after-rpc-reset] port=18991 curl=200 [after-rpc-reset] port=18992 curl=000 [after-rpc-reset] port=18993 curl=000 [turn5] exit=0 reply=STARTED [after-start-3] port=18991 curl=200 [after-start-3] port=18992 curl=000 [after-start-3] port=18993 curl=000 [after-gateway-stop] port=18991 curl=000 [after-gateway-stop] port=18992 curl=000 [after-gateway-stop] port=18993 curl=000 helpers_left=0 ``` Gateway, head: ```text [turn1] exit=0 reply=STARTED [after-start-1] port=18991 curl=200 [after-start-1] port=18992 curl=200 [after-start-1] port=18993 curl=200 [turn2] exit=0 reply=18991=200 18992=200 18993=200 [after-next-turn] port=18991 curl=200 [after-next-turn] port=18992 curl=200 [after-next-turn] port=18993 curl=200 [turn3] exit=0 reply=✅ Session reset. [after-chat-reset] port=18991 curl=000 [after-chat-reset] port=18992 curl=000 [after-chat-reset] port=18993 curl=000 [turn4] exit=0 reply=STARTED [after-start-2] port=18991 curl=200 [after-start-2] port=18992 curl=200 [after-start-2] port=18993 curl=200 [rpc-reset] ok=true [after-rpc-reset] port=18991 curl=000 [after-rpc-reset] port=18992 curl=000 [after-rpc-reset] port=18993 curl=000 [turn5] exit=0 reply=STARTED [after-start-3] port=18991 curl=200 [after-start-3] port=18992 curl=200 [after-start-3] port=18993 curl=200 [after-gateway-stop] port=18991 curl=000 [after-gateway-stop] port=18992 curl=000 [after-gateway-stop] port=18993 curl=000 helpers_left=0 (the script counted 1, an unrelated test-runner process whose arguments name the helper files; a direct check found 0 relay/anchor processes) ``` </details> ## Test results (head) - `ocx test` on 139 files (supervisor, relay, anchor, exec, process tool, exec follow-up, cron exit watchers, session reset/delete, agent delete, chat session, subagent reset, TUI, desktop): 10 shards pass, 1456 tests passed, 0 failed (previous head). - After the CI fixes: exec, worker runtime, supervisor, relay, anchor, adapters, TUI shell, exec follow-up, process scope and subagent reset suites: 5 shards, 416 passed, 0 failed (macOS); the Linux container run in row 5. - Not in that run: `bash-tools.exec.approval-id.test.ts`. One of its checks fails in this worktree only because the worktree path contains the word "process"; it passes on CI paths. - `pnpm tsgo:core` clean; oxlint and oxfmt clean on the changed files. ## Limits - The `--dts` build and packed smoke did not run. `ocx build --dts` fails locally with `PLUGIN SDK DTS TOO LARGE` on clean main commits too; CI's `build-artifacts` job on main measured the declarations under the limit. The Linux proof uses the dist-nodts build laid over a published install. - On macOS, a process that leaves the command's process group (`setsid`, double fork) re-parents to launchd before the census unless a tracked parent still holds it. OpenClaw does not see it, so it is not adopted, not capped, and it keeps running after session reset and Gateway stop, as in every other harness compared below. On Linux the subreaper sees it. - A process that a tracked survivor forks after the hand-off is not tracked separately; stopping the survivor does not stop it. - Test lines exceed the 400-line allowance by 150; `config/test-lines-allocations/199079-exec-detached-process-ownership.txt` records them. Each added test is a real-process regression for one review finding. - Adopted services count as live background sessions, so, like `background: true` services, they block a safe Gateway restart until they exit or are stopped. ## How this compares | Harness | Process left by a completed command | Bound while running | Session reset / new | Host stop | One-shot CLI exit | |---|---|---|---|---|---| | Codex | Survives; only timeout or Ctrl-C kills the group | No | Session shutdown terminates all its unified-exec processes | Killed with the session | Survives | | Pi | Survives; only in-flight commands are tracked | No | Kills in-flight commands only | Kills in-flight commands only | Survives | | OMP | Survives; the shell is kept while background jobs run, reaped every 5 s | 15 running background jobs; over the limit, new jobs fail | `newSession()` cancels the session's own async jobs | Kept shells and their jobs die with the harness | Killed with the harness | | Hermes | Tracked in a session-scoped process registry | 64 tracked records; prunes only finished ones | Agent close and session end kill the session's processes, except explicitly persisted ones | — | — | | OpenClaw before | Killed at the end of the call (Linux: daemons too) | — | Killed earlier, at the end of the call | Killed | Killed | | OpenClaw after | Survives as a tracked background session, reaped every 5 s, named in the result and `process list` | 16 per session, 64 per Gateway; over the limit, new services are refused or stopped, old ones never evicted | Stops in-flight work, `background: true` services and survivors; durable processes stay | Stopped | Handed off and printed (as Codex and Pi) | In every harness, a process that daemonized itself and was never tracked keeps running. Sources: Codex `codex-rs/core/src/exec.rs`, `spawn.rs` and `core/src/session/handlers.rs` (`terminate_all_processes`); Pi `packages/coding-agent/src/core/tools/bash.ts`; OMP `packages/coding-agent/src/exec/bash-executor.ts` (`RETAIN_REAP_INTERVAL_MS`), `src/async/job-manager.ts` (`DEFAULT_MAX_RUNNING_JOBS = 15`) and `newSession()` (`#cancelOwnAsyncJobs`); Hermes `tools/process_registry.py` (`MAX_PROCESSES = 64`, `kill_all`). ## Follow-ups (PR 2 and later) - A strict process scope for cron and heartbeat runs, with a tool notice that everything ends with the run. - A durable PID ledger so services are still owned after a Gateway crash. - One ownership policy: remove the service-marker and platform predicates and the PTY rejection. - cgroup and RSS memory budgets for adopted services. - File-backed stdio for all exec, which removes the drain anchor. Co-authored-by: Ayaan Zaidi <[email protected]>
…enclaw#199079) ## Problem When the agent starts a process that must keep running, OpenClaw stops it. - A completed host `exec` call cancels its whole process tree. This stops `cmd &` and `nohup cmd &`. On Linux, the child subreaper also adopts and stops processes that left with `setsid` or a double fork, such as `nginx` and `sshd`. - A one-shot `openclaw agent --local` run cancels every process in its exec scope when it exits. This also stops `background: true` services. - Result: on Linux, no start style survives the CLI. The agent reports success, and the service is gone before anything can use it. - `background: true` services also inherit the 1800 s exec timeout unless the model passes `timeoutSeconds: 0`. - The model-facing text was wrong. `background` said "Start an independent service now; survives request Stop", but the service did not survive the CLI. openclaw#150750 made the killing deliberate. Its real problem was that OpenClaw's own relay and owner processes stayed alive with the user's processes. It fixed that by stopping the user's processes too. ## Fix This is PR 1: stop killing, stay bounded. 1. **Hand off on a normal exit.** When the root command exits normally, the process-group owner (anchor) does not signal its group. It reads the process table, reports every live process the command left, stops observing lineage, and exits. On Linux it exits as the subreaper, so adopted processes go to init. If a released process still holds the command's stdout or stderr pipe, the anchor keeps draining that pipe until it closes, so the service never gets SIGPIPE or EPIPE when it logs. The cap bounds these drain anchors. 2. **Every survivor is accounted for.** The report has no size limit. It includes the owner's group members, the processes the Linux subreaper adopted (these are the owner's direct children, and they stay the command's), and all of their descendants, also those in a new session (for example the `sleep` under `setsid sh -c 'sleep 300 & wait'`). If the process table cannot be read, the anchor stops the tree like a cancellation instead of releasing processes it cannot name. 3. **Adopt survivors as sessions.** Each survivor becomes an ordinary background session in the process registry, under the session that ran the command. - The tool result names its PID and session ID. `process list` shows it, and `process kill` stops it. - It is pinned to its start time. Every signal re-checks that identity, so a reused PID is never signalled. - OpenClaw drops it within 5 s of its exit. Gateway stop stops it. 4. **A stop counts only when the exit is observed.** OpenClaw sends SIGTERM, then SIGKILL after the 5 s grace, then waits up to 2 s for the recorded identity to disappear. If a signal is denied (for example EPERM after a UID change) or the process does not disappear, the record stays, the session is marked as cleanup-uncertain, and the result says so. This applies to `process kill`, session reset and delete, Gateway stop and over-limit survivors. A later stop retries. 5. **Admission caps.** At most 16 services per session and 64 per Gateway. A service is a background session or an adopted survivor. - A `background: true` start reserves its slot before approval and startup and holds it until its session runs or startup fails, so concurrent starts cannot pass the limit. - Over the cap, a new `background: true` start fails with an error that names `process list` and `process kill`. - Over the cap, a foreground command's new survivors are stopped by identity, and the result lists their PIDs and the reason. A survivor whose stop is not confirmed stays tracked over the limit, so nothing escapes custody. - OpenClaw never stops an older process to make room. 6. **Stopping stays the same where it matters.** Timeout, no-output timeout, cancellation, request Stop, `process kill`, memory limit, host loss and launch failure still stop the whole tree, including Linux `setsid` and double-fork escapees. Scopes with `required-all` cleanup (the local TUI shell, managed workers, cron exit watchers, update repair, desktop helpers) keep strict cleanup on exit. 7. **Every reset path stops everything the session runs.** Chat `/new` and `/reset`, Gateway `sessions.reset` and session delete all call one shared step, `stopSessionResetProcesses`, after the session's subagents stop and before the replacement conversation is committed. It stops in-flight commands, `background: true` services and adopted survivors by identity. If a stop is not confirmed, the reset fails and asks to retry. Durable processes are not affected. 8. **One-shot exit hands services off.** At the end of `openclaw agent --local`: - `background: true` services and adopted survivors are handed off, and only in-flight work is cancelled. The order from openclaw#177940 stays: hand-off, then scope cleanup, then join. - The CLI prints what it left running (PID and command) to stderr. - If the CLI dies without cleanup, host loss still stops work that was not handed off. 9. **No built-in timeout for services.** `background: true` no longer inherits the 1800 s default. An explicit `timeoutSeconds` or a configured `tools.exec.timeoutSeconds` still applies. In a subagent or cron run that can wait for the command with `sessions_yield`, the default still bounds that wait, as current main requires. - `host=node` ignores `background` and runs synchronously through remote `system.run`, so it is not a service. It keeps the ordinary node timeouts (a 1800 s program timer and a longer Gateway invocation deadline, as designed in 90a62a0). Without this, `exec {host:"node", background:true}` sent a zero program timer and a 10 s Gateway deadline, and the caller got an outcome-unknown failure before the command returned. 10. **The model sees the truth.** The tool result names every survivor and every stop, with PID and reason. The `background` description and the background-process docs state the real lifetime. The relay and the anchor still exit after every completed command, so openclaw#150750 does not regress. ## Proof "Base" is the behaviour without this change. "Previous head" is the head that review rated (`3549c2b`, then `bb2b295`). | # | Proof | Tier | Base / previous head | Head | |---|---|---|---|---| | 1 | 50 calls that each leave a survivor: 16 are adopted, 34 are stopped with the reason in the result, 0 relay or anchor processes remain (openclaw#150750); `process list` shows them; `process kill` stops one by identity; an exited one drops out within one reap interval; Gateway stop ends the rest | vitest-source, macOS | previous head: fails | pass | | 2 | One command leaves 20 survivors: 16 tracked, 4 stopped, every PID named, none alive and untracked; then `background: true` is refused and a new survivor is stopped | vitest-source, macOS | previous head: fails (only 16 reported) | pass | | 3 | Two concurrent `background: true` starts at 15 of 16: exactly one starts | vitest-source, macOS | previous head: fails (both start, 17 running) | pass | | 4 | A survivor's child in a new session is tracked; stopping the session ends both | vitest-source, macOS | previous head: fails (child untracked) | pass | | 5 | Real Linux run in `node:24-bookworm` (root, subreaper active) of `bash-tools.exec-group-cleanup.real.test.ts`, `subagent-reset.lifecycle.test.ts` and `worker.runtime.test.ts`: survivors, cap, reservation, descendant closure, `setsid sh -c 'sleep & wait'`, timeout of `setsid`/double-fork children, unconfirmed stops, chat/RPC reset | vitest-source, Linux container (fresh `pnpm install`, no skips) | `bb2b295`: 8 failed (every survivor test: the subreaper-adopted survivors were classed as helpers, so nothing was reported) | 96 of 96 passed, 0 skipped | | 6 | Signals to a survivor are denied (EPERM): reset fails, the session stays running with cleanup uncertainty in its output, the process is still tracked; after signals work, a retry stops it and settles the record | vitest-source, macOS | previous head: fails (reset reported success, record dropped) | pass | | 7 | Chat `/reset` (`initSessionState`) and Gateway `sessions.reset` each stop a running `background: true` service and a `cmd &` survivor before the new session is committed | vitest-source, macOS | previous head: chat path fails (both processes still alive); RPC path passes | pass, both paths | | 9 | Detached styles (`node &`, `nohup`, plain `&`, double fork) survive a completed call; a timeout still stops what the call started; one-shot cleanup hands off and prints services and stops in-flight work; handed-off servers that log every request answer 20 of 20 requests 10 s after the run | vitest-source, macOS | — | pass | | 10 | A timeout stops `setsid` and double-fork children | vitest-source, Linux container | — | pass (part of row 5) | | 11 | Supervisor, relay, anchor, exec, process tool, exec follow-up (`sessions_yield`), cron exit watchers (`required-all` extinction), session reset/delete, agent delete, TUI, desktop and chat session suites | vitest-source, macOS | — | see "Test results" below | | 12 | CLI lifecycle, real model: `openclaw agent --local` with five start styles; the server is probed 0, 3 and 10 s after the CLI exits, then sent 20 requests | source (`ocx src`), macOS | base (`0a8e0b7d9cd0`): 1 of 5 alive (only the double-fork daemon, which leaves the group); `background: true` answers 200 during the run, then dies at CLI exit | 5 of 5 alive, each answers 20 of 20 requests; the CLI prints every handed-off PID; 0 relay/anchor processes after the servers stop | | 13 | Gateway lifecycle, real model, one session: start `background: true`, `nohup &` and plain `&` servers; check them in the next turn; chat `/reset`; start again; RPC `sessions.reset`; start again; stop the Gateway | source (`ocx src -- gateway run`), macOS | base: `nohup &` and plain `&` die at the end of their own call; `background: true` survives chat `/reset` and RPC reset | all 3 survive across turns; chat `/reset` stops all 3; RPC reset stops all 3; Gateway stop stops all 3; 0 relay/anchor processes left | | 14 | Upgrade: latest stable `2026.11.3` runs on a state dir with `tools.exec.timeoutSeconds: 90`, then this head (`doctor --fix --non-interactive`, as update does) runs on the same state | stable: published npm package; head: source (`ocx src`), macOS | stable reads 90 | head still reads 90 after doctor; a `background: true` call gets a deadline 90 s after its start ("times out in 1m30s"); without a configured timeout, the same call on head has no deadline | | 15 | Linux: five styles plus a timeout case in `node:24-bookworm` as root, `openclaw agent --local`, Node runtime | dist-nodts, Linux (this head's `dist/` laid over the `2026.11.5-beta.3` install) | published `2026.11.5-beta.2`: 0 of 5 alive | 5 of 5 alive, each answers 20 of 20 requests 10 s after the CLI exits; the timeout case stops both the `setsid` server and the double-fork daemon | | 16 | `exec {host:"node", background:true}` through `createExecTool` to the node `system.run` invocation keeps the ordinary 1800 s program timer and 1805 s Gateway deadline, and completes | vitest-source, macOS | previous head: fails (program timer 0) | pass | <details> <summary>Redacted captures (CLI and Gateway, head and base)</summary> CLI, base `0a8e0b7d9cd0`, `nohup … &` (the agent's own check fails, then the probes): ```text exec: nohup python3 -m http.server 18972 --bind 127.0.0.1 --directory /tmp > /tmp/oc-srv-18972.log 2>&1 & result: completed 0, (no output) exec: sleep 2; curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:18972/ result: 000 (Command exited with code 7) reply: FAILED 18972 000 after_exit_plus=0s curl=000 · 3s curl=000 · 10s curl=000 · twenty_requests_after_10s=0/20 ``` CLI, head, `nohup … &`: ```text exec result: pid 70493 (…/Python -m http.server 18982 --bind 127.0.0.1 --directory /tmp) keeps running as background session mild-sage:2b822b901780: process list shows it and process kill mild-sage:2b822b901780 stops it. Its later output to this command's stdout/stderr is discarded; redirect it to a file to keep it. reply: STARTED 18982 200 stderr: [openclaw] Left running after this run (OpenClaw no longer tracks them; stop with kill <pid>): pid 70493 …/Python -m http.server 18982 --bind 127.0.0.1 --directory /tmp after_exit_plus=0s curl=200 · 3s curl=200 · 10s curl=200 · twenty_requests_after_10s=20/20 ``` Gateway, base: ```text [turn1] exit=0 reply=STARTED [after-start-1] port=18991 curl=200 [after-start-1] port=18992 curl=000 [after-start-1] port=18993 curl=000 [turn2] exit=0 reply=18991=200 18992=000 18993=000 [after-next-turn] port=18991 curl=200 [after-next-turn] port=18992 curl=000 [after-next-turn] port=18993 curl=000 [turn3] exit=0 reply=✅ Session reset. [after-chat-reset] port=18991 curl=200 [after-chat-reset] port=18992 curl=000 [after-chat-reset] port=18993 curl=000 [turn4] exit=0 reply=STARTED [after-start-2] port=18991 curl=200 [after-start-2] port=18992 curl=000 [after-start-2] port=18993 curl=000 [rpc-reset] ok=true [after-rpc-reset] port=18991 curl=200 [after-rpc-reset] port=18992 curl=000 [after-rpc-reset] port=18993 curl=000 [turn5] exit=0 reply=STARTED [after-start-3] port=18991 curl=200 [after-start-3] port=18992 curl=000 [after-start-3] port=18993 curl=000 [after-gateway-stop] port=18991 curl=000 [after-gateway-stop] port=18992 curl=000 [after-gateway-stop] port=18993 curl=000 helpers_left=0 ``` Gateway, head: ```text [turn1] exit=0 reply=STARTED [after-start-1] port=18991 curl=200 [after-start-1] port=18992 curl=200 [after-start-1] port=18993 curl=200 [turn2] exit=0 reply=18991=200 18992=200 18993=200 [after-next-turn] port=18991 curl=200 [after-next-turn] port=18992 curl=200 [after-next-turn] port=18993 curl=200 [turn3] exit=0 reply=✅ Session reset. [after-chat-reset] port=18991 curl=000 [after-chat-reset] port=18992 curl=000 [after-chat-reset] port=18993 curl=000 [turn4] exit=0 reply=STARTED [after-start-2] port=18991 curl=200 [after-start-2] port=18992 curl=200 [after-start-2] port=18993 curl=200 [rpc-reset] ok=true [after-rpc-reset] port=18991 curl=000 [after-rpc-reset] port=18992 curl=000 [after-rpc-reset] port=18993 curl=000 [turn5] exit=0 reply=STARTED [after-start-3] port=18991 curl=200 [after-start-3] port=18992 curl=200 [after-start-3] port=18993 curl=200 [after-gateway-stop] port=18991 curl=000 [after-gateway-stop] port=18992 curl=000 [after-gateway-stop] port=18993 curl=000 helpers_left=0 (the script counted 1, an unrelated test-runner process whose arguments name the helper files; a direct check found 0 relay/anchor processes) ``` </details> ## Test results (head) - `ocx test` on 139 files (supervisor, relay, anchor, exec, process tool, exec follow-up, cron exit watchers, session reset/delete, agent delete, chat session, subagent reset, TUI, desktop): 10 shards pass, 1456 tests passed, 0 failed (previous head). - After the CI fixes: exec, worker runtime, supervisor, relay, anchor, adapters, TUI shell, exec follow-up, process scope and subagent reset suites: 5 shards, 416 passed, 0 failed (macOS); the Linux container run in row 5. - Not in that run: `bash-tools.exec.approval-id.test.ts`. One of its checks fails in this worktree only because the worktree path contains the word "process"; it passes on CI paths. - `pnpm tsgo:core` clean; oxlint and oxfmt clean on the changed files. ## Limits - The `--dts` build and packed smoke did not run. `ocx build --dts` fails locally with `PLUGIN SDK DTS TOO LARGE` on clean main commits too; CI's `build-artifacts` job on main measured the declarations under the limit. The Linux proof uses the dist-nodts build laid over a published install. - On macOS, a process that leaves the command's process group (`setsid`, double fork) re-parents to launchd before the census unless a tracked parent still holds it. OpenClaw does not see it, so it is not adopted, not capped, and it keeps running after session reset and Gateway stop, as in every other harness compared below. On Linux the subreaper sees it. - A process that a tracked survivor forks after the hand-off is not tracked separately; stopping the survivor does not stop it. - Test lines exceed the 400-line allowance by 150; `config/test-lines-allocations/199079-exec-detached-process-ownership.txt` records them. Each added test is a real-process regression for one review finding. - Adopted services count as live background sessions, so, like `background: true` services, they block a safe Gateway restart until they exit or are stopped. ## How this compares | Harness | Process left by a completed command | Bound while running | Session reset / new | Host stop | One-shot CLI exit | |---|---|---|---|---|---| | Codex | Survives; only timeout or Ctrl-C kills the group | No | Session shutdown terminates all its unified-exec processes | Killed with the session | Survives | | Pi | Survives; only in-flight commands are tracked | No | Kills in-flight commands only | Kills in-flight commands only | Survives | | OMP | Survives; the shell is kept while background jobs run, reaped every 5 s | 15 running background jobs; over the limit, new jobs fail | `newSession()` cancels the session's own async jobs | Kept shells and their jobs die with the harness | Killed with the harness | | Hermes | Tracked in a session-scoped process registry | 64 tracked records; prunes only finished ones | Agent close and session end kill the session's processes, except explicitly persisted ones | — | — | | OpenClaw before | Killed at the end of the call (Linux: daemons too) | — | Killed earlier, at the end of the call | Killed | Killed | | OpenClaw after | Survives as a tracked background session, reaped every 5 s, named in the result and `process list` | 16 per session, 64 per Gateway; over the limit, new services are refused or stopped, old ones never evicted | Stops in-flight work, `background: true` services and survivors; durable processes stay | Stopped | Handed off and printed (as Codex and Pi) | In every harness, a process that daemonized itself and was never tracked keeps running. Sources: Codex `codex-rs/core/src/exec.rs`, `spawn.rs` and `core/src/session/handlers.rs` (`terminate_all_processes`); Pi `packages/coding-agent/src/core/tools/bash.ts`; OMP `packages/coding-agent/src/exec/bash-executor.ts` (`RETAIN_REAP_INTERVAL_MS`), `src/async/job-manager.ts` (`DEFAULT_MAX_RUNNING_JOBS = 15`) and `newSession()` (`#cancelOwnAsyncJobs`); Hermes `tools/process_registry.py` (`MAX_PROCESSES = 64`, `kill_all`). ## Follow-ups (PR 2 and later) - A strict process scope for cron and heartbeat runs, with a tool notice that everything ends with the run. - A durable PID ledger so services are still owned after a Gateway crash. - One ownership policy: remove the service-marker and platform predicates and the PTY rejection. - cgroup and RSS memory budgets for adopted services. - File-backed stdio for all exec, which removes the drain anchor. Co-authored-by: Ayaan Zaidi <[email protected]>
Related: #160864. Stack unit 2 of 5; A has landed: #177939. This PR now targets main. Next: #177941.
Current source: captured upstream
f7908148d72e52c7deeca5520e1dfa71fa0c2655→ headea2d849e032286701405f53611c1fd1b4b2a1e3f. The signed merge keeps prior B as its first parent and the A-containing main checkpoint as its second parent. C, D, and E are unchanged. This unit has 4,471 no-renames added-plus-deleted lines (+3,211/−1,260) across 62 files. Prior evidence below remains bound to its named source; new preparation results and limitations follow.What Problem This Solves
Process cancellation and automation changes can report completion before cleanup is confirmed or report a committed change as rolled back when follow-up cleanup fails.
User Impact
Stop results distinguish a requested cancellation from confirmed termination. Failed cleanup retains ownership for reconciliation and blocks replacement; rejected stream updates leave the existing source running. A committed update remains reported as committed even if later cleanup needs attention.
Why This Change Was Made
Join process-tree and backend finalization, recheck process identity after awaited cleanup, and commit stream updates before stopping their prior source. Consume one-use approval only through its live owner and matching committed transaction, then acknowledge durable resolution before best-effort follow-ups. Preserve captured ownership through background-result publication. The existing sandbox lifecycle keeps setup and cleanup while sharing container allocation with the later stream adapter.
This depends on A's background-result mutation classification. It supplies the ordinary approval and container-allocation contracts used by C and D.
Derived from the stream work by Agustin Rivera (@eleqtrizit); contributor credit is preserved in the commit.
Evidence
Preparation after A landed — October 20
A landed as
bc3092fceb5d1353a60647c21c816198ee54d501. The actual B/main conflict resolution preserves upstream's continuation-fixture refactor and B's existing scheduler-registration/wake handling. The background-result test keeps its required database-worker routing exactly once; main's assertion-baseline shrink remains intact. Sixty of B's 62 affected files retain identical bytes and modes to prior B; only the continuation fixture and assertion baseline required reconciliation. No additional production change, dependency, test, timeout, or authorization relaxation was introduced by this preparation.The existing continuation E2E passed on prepared tree
dcd02da7a1c1db5cf2a78e89455b38cb592eeedc: eight model steps, two durable run receipts, rearming, creator disconnect, and reconnect/history behavior. Command:node scripts/run-vitest.mjs test/e2e/qa-lab/runtime/gateway-authorized-continuation.e2e.test.ts --maxWorkers=1. One test passed; test body 35.844s, Vitest 69.23s, full wrapper 339.078s including the isolated cold runtime build. These are test execution costs, not product performance measurements. New-head CI seconds are not yet available.The owning E2E type graph (17.578s), scoped typed lint (18.702s), formatting, assertion-safety and line-cap ratchets, and whitespace checks pass. The initial pre-commit line-cap invocation selected the old ancestry merge base and flagged unchanged upstream
core-descriptors.ts; that file is byte-identical to captured main. The supported explicit prepared-base selection passed without source, baseline, or policy changes. This tooling qualification remains recorded with the original failure.Fresh independent review found no actionable P0–P2 findings in the resolution. Its scope was the resolution and supplied owner/caller context, not a new whole-campaign audit; it did not include every E2E cleanup definition. Root separately inspected the cleanup owner, and the real continuation execution passed. Unchanged behavior reuses the source-bound evidence below. New-head pull-request CI run 39394835555 is attached to
ea2d849e0322and in progress; no current-head broad CI success is claimed. B is prepared, not merged.Prior controlled restack evidence (
0f5116e05126)The controlled restack reconciles seven actual conflict paths against pinned upstream. This unit reconciles the Docker lifecycle owner and Gateway cron fixture with upstream changes.
An automatically merged namespace-recovery regression in D was reproduced by the existing reused-PID test and fixed: each owner proves its namespace before shared PID/start-time classification. Unknown namespaces remain conservative.
Focused proof and review: 45 affected sandbox allocation/access/cleanup cases passed (52.8s wrapper). The final shared integration run passed 365 cases, including 129 cron/lifecycle/drain cases (411.9s wrapper total). Core and Gateway fixture types, focused lint/format, line-cap, assertion, mock-export and SQLite worker ratchets passed; the resolution review was scoped-clean.
Prior CI: run 39388782157 completed successfully on prior head
0f5116e0512656f8047ab49660b985f3fbaa1284: 83 successful jobs, 23 skipped. This is prior-head evidence, not CI clearance for the prepared merge. No manual workflow dispatch or rerun occurred. Earlier runs remain bound to their original heads.Scope remains operation-level, with ordinary streaming and mixed requests. The message-tool interface is unchanged; broad prose consistency and native Codex/Claude enforcement remain outside this guarantee. Historical source qualifications and unresolved failures below remain in force. No new benchmark is claimed.
Prior review and CI triage
Fresh hosted review at
f93bc59b707ereports no actionable code findings. Its installed process/package evidence remains tied to the earlier named revisions; the revised composition has focused harness proof. Exact-head CI run39380683082 completed successfully.CI repair and stack integration
Preserved real exports in the logger mock and explicitly documented isolated external/runtime mock owners. The standalone B checkout passes 34 exec/lifecycle cases (105.01s wrapper), scoped typed lint and mock-export checks. Upstream independently repaired the native-runtime fixtures; integration retains its public service registration and capability assertions plus the isolated probe setting. The background-result owner retains live authority, cancellation, exact replay, commit and publication checks while accepting upstream’s removal of an unused success-return field; media still consumes the message ID from the actual commit receipt.
The complete repaired source
992e8d57e9bpassed the canonical build (252.91s), production/test/UI type checks, scoped typed lint, import-cycle/export guards and shrink ratchets. Canonical prompt snapshots are current. Two fresh scoped repair reviews found no actionable issue; their diff-only limitations are retained. Test costs include cold compilation and owner waits; hosted CI cost for these new heads is not yet available. The repaired pinned-base assembly exactly matches that integration tree.After integration onto fixed upstream
7a255a1990a3b0c280339fc730672bdf9d8cc122, all 30 native/background-result cases pass (145.04s wrapper), as does the selected media promotion-failure/retry case (89.87s; 10 unrelated cases excluded). Production and agent-test types, scoped lint, assertion/mock ratchets and the 372-file line-cap ratchet pass. The canonical complete-stack CI plan passes with 98 selected rows (57.28s); this runs planning locally, not hosted CI. A tree comparison verifies that only the three inspected conflicts differ from Git’s automatic merge; all other upstream integrations are unchanged. Each PR remains below 10,000 changed lines. No benchmark, workflow rerun/dispatch or merge was performed. Fresh full-build evidence is for the repaired pre-rebase tree; the three conflict resolutions received the focused post-rebase checks above.Prior review repairs
The description consumer now checks its capability contract instead of duplicating whole prose strings. The two exit-order tests await the actual
processExitedoperation after process completion, retaining the stale-output and pending-loss assertions. Before repair, the description suite had 13 passes/1 failure and the exit-order suite had 9 passes/2 failures; afterward they pass 14/14 and 11/11. Narrowed liveness wording assertions and shrank the assertion-safety baseline from two casts to one forlazy-process-tool.ts.The affected native-plugin fixtures now register through the public plugin/service contract and read the registered ACP runtime; no retired private facade or
getRuntimeshim remains. The Custodian fixture advertises/provides the current chat-history method. These failures were reproduced, then the native suites passed 21 cases and the browser case passed using the existing supported Chromium override. This is fixture repair, not native Codex/Claude stream-enforcement parity.The continuation fixture now captures the real scheduler channel through its post-ready registration and delivers wakes when advancing the test clock. Its old prefix matched the earlier history channel, while the real worker timer ignored the fake Gateway clock. The initial delayed 84.874s pass is not credited as a fix. With the registration correction, the full continuation passes all eight model steps, two durable run receipts, rearm and reconnect/history assertions in 18.398s, before the original 60-second real-time deadline. No production scheduler, timeout, or authorization assertion changed. All seven existing helper consumers also pass: 46 cases across eight files including continuation, 177.27s grouped wrapper wall.
The other focused group passes 54 cases in 194.55s wrapper wall; browser proof costs 92.65s including build (about 17s test body). Four selected type graphs pass in 64.78s; the final cron/E2E graphs, typed lint, line-cap, shrink-only assertion ratchet and whitespace checks pass. Grouped costs are not per-file measurements; revised-head CI costs are unavailable. Fresh scoped P3 review found no actionable findings in these repairs; it is static review of this delta, not full-campaign or native-enforcement certification.
node scripts/run-vitest.mjs <three files> --maxWorkers=1). CI seconds are unavailable.Selected verbatim Vitest output from the local assembled-tree run above, which preceded the final C fixture correction. The quoted test files are byte-identical at packaged source
4733afc513466and final complete-stack source191c7fe10d189; this is not a separate intermediate-unit run. These two composed consumer tests ship in C and exercise the protected cron write.Retained earlier proof (not rerun after rebase):
bd6dbed4c773; the original published B head92a87cbdddf4had unchanged production code. Its later test-only work had separate proof: a byte-identical worker-fixture relocation, 13 registered lifecycle cases, and focused static checks.node scripts/run-vitest.mjs <selected files>; separate per-file--maxWorkers=1wall measurements and CI seconds were not recorded. Selected core/test types, lint and formatting passed.