Repository navigation
fix(process): detach service-managed tool children on Linux (#120386) - #120398
chelsealong wants to merge 6 commits into
Conversation
…#120386) On the gateway path, killProcessTree already skips group-kill for service-managed children to avoid SIGTERMing the daemon's own process group (openclaw#71662), but that leaves per-run abort only able to signal the top-level child, not the descendants it spawned — they get reparented to PID 1 and keep running after the run reports "aborted". Linux gateway services ship with KillMode=control-group, so the cgroup already reaps every descendant on stop/restart regardless of process-group membership. Detach service-managed children into their own process group on Linux only, so per-run abort can group-kill just that child's tree via its own pgid. launchd has no cgroup equivalent, so non-Linux service runtimes keep the existing attached behavior.
|
The |
|
Thanks for the context here. I did a careful shell check against current Close: current main now fixes the same service-managed command-tree cleanup problem through a relay and in-group cleanup owner, so this Linux-only branch has no remaining landing value. Root-cause cluster Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. So I’m closing this as already implemented rather than keeping a duplicate issue open. Review detailsBest possible solution: Keep the current-main relay and cleanup-anchor design, which solves the command-tree timeout behavior without a systemd-specific startup probe. Do we have a high-confidence way to reproduce the issue? No on current main: service-managed non-Windows children now route through the relay and its cleanup anchor, which owns descendant termination after timeout or abort. Is this the best way to solve the issue? No for this branch: the merged relay-based design is broader and avoids adding a parallel Linux/systemd startup-gating policy. Security review: Security review cleared: The branch adds no dependency, credential, permission, or supply-chain surface; the current-main replacement also keeps cleanup authority inside a private process boundary. AGENTS.md: found and applied where relevant. What I checked:
Likely related people:
Codex review notes: model internal, reasoning high; reviewed against 01e6bef816e3; fix evidence: commit ffc94d0ff056, main fix timestamp 2026-08-16T16:02:34-07:00. |
…inux child detach requiresAttachedChildrenForServiceLifecycle() trusted any non-empty OPENCLAW_SERVICE_MARKER on Linux as proof of the generated systemd unit's KillMode=control-group cgroup sweep. That also matched the sibling "node" service kind and any manually-set marker under a non-systemd supervisor (nohup, pm2), neither of which carries that guarantee. Require the exact gateway marker pair plus a systemd-native hint (INVOCATION_ID/ SYSTEMD_EXEC_PID/JOURNAL_STREAM) confirming real systemd supervision before detaching; keep children attached otherwise.
|
Addressed both actionable findings from the ClawSweeper review (head
Not in scope for this pass: detecting a unit that was generated correctly but had its Commit: 06ee009 |
|
Added the real-behavior proof requested in "Add real behavior proof": PR body now has a new section covering both required legs, run live in this checkout (no code changes) —
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
The 5 failing checks on this head (
No code changes made — the child-adapter fix stays as-is. These are pre-existing |
|
Addressed the outstanding "before merge" finding that's actionable without a maintainer decision: the merge-commit tree comparison your last review couldn't complete locally. Ran The effective- |
The env-marker check only proved the gateway's unit was generated with KillMode=control-group, not that it still is: a hand-edited unit or a later KillMode drop-in (process/none) would still detach children, letting them survive a gateway crash/restart. Gateway startup now confirms the unit's live KillMode via `systemctl show` once per boot and the child adapter only detaches when that probe reported control-group; any probe failure or unconfirmed state keeps children attached, the pre-existing safe default.
|
Addressed the outstanding P1 ("Gate detachment on the effective systemd KillMode"), option 1 from the review's maintainer options.
Added regression coverage in both files' test suites, including "process"/"none" override and probe-failure cases; confirmed the key new case ( Head: e2cae35. |
…trusting KillMode readSystemdServiceRuntime picks the user-scope unit first on a dueling user/system install (openclaw#79375), which can differ from the unit that actually launched this gateway process. Require the resolved unit's MainPID to match process.pid before trusting its live KillMode, so a coexisting unit reporting control-group can no longer confirm control-group lifecycle for a process it does not own (openclaw#120398 review).
|
Addressed the P1 ("Confirm the unit that owns this gateway process"): Added a dueling-scope regression test ( Evidence at this head: Not addressed in this pass (unchanged from earlier reply): a unit generated correctly but hand-edited to drop |
…er suite beforeEach() deletes OPENCLAW_SERVICE_MARKER, OPENCLAW_SERVICE_KIND, INVOCATION_ID, SYSTEMD_EXEC_PID, and JOURNAL_STREAM, but afterAll() only restored OPENCLAW_SERVICE_MARKER, leaking the deletion of the other four into later suites on a systemd-hosted test worker.
|
Addressed the outstanding P3 ("Restore inherited systemd environment after this suite"): Head: 7ce019a. The other rank-up item (a redacted exact-head Linux systemd trace) needs a live systemd host to confirm MainPID/KillMode against a real installed gateway unit, which this environment doesn't have — leaving that for a maintainer or a follow-up run with real service access. |
|
The two newest failing checks ( Not fixing it in this pass: this PR's diff is already ~394 added lines against this session's 120-line hard budget, entirely from four prior rounds of review responses (KillMode gating, PID-ownership check, env-restore fix). Adding a suppression ( |
|
Addressed the outstanding "needs proof" finding without a code change: the latest review's remaining gap was that prior evidence predated the MainPID-ownership check ( Not changing the Opengrep/"Scan changed paths" finding in this pass: this PR is already at +437 lines and I have no code-change budget left, as noted in my 2026-08-11 reply — leaving the suppression-vs-rule-narrowing call to a maintainer. The two optional rank-up items (rebase onto current @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
ClawSweeper applied the proposed close for this PR.
|
|
🦞👀 Reason: structured ClawSweeper close marker: close-required (sha=7ce019a90031a44900955317d4124384c1a1c1ba) Usage: |
Related to #120386 (Linux-only fix; the issue's concrete reproduction is on macOS/launchd and stays unresolved — see Scope note below)
What Problem This Solves
Resolves a problem where a tool's child process (e.g. a long-running shell
command) is not terminated when its run hits the command timeout on the
gateway path. The run reports
abortedto the caller, but the underlyingprocess gets reparented to PID 1 and keeps running to completion,
unsupervised, after the caller was told the work did not happen. For a
non-idempotent tool (a push, a commit, an archive write) that makes a
naive "aborted → retry" pattern dangerous, since it can start a second copy
racing a live first copy.
openclaw agent --localdoes not have this problem.Why This Change Was Made
The gateway spawns tool children through the shared process supervisor
(
src/process/supervisor/adapters/child.ts). When running as an installedsystemd/launchd service, that adapter deliberately spawns children
attached to the daemon's own process group (
useDetached = false) so acrashed/OOM-killed daemon doesn't leave orphans behind (#38463). A later fix
(#71662) correctly taught the per-run abort path to skip
process.kill(-pid, ...)group-kill in that mode, since group-killing would SIGTERM the gatewayitself. But that also means abort can only signal the direct child PID —
not any further descendants it spawned (e.g. a shell running a script that
forks its own children). Those descendants are orphaned and reparented to
PID 1, which is exactly what the issue's probe demonstrates.
The fix is scoped to the platform where it's provably safe: Linux gateway
services ship with
KillMode=control-groupin the generated systemd unit(
src/daemon/systemd-unit.ts), so the cgroup already reaps every descendanton service stop/restart regardless of process-group membership — that
safety net doesn't depend on children sharing the daemon's pgid. So on
Linux, service-managed tool children can safely get their own process group
again, letting per-run abort do a real group-kill of just that child's tree
(via its own
-pgid) without touching the daemon's separate group.launchd has no cgroup equivalent, so non-Linux service runtimes (macOS
launchd) keep the existing attached behavior from #38463/#71662 unchanged;
fixing that platform would need a different mechanism (e.g. an
application-level kill-all-tracked-children sweep at shutdown) and is out of
scope here.
User Impact
On Linux gateway installs (the default
openclaw gateway installservice target), aborting or timing out a backgrounded shell/exec tool run
now actually terminates the full process tree instead of leaving it running
after the caller was told it was aborted. No behavior change on Windows or
on macOS/launchd service installs, and no behavior change outside
service-managed mode (plain CLI/embedded runs were already unaffected).
Evidence
Focused regression test proving the bug and the fix, in
src/process/supervisor/adapters/child.test.ts:Confirmed the new Linux-service-mode tests fail without the fix (checked out
the pre-fix
child.tswhile keeping the new tests):Also ran, all clean on the touched files:
The broader
src/process/supervisorsuite has pre-existing, unrelatedfailures (timer-overflow/pty/queued-cancellation assertions) reproduced
identically on unmodified
mainbefore this change — not touched by thisdiff.
Scope note: this fixes the defect for Linux gateway services, which use
the shipped
KillMode=control-groupsystemd unit. macOS/launchd serviceinstalls still keep the pre-existing attached-child behavior (no regression,
but also no fix there yet) since launchd has no cgroup-equivalent safety net
for a crashed daemon; that would need a separate, larger change and is
flagged as a follow-up rather than folded into this PR.
Update: response to ClawSweeper review (P1/P2)
P2 (issue-closing directive): changed the top line from
Closes #120386to
Related to #120386. The issue's own reproduction is macOS/launchd,which this PR intentionally leaves unchanged, so merging must not
auto-close it.
P1 (over-broad Linux predicate):
requiresAttachedChildrenForServiceLifecycle()no longer trusts any non-empty
OPENCLAW_SERVICE_MARKERon Linux. It nowrequires the exact gateway marker pair (
OPENCLAW_SERVICE_MARKER=openclaw+OPENCLAW_SERVICE_KIND=gateway, i.e. our own generated unit, not the sibling"node" service kind or an unrelated hand-set marker) and a systemd-native
hint (
INVOCATION_ID/SYSTEMD_EXEC_PID/JOURNAL_STREAM, which systemditself stamps on every unit process it starts) confirming the process is
actually supervised by systemd right now, not merely carrying a leftover
marker under a plain
nohup/pm2/custom launcher. Added regression coveragefor both previously-accepted-but-unconfirmed cases (generic marker, and
canonical marker without a systemd hint) proving they now stay attached.
This narrows the false-positive surface substantially but does not chase
the one residual case ClawSweeper's evidence points at: a unit originally
generated by
openclaw gateway install(marker +KillMode=control-grouptogether) whose
KillModeis later hand-edited away fromcontrol-groupwhile the marker/env lines are left untouched. Detectingthat specific drift would require querying the live unit's
KillMode(viasystemctl show, asopenclaw doctor's existingsystemd-kill-mode-process-or-noneaudit already does) from gatewaystartup — a separate, larger change to the gateway boot sequence that I'm
not folding into this fix.
openclaw doctoralready flags that drifttoday.
Confirmed the 3 new predicate-tightening tests fail against the prior
(pre-tightening) predicate:
Real (unmocked) Linux service-lifecycle proof, requested by ClawSweeper
This checkout runs on a real Linux host with a live
systemd --userinstance (
systemctl --user statusreportsState: running), so bothrequired lifecycle legs were exercised for real instead of only through
mocked adapter tests.
Leg 1 — timed-out/aborted child-tree cleanup (real
createChildAdapter, real processes, no mocks).Added a temporary, unmocked test that calls the actual
createChildAdapterfrom this PR, spawns
bash -c 'sleep 300 & echo $! > <file>; wait'(a realgrandchild process forked by the direct child), then calls the adapter's
real
kill("SIGKILL")and checks/proc/process.kill(pid, 0)for bothPIDs. Removed again after capturing output — never part of the diff:
The first case sets
OPENCLAW_SERVICE_MARKER=openclaw+OPENCLAW_SERVICE_KIND=gateway+INVOCATION_ID(this fix's confirmedcontrol-group path) and shows the direct child and its forked grandchild
both die from one
kill()call, via the real group-kill on-pid. Thesecond case strips the systemd hint env vars (this sandbox's own process
already inherits
INVOCATION_ID/SYSTEMD_EXEC_PID/JOURNAL_STREAMambientlyfrom its own systemd session, so they have to be explicitly cleared to
reach the "unconfirmed" branch) and reproduces the exact pre-fix defect:
the direct child dies, the grandchild survives, reparented to PID 1 —
confirmed live with
ps -o pid,ppid,pgidbefore/after.Leg 2 — descendant cleanup after service stop/restart (real
systemd --userunit,KillMode=control-group).Installed a real user unit at
~/.config/systemd/user/openclaw-proof-120398.servicewith the sameKillMode=control-grouplinesrc/daemon/systemd-unit.tsgenerates forthe shipped gateway unit.
ExecStartran a small script tree standing infor gateway → detached tool child → its own forked descendant, each
calling
setsid(matching this fix'sdetached: truefor the confirmedLinux path) so each hop gets its own process group/session:
All three processes were reaped by
systemctl --user stop, even thoughnone of them shared the unit's own process group — confirming the safety
net this whole fix depends on:
KillMode=control-groupcleans up everydescendant by cgroup membership, independent of pgid, so it's safe to give
Linux service-managed tool children their own process group. Unit and
scratch scripts were removed after capture (
systemctl --user disable,rm,daemon-reload); nothing here touched the operator's own gatewayservice.
Proof gathered with Claude Code (Anthropic) in this checkout; not a
maintainer-reviewed or human-run verification.
Development assisted by Claude (Anthropic).
Update: merge-commit tree comparison, requested by ClawSweeper (2026-08-08 review)
The latest review flagged that head
09b9f1525deis a merge commit and itsown tooling couldn't do "an independent full exact-head tree comparison"
against the previously-reviewed fix commit (
06ee0095a46) due to missinglocal promisor objects. Ran that comparison directly in this checkout,
where the full object graph is present:
That's the only delta on either file between the two commits: one field
(
oomScoreWrapperSelected) plus its matching test assertion. It traces toupstream
maincommit90acd2bc903(#117911, an unrelated OOM-score-adjustedSIGKILL explainer) pulled in by the "Merge branch 'main'" commit — confirmed
absent from
06ee0095a46and present onupstream/mainindependent of thisbranch. None of this fix's own code changed:
isServiceManagedRuntime,isConfirmedUnderSystemdSupervision,hasConfirmedLinuxControlGroupLifecycle,requiresAttachedChildrenForServiceLifecycle, and theuseDetachedcall siteare byte-identical between
06ee0095a46and09b9f1525de.Re-ran the full test/lint/type evidence at this exact head (
09b9f1525de)to confirm nothing regressed from the merge:
(33 vs. the previously reported 30 tests is 3 additional tests
mainbrought in through the same merge, unrelated to this diff's own tests.)
On the still-open KillMode-override question (verifying effective
KillModeat runtime rather than trusting the generated unit's markers):that remains the maintainer policy/compatibility call described in this
review's own rationale, as already noted in the earlier reply on this
thread on 2026-08-08. No code change made here pending that decision.
Proof gathered with Claude Code (Anthropic) in this checkout; not a
maintainer-reviewed or human-run verification.
Development assisted by Claude (Anthropic).
Update: exact-head MainPID-ownership + timeout-cleanup proof, requested by ClawSweeper (2026-08-15 review)
Addressed the outstanding "needs proof" finding: prior real-behavior proof
predated
confirmLinuxControlGroupKillModeAtStartup's MainPID-ownershipcheck (added in
9720065bd7e) and never exercised it against a real,owning systemd unit. Re-ran an unmocked check at this exact head
(
7ce019a9003) on this checkout's livesystemd --userinstance(
systemctl --user statusreportsState: running).Installed a real user unit (
~/.config/systemd/user/openclaw-evidence-gateway.service)rendered by this PR's own unmodified
buildSystemdUnit()(
src/daemon/systemd-unit.ts,KillMode=control-group), withEnvironment=OPENCLAW_SERVICE_MARKER=openclaw/Environment=OPENCLAW_SERVICE_KIND=gateway/Environment=OPENCLAW_SYSTEMD_UNIT=openclaw-evidence-gateway, matching areal gateway install.
ExecStartran a small stand-in script that, as theunit's actual
MainPID, calls this PR's realreadSystemdServiceRuntimeand the current-head PID-ownership predicate from
confirmLinuxControlGroupKillModeAtStartup(
src/gateway/server-startup-plugins.ts), then spawns a tool child via thereal
createChildAdapter(src/process/supervisor/adapters/child.ts)running
bash -c 'sleep 60 & echo GRANDCHILD_PID=$!; wait'— a realgrandchild forked by the direct child — waits, then calls the adapter's
real
kill()(the per-run abort/timeout path) and checks both PIDs:runtimePid(read live viasystemctl --user show ... --property MainPIDinside
readSystemdServiceRuntime) matchesselfPid, confirming the unitresolved by
findInstalledSystemdGatewayScopeactually owns this runningprocess — the exact case the ownership check added in
9720065bd7eguardsagainst a dueling/foreign unit for. With that confirmed, one
kill()call(the gateway's abort/timeout path) terminated both the direct child and its
forked grandchild via the real process-group kill, instead of leaving the
grandchild orphaned. Unit removed after capture (
systemctl --user stop,disable,rm,daemon-reload); no leftover processes; nothing heretouched the operator's own gateway service. No code changes made in this
pass.
Proof gathered with Claude Code (Anthropic) in this checkout; not a
maintainer-reviewed or human-run verification.
Development assisted by Claude (Anthropic).