Skip to content

fix(sandbox): end the processes an exec leaves behind - #4097

Merged
yannickmonney merged 26 commits into
mainfrom
fix/sandbox-exec-process-cleanup
Oct 3, 2026
Merged

yannickmonney merged 26 commits into
mainfrom
fix/sandbox-exec-process-cleanup

Conversation

@yannickmonney

@yannickmonney yannickmonney commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Why

Sandbox sessions did not free what their work started. runnerd spawns each exec in a process group of its own but signalled that group only on a cancel or at the exec's deadline: when a command exited on its own, everything it had backgrounded — a cmd &, a nohup worker, a dev server, a browser its driver started detached — kept running in a session that read idle, holding memory and pids until the container stopped (pinned sessions: never). Reproduced in a live container: (sleep 1000 &); nohup sleep 999 & left both alive with /healthz reporting liveExecs: 0, and the exec waited out the 2 s drain grace.

Part of the sandbox resource work; the spawner half is #4098 and the platform half #4099.

What changes

  • An exec's leftover processes are ended. Each exec carries TALE_EXEC_ID in its environment. When its command exits, runnerd sends SIGTERM to what it left running — the exec's process group as a whole, and on its own each tagged process that moved to a group or session of its own (found through an async /proc scan) — then SIGKILL 5 s later. Each process gets one signal, so a second SIGTERM never lands inside the cleanup the first one started. The delayed SIGKILL reaches the group while the exec's own process still runs (its pid holds the group's number, so it also ends a leader whose environment the scan cannot read), and afterwards only while a tagged process is still in it, so a reused number is never signalled.
  • Shared leftovers wait for the last exec. While another exec of the session still runs, an exited exec's leftovers (a dev server, a build daemon it may be using) wait and end when the session's last running exec ends, keeping their output pipes meanwhile (their output is read and dropped). A cancel or the deadline ends an exec's processes at once, what it left waiting included. Otherwise a forced drain closes runnerd's pipe ends.
  • A dropped attach settles. The platform re-attaches every 90 s window; each dropped attach used to keep its subscriber and an active operation until the exec ended (40 reconnects read as 41 operations).
  • A session stop reaches the execs. tini -g forwards SIGTERM only to runnerd's group; runnerd now passes it on to every live exec and to what exited execs left waiting, and closes only once those signals are sent. The egress sidecar's idle sleep infinity runs under tini so a Pod deletion no longer waits out the grace period.
  • Wrappers clean up on cancel. gemini/qwen/pi wrappers left staged settings and per-exec context files (on the workspace volume) after a SIGTERM; they now unwind like tale-openclaw-run, and ignore further signals once their cleanup started.
  • Steer hook: the empty-queue path no longer spawns jq on every tool call (265 → 20 ms per call in the image).
  • Signals never wait on the process table. A group known to be the exec's (a live exec, one whose leader just exited, the SIGKILL while the leader runs) is signalled at once, before /proc is read; a scan answers within 2 s with what it read, and a process whose read never returns is skipped (concurrent scans share its read). A blocked read also no longer hangs runnerd's exit: with one still out, runnerd ends itself by SIGKILL.
  • A steer restart keeps the agent's servers. POST /execs/:id/cancel?leftovers=keep ends only the exec's own group and holds what it left outside it for the exec that takes over; they end when that successor (or the session's last exec) ends, and a hold that sees no successor within ten minutes (a restart whose new exec never started) lifts and ends them. The spawner forwards the flag and the platform's steer restart lane — only that lane — sends it; a person's Stop still ends everything. Older spawners or runnerds ignore the flag and cancel in full.
  • Every exec runs under a subreaper shim. runnerd starts each exec under tale-exec-shim (daemon/exec-shim/tale-exec-shim.c, built in its own image stage), a child subreaper (PR_SET_CHILD_SUBREAPER) that runs the command in a process group of its own: whatever the command orphans is reparented to the shim, not to tini, so a double-forked setsid env -i server (no group, no session, no tag) is still found — by walking down from the shim through /proc/<pid>/stat — and ended with the exec. While every exec of a round has its shim, the scan reads stat alone and takes no process's memory lock. The shim reports the command's pid, exit (128 + N for signal N), spawn error or a refused subreaper on a status pipe (fd 3); the pipe, not the shim's own exit, decides the exit code. It ignores SIGTERM/SIGINT/SIGHUP (a pkill -f aimed at the command must not take the subreaper away) and blocks them across the fork, so a group signal sent before the child restored its defaults still ends it. A cancel that arrives before the shim named the group waits for it and still signals the group once. Without the shim (a non-Linux dev host, a kernel that refuses the subreaper — logged once) execs run as before; runnerd's startup line names it (execShim=).
  • Waiting leftovers keep their group reach. An exec that ends while another runs records its group's processes (pid and start time from stat); a later round treats the group as the exec's while one of them is still in it, so an untagged process in the group (a scrubbed environment, a rewritten title) is ended too.

Behaviour change

A process an exec backgrounds no longer survives the session's last running exec. Nothing on the platform relies on that (no preview ports; checked), and session stops already ended such processes. Out of reach, as documented: the entrypoint's daemons and inner-dockerd containers, and — only where an exec runs without the shim — a process that both left the exec's group and replaced its environment.

Verification

  • bun test (daemon, 243 tests) green on Linux inside the runtime image, both with every exec under the shim and without it; the two host-only reds on macOS (file-ops stalled URL, main "partial exec request body") fail identically on main.
  • exec-shim.test.ts builds the shim from its source wherever Linux has a C compiler (CI's Unit job included; a failing build fails the run) and checks output and exit status, 128 + N for a signal, a spawn error, a setsid env -i escapee ended with its exec, while another exec runs and after a rotation, the control case that the same escapee survives without the shim, and a cancel before the group is named; stand-in shims check runnerd's reading of the status pipe on every platform.
  • The image's new shim stage builds with -Wall -Wextra -Werror, and the image conformance test now boots runnerd under the daemon entrypoint and checks that it names /usr/local/bin/tale-exec-shim and that a double-forked setsid env -i escapee is gone once its exec ends: green on this PR's image (91 checks, 0 failed).
  • New tests fail on the old code: env tag, background child at exit and on cancel, one SIGTERM per cancel, an untagged leader still SIGKILLed, leftovers kept while another exec runs and keeping their pipes, a cancel during the drain, the daemon's stop of live and waiting execs, the leftover prune, a setsid descendant (Linux), a dropped attach, the reaper's one-signal and no-stale-group rules, and each wrapper's cleanup after one and after two signals (the two-signal case failed 8 of 9 runs before the fix).
  • End to end through a real spawner with this runnerd: all three leftovers gone 1 s after the exec, exec 10 ms instead of 2 017 ms; 20 dropped attaches leave activeOperations at 1.

@yannickmonney

Copy link
Copy Markdown
Contributor Author

Independent review of PR #4097 at 9f9b1fcdbb0d0e8bfc1f7e73cbcbdfcd2103f699: changes required (1 MEDIUM, a regression against main, reproduced).

MEDIUM: once the exec's own process has exited, a cancel or deadline no longer SIGKILLs an untagged process left in its group.

  • Where:

    • exec-manager.ts:686-694 with process-reaper.ts:165-171: once the leader is gone, group N is signalled only while a tagged process is in it.
    • On main, a cancel or deadline sent kill(-pgid, SIGKILL) unconditionally.
    • The survivor still holds pgid N, so N can't be reused, and the reuse guard protects nothing in this case.
  • Probe: an untracked bun test that records the one pid it starts and kills only that one. The shell is env -i /bin/sh -c "trap '' TERM; exec sleep 600" & echo $!; wait; the probe cancels it and checks 9 s later.

    Tree The sleep 9 s after the cancel
    main 358f69107 gone
    this head still running
  • Who's exposed: anything started in the background that has lost its TALE_EXEC_ID tag and stops slowly or never on SIGTERM. That includes env -i, a server that rewrites its environment area for a process title (postgres, nginx, gunicorn, celery through setproctitle), and an MCP child started with a filtered environment. A pinned session keeps it running.

  • Fix: treat group N as the exec's while any process has pgrp N and sid N, and N isn't a live exec's group; /proc/*/stat is readable for every process. Or keep the group SIGKILL while the group has members.

  • Regression test: the probe above, asserting the pid is gone within 9 s.

  • Docs: add the case, if any part stays out of reach, to sessions.md's "Out of reach" list. That list also omits processes that left the group with an unreadable environment, such as setuid programs and a non-dumpable ssh-agent.

LOW

  1. The session-stop pass-through isn't guaranteed to give the execs time (main.ts:516-529).
    • On Docker it never runs: docker rm --force is a SIGKILL.
    • On Kubernetes, terminateAll resolves once SIGTERM is sent, and with no connection open process.exit follows on the next tick. A wrapper's finally then races the namespace teardown.
    • Suggest waiting on the live execs' done, bounded to about 4 s.
  2. The manual row overstates its coverage. tests/manual/reference/automation.md:181 marks ✅ the attach-drop release and the SIGTERM pass-through. The specs cover ExecManager only, and the main.ts wiring is untested. Mark it 🔶, or add main.test.ts cases.
  3. The prune test has a timing coupling (exec-manager.test.ts:583-629). prune-long inherits timeoutMs: 5_000, and on a loaded runner the 256 sequential execs can outlast it. Give it timeoutMs: 60_000.

INFO

  • The setsid test finds its pid host-wide (exec-manager.test.ts:327) with pgrep -n -f "^sleep 30$". The toolchain tests also start sleep 30 under turbo's --concurrency=2. Use echo $!.
  • Every exec exit runs two full /proc scans, even with nothing left behind. The scan has no concurrency cap and no timeout, and a hung environ read pins a libuv thread. Skip the SIGKILL round when the SIGTERM round reached nothing.
  • A detached git gc --auto started by an exec's last git command now gets SIGTERM, and the image doesn't set gc.autoDetach=false.
  • No user-facing opt-out is documented. In practice, env -u TALE_EXEC_ID setsid … escapes.

Checked and correct:

  • The tag can't be overridden: it is spread last, and matching is exact.
  • PID 1 and runnerd are never targeted.
  • No other session can be reached: runnerd runs as uid 10001.
  • Each process gets one SIGTERM per exec.
  • Leftovers never outlive the last live exec.
  • An attach settles on abort without making a live exec reclaimable.
  • The gemini, qwen and pi wrappers clean up without cutting the CLI short.

Repairs go through the manager. I'll re-review the next exact head.

@yannickmonney
yannickmonney force-pushed the fix/sandbox-exec-process-cleanup branch from 9f9b1fc to 1fc63f8 Compare October 3, 2026 00:15
@yannickmonney

Copy link
Copy Markdown
Contributor Author

Independent re-review of PR #4097 at 1fc63f8fa61e4817f92716d5aa389523cced2a4b: changes required.

  • The previous MEDIUM is fixed for cancel, deadline and natural exit, but not on the rotation path, where it is still a regression against main (reproduced).

  • New MEDIUM: a second steer ends what the first steer handed over.

  • New MEDIUM: stuck reads can exhaust the fs pool under the default session CPU quota, and the PR's own test fails there.

  • Reviewer: Tale agent update dashboard ui (#508) #2 3f9fdcee-79e7-430b-a430-ba179d5b5132, TALE-483 run bf5d1620-07c5-4697-853c-9de9c9dc8b0a. That is a manual child of TALE-359, distinct from the implementer: the shared principal, commits 22:24Z–23:21Z, no agent update dashboard ui (#508) #2 run.

  • Base:

    • The branch was rebased onto main 358f69107, which is its merge base and current main.
    • The head I reviewed before, 9f9b1fcd, is no longer an ancestor.
    • Changes since that review (the old head merged onto 358f69107, compared with this head): 19 files, +1568/−145.
  • Merge: git merge-tree is clean against main, fix(sandbox): free idle compute, bound helpers, admit by memory and disk #4098 and fix(platform): wait for sandbox room instead of failing the run #4099.

  • CI at this head: all attempt 1, all complete.

    • Build 37081323715.
    • Checks 37081323697: Backend integration ran (job 111082447348), and Unit, UI, Type check and Lint passed.
    • E2E 37081323673, SAST 37081323790 and Commitlint 37081323685.
    • Totals: 52 success, 11 skipped, Trivy neutral. The skips are 5 Candidate gate, 2 fork-PR jobs, and the AI gateway, Docs, UI docs and Web container tests, which are path-filtered.
  • Method:

    • My own runs in an isolated checkout.
    • One read-only source review agent.
    • Tags below: [local] = executed here; [source] = read, not run.

Local probe [local]. An untracked bun test on the public ExecManager API. Each case records the one pid it starts and kills only that pid. The child is env -i /bin/sh -c "trap '' TERM; exec sleep 600": untagged, and it ignores SIGTERM. The check runs 9 s after the exec or its successor ends.

Case 9f9b1fcd (my earlier run) this head main 358f69107
A: cancel while the leader waits survived gone gone
B: the leader exits on its own — gone (the exec ends at the leader's exit; cancel() = false) gone (cancel() = true)
C: deadline after the leader exits — gone gone
D: deadline while the leader waits — gone gone
E: rotation, cancel(id, {keepLeftovers: true}), then a successor exec runs and ends — survived gone

The PR's own tests [local]: bun test src/exec-manager.test.ts src/process-reaper.test.ts src/daemon-exit.test.ts src/main.test.ts gives 78/79. The failure is process-reaper.test.ts:358, "a process whose read did not come back is skipped until the read returns or the pid is someone else's". It fails 6/6 here: 3 runs of the whole file and 3 of the test alone. It passed in CI Unit job 111082288162 (log checked). See MEDIUM 3.

Disposition of the previous review

  • MEDIUM (an untagged process that ignores SIGTERM gets no SIGKILL once the leader has exited): PARTIAL.
    • Fixed for cancel, deadline, natural exit and a deferred exec: process-reaper.ts:411-444, exec-manager.ts:596,603,820-830.
    • Pinned by exec-manager.test.ts:395 and :360, and by process-reaper.test.ts:232,254. Probes A–D confirm it [local].
    • Not fixed on the rotation path: see MEDIUM 1.
  • LOW 1 (the session-stop pass-through gives the execs no time): NOT FIXED. main.ts:528-537: the exit follows the SIGTERM round, not the execs' done [source].
  • LOW 2 (the manual row overstates its coverage): NOT FIXED. automation.md:182 is still ✅, and main.test.ts has no attach-drop or SIGTERM case [source].
  • LOW 3 (the prune test's timing coupling): NOT FIXED. prune-long still inherits timeoutMs: 5_000 (exec-manager.test.ts:960) [source].
  • INFO, host-wide pgrep in the setsid test: NOT FIXED. It's at :346, and there are new ones at :764 and main.test.ts:247 [source].
  • INFO, two /proc scans on every exit: PARTIAL. Scans are now bounded by a deadline and share a stuck read, but the SIGKILL round is still unconditional [source].
  • INFO, a detached git gc gets SIGTERM: NOT FIXED.
  • INFO, no documented opt-out: NOT FIXED.
  • Docs, "Out of reach": PARTIAL.
    • sessions.md:69-73 still leaves out processes outside the group with an unreadable environment.
    • :63-68 says every SIGKILL is backed by a record, which is false for a rotation [source].

MEDIUM 1: a rotation leaves an untagged process that ignores SIGTERM running in the exec's group. Regression against main, reproduced [local].

  • Where:
    • handOver (exec-manager.ts:644-666) sends SIGTERM to the group. Its 5 s timer sends SIGKILL only while the leader still runs.
    • held = {execId, groupId} carries no recorded members.
    • At the successor's end, signalExecProcesses (process-reaper.ts:427-436) signals the group only for a tagged process or a recorded member.
  • On main: a cancel sent SIGKILL to -pgid 5 s later, unconditionally. Case E shows the process gone on main and still running at this head.
  • Exposed: every steer restart (steerTaskAgentTurnImpl, agent_run_host.ts:2346, the only caller of keepLeftovers). Typical survivors are env -i children, servers that rewrite their environment area for a process title, and MCP children started with a filtered environment. A pinned session keeps such a process forever.
  • Fix: record the group's members in handOver right after the SIGTERM. Let the 5 s timer send a group-only SIGKILL while the leader runs or while a recorded member (pid and start time) is still in N.
  • Regression test: case E.

MEDIUM 2: a second steer in the same turn ends the servers the first exec handed over [source, re-read by me; the platform timing is likely, not proven].

  • Where: holdForSuccessor sets heldSince = this.started (:673). The exec ordinal is this.started at start (:330-333). dropLive → liftHolds(rec.ordinal) lifts every hold with heldSince < ordinal (:733-747).
  • Scenario:
    1. E1 (ordinal k) is rotated, so held1.heldSince = k.
    2. Successor E2 (k+1) starts, and a second steer rotates it, so held2.heldSince = k+1.
    3. E2 exits, and liftHolds(k+1) lifts held1.
    4. E3 starts only after the awaited cancel plus resolveTaskServing, stageWorkflowSkills, the mint and the stamp (agent_run_host.ts:2346-2400). Until then the live set is empty, so held1 is reaped: E1's setsid dev server gets SIGTERM, then SIGKILL.
  • The design says otherwise: this contradicts handOver's own comment (:639-643) and sessions.md:92-94.
  • Fix: in handOver, re-hold every leftover this exec would lift (heldSince < rec.ordinal), with heldSince = this.started and a fresh timer.
  • Test: two chained rotations where E2 ends before E3 starts. E1's tagged pid must not be signalled until E3 ends.

MEDIUM 3: stuck environment reads can take the whole fs pool in a default session, and the PR's own test fails there.

  • Measured here [local]:
    • Setup: cgroup cpu.max 200000/100000 (2 CPUs) on a 4-CPU host. That is the quota a session gets from SANDBOX_AGENT_CPUS, whose default is 2 (config.ts:484).
    • Bun 1.4.2's default fs pool serves 2 blocked reads. With 2 FIFO reads blocked, a plain readFile stalls past the 500 ms cut.
    • With UV_THREADPOOL_SIZE=4, it serves 4.
    • That a real session container behaves the same is an inference; I didn't run one.
  • Consequence for the test [local]: process-reaper.test.ts:358-392 sees 3 pending reads instead of 2: the plain read of pid 42 queues behind two pinned threads. The CI runner has more threads.
  • Consequence in production [source]:
    • Two processes stuck on their memory lock stall every node:fs/promises call in runnerd: staging, file reads, the next scan's readdir. This is exactly the case process-reaper.ts and daemon-exit.ts are designed for.
    • Scans then return [] at the deadline, so leftovers go unreaped meanwhile.
    • This is new against main, which never read /proc/*/environ.
    • The shared read (:228-235) bounds the threads per stuck process, not in total.
  • Fix:
    • Keep the environment reads in flight below the pool size, or move them off the pool, and/or set UV_THREADPOOL_SIZE for runnerd.
    • Make the test independent of the pool size.

LOW / INFO [source]

  • A second SIGTERM on the rotation path: survivors get another SIGTERM when the successor ends, so sessions.md:59-60's "one SIGTERM" doesn't hold there.
  • A stuck read loses the SIGKILL: the SIGTERM round's member list leaves out a process whose environment read is still out.
  • A snapshot record: the record taken at deferral doesn't cover untagged children forked into N later.
  • Pipes left open: when leftovers can't be reached, their pipe descriptors stay open.

Checked and correct

  • Nothing signals 0, 1, −1 or runnerd [source + local safety read]:
    • groupOf requires >1 (:327-328), as does signalGroup (:377).
    • The scan skips pid ≤1 and runnerd's own pid (:194).
    • Tagged processes get a positive pid.
    • runnerd's self-SIGKILL fires only with reads pending.
  • PID reuse: after the leader exits, a group is signalled only while a tagged process or a recorded member (pid and start time) is still in it.
  • Holds are bounded to 10 min, and a late cancel of a handed-over exec does nothing.
  • Compatibility: an older runnerd treats keepLeftovers as a plain cancel, and only the steer passes it.
  • No stray processes: none of my probe processes survived (checked).

Repairs go through the manager. I'll re-review the next exact head.

@yannickmonney
yannickmonney force-pushed the fix/sandbox-exec-process-cleanup branch from 1fc63f8 to c863a0c Compare October 3, 2026 01:34
yannickmonney added a commit that referenced this pull request Oct 3, 2026
Backend integration on 2e62a81 stopped at lane 49 of 217: "checkBellHintWire
did not settle within 10 min", then the 30-minute step timeout (job
111128211899). The same hang, at the same lane, failed #4094 (run
37056656989) and #4097 (run 37086605668), neither of which changes a
dependency. The integration run sets no SENTRY_DSN, and importing
@sentry/node 10.48.0 or 10.54.0 without init subscribes to no
diagnostics channel and patches nothing in node:http or fetch. No code
change.
runnerd spawned each exec in a process group of its own but signalled that
group only on a cancel or at the exec's deadline. When the command exited on
its own, everything it had backgrounded (a `cmd &`, a `nohup` worker, a
browser its driver started detached) kept running in a session that read idle,
holding memory and pids until the container stopped, and a leftover holding
the inherited stdout made every such exec wait out the 2 s drain grace.

Each exec now carries its id in the environment (TALE_EXEC_ID). When its
command exits, and on a cancel or at the deadline, runnerd sends SIGTERM to
the exec's process group and to every process carrying the id, which also
reaches a descendant in a group or session of its own, then SIGKILL five
seconds later. A forced drain closes runnerd's ends of the pipes.
A dropped /attach left its subscriber on the exec and kept its request open,
and with it one active operation, until the exec ended. The platform
re-attaches every drain window, so a long agent turn piled up one stale
subscriber and one phantom operation per window (40 reconnects read as 41
active operations) and runnerd's memory grew with each.

The attach now follows its consumer: when the request or response closes, it
leaves the exec's subscribers and settles at once.
tini -g forwards the container stop's SIGTERM to runnerd's process group
only, and every exec runs in a group of its own, so on a Pod deletion a
harness never got to write its transcript or a wrapper to remove what it
staged before the kill; the comment claiming otherwise was wrong. runnerd
now sends every live exec its SIGTERM before it exits.

The egress sidecar idled as a bare `sleep infinity` when it found no proxy;
as PID 1 that ignores SIGTERM, so every Pod deletion waited out the sidecar's
whole grace period. It now idles under tini.
Python's default SIGTERM disposition ends the process without running any
`finally`, so a cancelled or timed-out turn of these three wrappers left its
staged settings in TMPDIR and its per-exec context file under ~/.gemini or
~/.qwen, which sit on the workspace volume for good. A cancel now raises an
exception that unwinds through the cleanup, as tale-openclaw-run already did.
tale-steer-hook runs after every tool call of every Claude Code turn and
spawned jq on the payload before checking whether anything was queued at
all. The empty-queue answer now comes first and only drains the payload:
about 20 ms instead of 265 ms per tool call in the runtime image.
Each process an exec leaves gets one SIGTERM: its group as a whole, and
on their own only the tagged processes that left it. A second signal used
to land inside the cleanup the first one started.

Leftovers of an exec that ends while another exec of the session runs now
wait for the session's last running exec, which may still use them (a dev
server, a build daemon). A delayed signal reaches a group only while a
process tagged with the exec is still in it, so a reused number is never
signalled. The /proc scan is asynchronous and no longer blocks runnerd,
and runnerd's own stop waits for its SIGTERMs to go out before it closes.
The gemini, qwen and pi wrappers ignore further TERM, INT and HUP once a
first one started their cleanup, so a Ctrl-C after a group SIGTERM no
longer leaves the staged settings or context file behind. One test now
covers the cancel path of all three wrappers, after one and two signals.
The delayed SIGKILL of a cancel or a deadline reached the exec's group
only while the /proc scan found a tagged process in it, so a leader with
a scrubbed or unreadable environment that ignored SIGTERM never ended:
the exec stayed live, held a slot and kept the session from going idle.
While the exec's own process runs its pid holds the group's number, so
the SIGKILL goes to the group then, as before.

An exec whose leftovers wait for the session's last exec no longer has
its pipes closed after the drain grace, which killed a waiting dev
server at its next line of output; its output is read and dropped. A
cancel or deadline during that drain ends the waiting leftovers at once
instead of doing nothing. Tests now cover the daemon's stop of waiting
leftovers and the prune past 256.
A cancel, the deadline and runnerd's own stop sent their SIGTERM only
after a scan of /proc had read the environment of every process. That
read takes the target's memory lock, so one process stuck under memory
pressure held back the signal of every exec, and each later round tied
up another thread of libuv's pool on the same process until runnerd's
file routes stalled as well.

A group known to be the exec's (a live exec, one whose leader just
exited, the delayed SIGKILL while the leader runs) is now signalled
before the scan. A scan answers with what it read after two seconds,
and a process whose read did not come back is skipped until the read
returns or its pid names a new process, so a stuck process holds one
thread at most.
process.exit waits for every thread of libuv's pool, so a /proc read
stuck on a process's memory lock kept runnerd's two-second hard exit
from ever completing; the container lived on until the orchestrator
killed it. No timer can step in, since the wait blocks the event loop
itself. With a process-table read still out, runnerd now ends itself
by SIGKILL instead, which waits for nothing; otherwise it exits with
its code as before.
A round that comes after an exec's end signalled the exec's group only
while a process in it still carried the exec's tag, as the group's
number may be someone else's by then. So a leftover that stayed in the
group without the tag (a child started with `env -i` or a cleared
environment) was ended when its exec ended alone, but never once its
leftovers had waited for another exec, and the prune dropped it as
gone. For the same reason such a process that ignored SIGTERM outlived
the SIGKILL of an exec that ended alone.

An exec whose leftovers wait now records its group's processes, pid and
start time read from stat alone, and a SIGTERM round passes on the ones
it saw in the group to its SIGKILL. A later round counts the group as
the exec's while one of them is still in it, and the prune keeps such
a target.
A steer's restart cancels the running exec and starts a new one that
continues the conversation in the same workspace. Since a cancel ends
every process tagged with the exec, it also ended the servers the turn
had started from its tool calls, which most harnesses run in a session
of their own; the restarted turn then found them gone.

POST /execs/:id/cancel?leftovers=keep now ends only the exec's own
group (SIGTERM, then SIGKILL while its leader still runs) and holds
what it left outside the group. The hold lifts once an exec started
after it ends; the leftovers then end with the session's last running
exec, as other leftovers do, or when runnerd stops. A plain cancel, a
user's Stop, ends everything as before, and an older runnerd ignores
the flag.
The spawner's exec cancel route now takes ?leftovers=keep and forwards
it to runnerd's cancel, which then ends only the exec's own process
group and holds what the exec left outside it for the exec that takes
over. Without the flag a cancel ends everything the exec started, as
before; an older spawner ignores the flag, so the platform's rotation
falls back to a full cancel there.
A comment on a task whose agent cannot be steered live restarts the
turn: the old exec is cancelled and a new one continues the
conversation in the same workspace. That cancel ended everything the
turn had started, including a dev server it was testing against from
its shell tool, so the restarted turn found it gone and could take the
site for down.

The restart lane now cancels the old exec as a rotation
(sessionCancelExec with keepLeftovers): the harness's own processes
end, and what it started outside them stays for the restarted turn.
A Stop, a crash and every other cancel still end everything.
The sessions guide now says how a later round proves an exec's group is
still the exec's (a tagged process, or a recorded member still in it),
why a known group is signalled before the process table is read and how
a stuck read is bounded, and what a rotation's cancel
(?leftovers=keep) ends and holds for the exec that takes over.
The exec process-lifetime row now names what the specs own beyond the
earlier checks: signals that do not wait on a stuck /proc read, the
scan's deadline and runnerd's SIGKILL exit, the group record that
reaches an untagged leftover in the exec's group, and a steer
restart's rotation cancel at runnerd, spawner and platform.
Each process-table scan read every environment itself, so scans that ran
at once (a cancel's round, a deferral's group record, a prune) each tied
up a thread of libuv's pool on the same stuck process before the first
of them reached its deadline; four such reads leave runnerd without a
thread for any file work. Concurrent scans now wait on the one read of
a process already out. The listing of /proc is held to the scan's
deadline as well.
After a steer's restart the platform's superseded drive still reaps the
old exec it no longer owns, with a plain cancel. Arriving while the old
exec drained (a child kept its pipes), that cancel ended what the
rotation had just held for the restarted turn. A cancel or deadline of
an exec already handed over now ends none of what it holds; a person's
Stop goes to the exec that took over, whose end ends the held
processes too.
A rotation's cancel holds what the exec left outside its group for the
exec that takes over. A restart whose new exec never started kept that
hold until some later exec of the session ended, keeping a dev server
running in a session that otherwise had nothing to do. The hold now
lifts after ten minutes, and with no exec running its leftovers end at
once.

The listing of the process table can be swapped out, so the bound on a
listing that never answers has a test.
A process that both left an exec's process group and rewrote its
environment (a double-forked `setsid env -i` server, a daemon that sets its
own title) escaped cleanup: neither the group nor the TALE_EXEC_ID tag
reached it, and it ran on in a session that read idle until the container
stopped.

runnerd now starts each exec under tale-exec-shim, a small C program built
in its own image stage. It registers as a child subreaper, runs the command
in a process group of its own, and keeps every process the command starts
its descendant: orphans are reparented to the shim, not to tini. runnerd
finds an exec's processes by walking down from the shim (reading
/proc/<pid>/stat alone while every exec of a round has its shim, so no
process's memory lock is taken) as well as by the tag.

The shim reports on a status pipe (fd 3) the command's pid, how it ended
(128 + N for signal N), why it could not be executed, or that the kernel
refused the subreaper; the pipe, not the shim's own exit, decides the exit
code, since the shim outlives the command for as long as anything it
started runs. It ignores SIGTERM, SIGINT and SIGHUP, so a `pkill -f`
aimed at the command cannot take the subreaper away, and blocks them across
the fork so a group signal sent before the child restored its defaults
still ends it. A cancel that comes before the shim named the group waits
for it, so the group still gets one signal as a whole. Without the shim (a
development host, a kernel that refuses the subreaper, logged once) execs
run as before.
The runtime image conformance test boots runnerd under the daemon entrypoint, checks its startup line names /usr/local/bin/tale-exec-shim, and runs an exec that leaves a double-forked `setsid env -i` sleep behind: the process must be gone once the exec ends.
The exec-reaping ledger row now covers the subreaper shim: a process that left the exec's group, session and tag is found below the shim; the status pipe's exit, signal, spawn-error and refused-subreaper lines; the cancel that comes before the group is named; and where each is automated.
resolveExecShim: the path TALE_EXEC_SHIM names when it is executable, none when it is not, empty or off Linux, and the runtime image's own shim unset. Also gives the export the use knip asks for.
@yannickmonney

Copy link
Copy Markdown
Contributor Author

Post-merge independent reevaluation of #4097 at 37b234216 (squash of 2bc516ee1, merged by root at 07:49:50Z without a re-review of that head). Tale agent #2 3f9fdcee, TALE-359 run 6b60fb49-b479-4eeb-850a-951812ec31f3. This is a source reevaluation by one read-only review agent, cross-checked by me; nothing was executed for it. The squash's net change equals 3b23bd2cb..2bc516ee1.

My earlier findings (records 5963058115, 5963888996):

Finding Status at 37b234216
MEDIUM: an untagged in-group process survived a cancel once the leader exited Fixed, through the recorded group members (exec-manager.ts:682-687,1036-1039) and, under the shim, the walk down from the shim (process-reaper.ts:383-397,500-512). Pinned without the shim (exec-manager.test.ts:361,396).
MEDIUM: a rotation's untagged, TERM-proof survivor Fixed under the subreaper shim. Not fixed without it (TALE_EXEC_SHIM='', or a kernel that refuses the subreaper, for example gVisor, which is unverified). handOver still sends SIGKILL only while the leader runs (:841-843). No test covers it under the real shim.
MEDIUM: a second steer lifts the first steer's hold Not fixed. The code is unchanged (exec-manager.ts:866-874,934-948). Under the shim the walk now also kills an env-scrubbed dev server of the first steer. No chained-rotation test.
MEDIUM: stuck /proc/*/environ reads exhaust the fs pool Partly fixed. Scans read stat only while every target's shim is alive. A shim that ended normally sets rootExited, though, so the SIGKILL round 5 s after every exec ends still reads every process's environ, the common case (pinned that way at process-reaper.test.ts:549). In production runnerd runs under Node, a 4-thread pool rather than Bun's 2.
LOWs: the session-stop pass-through, the manual row's ✅, the prune test's timing Not fixed.
Docs: the "Out of reach" list Fixed (sessions.md:79-83).

The subreaper shim (daemon/exec-shim/tale-exec-shim.c) checks out:

  • Signals and process group: prctl refusal is reported and handled, signals are blocked across the fork and restored in the child, and setpgid is called on both sides.
  • Handles and reaping: the status fd is close-on-exec, the shim's own stdio goes to /dev/null, and it reaps until ECHILD.
  • Exit codes: 128+N for a signal.
  • Reach and fallback: no other exec's processes can be walked. A missing shim falls back to the old direct spawn.
  • Coverage: the image-level check runs in Build.

New, LOW:

  • One stuck intermediate process hides its whole subtree from a tag scan (process-reaper.ts:253-263,282-290,357-379). A cut read goes to unsettled instead of being walked.
  • INFO: pkill -9 -f '<command>' can now kill a shim, whose argv carries the shell string, so runnerd reports 137 and reaps a command that is still running.

Next owner: the manager, for follow-ups: the second steer lifting the first one's hold, the no-shim rotation path, and the per-exec environ scan.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant