Skip to content

fix(process): detach service-managed tool children on Linux (#120386) - #120398

Closed
chelsealong wants to merge 6 commits into
openclaw:mainfrom
chelsealong:fix-gateway-tool-child-orphan-on-abort-120386
Closed

chelsealong wants to merge 6 commits into
openclaw:mainfrom
chelsealong:fix-gateway-tool-child-orphan-on-abort-120386

Conversation

@chelsealong

@chelsealong chelsealong commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

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 aborted to the caller, but the underlying
process 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 --local does 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 installed
systemd/launchd service, that adapter deliberately spawns children
attached to the daemon's own process group (useDetached = false) so a
crashed/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 gateway
itself. 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-group in the generated systemd unit
(src/daemon/systemd-unit.ts), so the cgroup already reaps every descendant
on 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 install
service 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:

$ node scripts/run-vitest.mjs src/process/supervisor/adapters/child.test.ts
 Test Files  1 passed (1)
      Tests  30 passed (30)

Confirmed the new Linux-service-mode tests fail without the fix (checked out
the pre-fix child.ts while keeping the new tests):

$ git checkout HEAD~1 -- src/process/supervisor/adapters/child.ts
$ node scripts/run-vitest.mjs src/process/supervisor/adapters/child.test.ts
 ❯ createChildAdapter > passes detached:true in service-managed mode on Linux, whose cgroup already sweeps the tree (#120386)
   AssertionError: expected "vi.fn()" to be called with arguments: [ Array(3) ]
   Received: [ 9998, "SIGKILL", { "detached": false, "onComplete": [Function] } ]
 ❯ createChildAdapter > keeps detached mode in service-managed runtime on Linux, whose cgroup already sweeps the tree (#120386)
   AssertionError: expected false to be true
 Test Files  1 failed (1)
      Tests  2 failed | 28 passed (30)
$ git checkout HEAD -- src/process/supervisor/adapters/child.ts   # restored the fix

Also ran, all clean on the touched files:

$ node scripts/run-vitest.mjs src/process/supervisor/adapters/child.test.ts src/process/kill-tree.test.ts
 Test Files  2 passed (2)
      Tests  55 passed (55)

$ pnpm tsgo        # tsgo:core — no errors
$ node scripts/run-oxlint.mjs src/process/supervisor/adapters/child.ts src/process/supervisor/adapters/child.test.ts   # clean, exit 0
$ node scripts/check-changed.mjs -- src/process/supervisor/adapters/child.ts src/process/supervisor/adapters/child.test.ts
 ... all core checks ok (format, dependency pins, plugin boundaries, dead-export scan, etc.)

The broader src/process/supervisor suite has pre-existing, unrelated
failures (timer-overflow/pty/queued-cancellation assertions) reproduced
identically on unmodified main before this change — not touched by this
diff.

Scope note: this fixes the defect for Linux gateway services, which use
the shipped KillMode=control-group systemd unit. macOS/launchd service
installs 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 #120386
    to 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_MARKER on Linux. It now
    requires 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 systemd
    itself 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 coverage
    for 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-group
    together) whose KillMode is later hand-edited away from
    control-group while the marker/env lines are left untouched. Detecting
    that specific drift would require querying the live unit's KillMode (via
    systemctl show, as openclaw doctor's existing
    systemd-kill-mode-process-or-none audit already does) from gateway
    startup — a separate, larger change to the gateway boot sequence that I'm
    not folding into this fix. openclaw doctor already flags that drift
    today.

$ node scripts/run-vitest.mjs src/process/supervisor/adapters/child.test.ts src/process/kill-tree.test.ts
 Test Files  2 passed (2)
      Tests  58 passed (58)

$ pnpm tsgo        # tsgo:core — no errors
$ node scripts/run-oxlint.mjs src/process/supervisor/adapters/child.ts src/process/supervisor/adapters/child.test.ts   # clean, exit 0

Confirmed the 3 new predicate-tightening tests fail against the prior
(pre-tightening) predicate:

$ git checkout HEAD -- src/process/supervisor/adapters/child.ts   # (uncommitted fix stashed out)
$ node scripts/run-vitest.mjs src/process/supervisor/adapters/child.test.ts
 Test Files  1 failed (1)
      Tests  3 failed | 30 passed (33)
# (all 3 failures are the new tightening tests, expecting attached/detached:false
# where the loose marker-only predicate wrongly returned detached:true)

Real (unmocked) Linux service-lifecycle proof, requested by ClawSweeper

This checkout runs on a real Linux host with a live systemd --user
instance (systemctl --user status reports State: running), so both
required 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 createChildAdapter
from this PR, spawns bash -c 'sleep 300 & echo $! > <file>; wait' (a real
grandchild process forked by the direct child), then calls the adapter's
real kill("SIGKILL") and checks /proc/process.kill(pid, 0) for both
PIDs. Removed again after capturing output — never part of the diff:

$ node scripts/run-vitest.mjs src/process/supervisor/adapters/manual-proof-120398.test.ts --reporter=verbose
 ✓ confirmed Linux control-group service: killing the child group-kills the grandchild too   36ms
 ✓ without a confirmed control-group lifecycle: killing the child leaves the grandchild orphaned (the pre-fix bug)   4029ms
 Test Files  1 passed (1)
      Tests  2 passed (2)

The first case sets OPENCLAW_SERVICE_MARKER=openclaw +
OPENCLAW_SERVICE_KIND=gateway + INVOCATION_ID (this fix's confirmed
control-group path) and shows the direct child and its forked grandchild
both die from one kill() call, via the real group-kill on -pid. The
second case strips the systemd hint env vars (this sandbox's own process
already inherits INVOCATION_ID/SYSTEMD_EXEC_PID/JOURNAL_STREAM ambiently
from 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,pgid before/after.

Leg 2 — descendant cleanup after service stop/restart (real systemd --user unit, KillMode=control-group).
Installed a real user unit at
~/.config/systemd/user/openclaw-proof-120398.service with the same
KillMode=control-group line src/daemon/systemd-unit.ts generates for
the shipped gateway unit. ExecStart ran a small script tree standing in
for gateway → detached tool child → its own forked descendant, each
calling setsid (matching this fix's detached: true for the confirmed
Linux path) so each hop gets its own process group/session:

$ systemctl --user start openclaw-proof-120398.service
$ ps -o pid,ppid,pgid,sid,cmd -p $GW,$CH,$GC
    PID    PPID    PGID     SID CMD
  20319    1111   20319   20319 /bin/bash /tmp/proof/gw-sim.sh /tmp/proof/run
  20321   20319   20321   20321 /bin/bash /tmp/proof/child-sim.sh /tmp/proof/run
  20323   20321   20323   20323 /bin/bash /tmp/proof/grandchild-sim.sh /tmp/proof/run
# three distinct pgids/sids -- not sharing the "gateway" process's group,
# exactly like a detached tool child under this fix.

$ systemctl --user stop openclaw-proof-120398.service
$ systemctl --user show openclaw-proof-120398.service -p Result,ActiveState,SubState
Result=success
ActiveState=inactive
SubState=dead
$ for pid in 20319 20321 20323; do kill -0 "$pid" 2>/dev/null && echo "STILL ALIVE $pid" || echo "gone $pid"; done
gone 20319
gone 20321
gone 20323

All three processes were reaped by systemctl --user stop, even though
none of them shared the unit's own process group — confirming the safety
net this whole fix depends on: KillMode=control-group cleans up every
descendant 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 gateway
service.

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 09b9f1525de is a merge commit and its
own tooling couldn't do "an independent full exact-head tree comparison"
against the previously-reviewed fix commit (06ee0095a46) due to missing
local promisor objects. Ran that comparison directly in this checkout,
where the full object graph is present:

$ git diff 06ee0095a46..09b9f1525de -- src/process/supervisor/adapters/child.ts src/process/supervisor/adapters/child.test.ts
diff --git a/src/process/supervisor/adapters/child.test.ts b/src/process/supervisor/adapters/child.test.ts
@@ -838,10 +838,11 @@ describe("createChildAdapter", () => {
-      await createAdapterHarness({
+      const { adapter } = await createAdapterHarness({
         pid: 3334,
         argv: ["/usr/bin/node", "-e", "process.exit(0)"],
       });
+      expect(adapter.oomScoreWrapperSelected).toBe(true);
diff --git a/src/process/supervisor/adapters/child.ts b/src/process/supervisor/adapters/child.ts
@@ -537,6 +537,7 @@ export async function createChildAdapter(params: {
   return {
     pid: child.pid ?? undefined,
     stdin,
+    oomScoreWrapperSelected: preparedSpawn.wrapped,

That's the only delta on either file between the two commits: one field
(oomScoreWrapperSelected) plus its matching test assertion. It traces to
upstream main commit 90acd2bc903 (#117911, an unrelated OOM-score-adjusted
SIGKILL explainer) pulled in by the "Merge branch 'main'" commit — confirmed
absent from 06ee0095a46 and present on upstream/main independent of this
branch. None of this fix's own code changed: isServiceManagedRuntime,
isConfirmedUnderSystemdSupervision, hasConfirmedLinuxControlGroupLifecycle,
requiresAttachedChildrenForServiceLifecycle, and the useDetached call site
are byte-identical between 06ee0095a46 and 09b9f1525de.

Re-ran the full test/lint/type evidence at this exact head (09b9f1525de)
to confirm nothing regressed from the merge:

$ node scripts/run-vitest.mjs src/process/supervisor/adapters/child.test.ts
 Test Files  1 passed (1)
      Tests  33 passed (33)

$ pnpm tsgo        # tsgo:core -- no errors
$ node scripts/run-oxlint.mjs src/process/supervisor/adapters/child.ts src/process/supervisor/adapters/child.test.ts   # clean, exit 0

(33 vs. the previously reported 30 tests is 3 additional tests main
brought in through the same merge, unrelated to this diff's own tests.)

On the still-open KillMode-override question (verifying effective
KillMode at 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-ownership
check (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 live systemd --user instance
(systemctl --user status reports State: 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), with
Environment=OPENCLAW_SERVICE_MARKER=openclaw /
Environment=OPENCLAW_SERVICE_KIND=gateway /
Environment=OPENCLAW_SYSTEMD_UNIT=openclaw-evidence-gateway, matching a
real gateway install. ExecStart ran a small stand-in script that, as the
unit's actual MainPID, calls this PR's real readSystemdServiceRuntime
and the current-head PID-ownership predicate from
confirmLinuxControlGroupKillModeAtStartup
(src/gateway/server-startup-plugins.ts), then spawns a tool child via the
real createChildAdapter (src/process/supervisor/adapters/child.ts)
running bash -c 'sleep 60 & echo GRANDCHILD_PID=$!; wait' — a real
grandchild forked by the direct child — waits, then calls the adapter's
real kill() (the per-run abort/timeout path) and checks both PIDs:

$ systemctl --user start openclaw-evidence-gateway.service
$ journalctl --user -u openclaw-evidence-gateway.service --no-pager
EVIDENCE startup-probe {"selfPid":16263,"runtimeStatus":"running","runtimePid":16263,"resolvedUnitOwnsThisProcess":true,"killMode":"control-group","confirmed":true}
EVIDENCE pre-abort {"childPid":16286,"grandchildPid":16287,"childAlive":true,"grandchildAlive":true}
EVIDENCE post-abort {"childAlive":false,"grandchildAlive":false}

runtimePid (read live via systemctl --user show ... --property MainPID
inside readSystemdServiceRuntime) matches selfPid, confirming the unit
resolved by findInstalledSystemdGatewayScope actually owns this running
process — the exact case the ownership check added in 9720065bd7e guards
against 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 here
touched 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).

…#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.
@chelsealong

Copy link
Copy Markdown
Contributor Author

The check-lint / openclaw/ci-gate failures are unrelated to this PR's diff (only src/process/supervisor/adapters/child.ts + child.test.ts). They're an oxlint max-lines violation in src/agents/embedded-agent-runner/runs.test.ts (1171 lines, cap 1000), already present at this PR's base commit (480e0c0) and reproducing on current upstream/main HEAD (cd53ac0, run https://github.com/openclaw/openclaw/actions/runs/31229801243, jobs check-lint/openclaw/ci-gate both failure) — main is red for the same reason independent of this branch. It's already tracked/fixed separately in #120401 ("fix: restore main CI max-lines compliance"), so no action needed here.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Aug 8, 2026
@clawsweeper

clawsweeper Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I did a careful shell check against current main, and this is already implemented.

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
Relationship: superseded
Canonical: #124081
Summary: Current main’s merged relay-based process-tree cleanup supersedes this branch’s narrower Linux systemd approach.

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 details

Best 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:

  • Josh Avant: Current file history attributes the service-child relay and cleanup-anchor implementation to the merged current-main fix. (role: introduced current-main replacement; confidence: high; commits: ffc94d0ff056; files: src/process/supervisor/adapters/child.ts, src/process/supervisor/service-child-group-anchor.ts)

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.
@chelsealong

Copy link
Copy Markdown
Contributor Author

Addressed both actionable findings from the ClawSweeper review (head 48b13bbc5c2):

  • P2: changed the PR-body directive from Closes #120386 to Related to #120386 — the issue's reproduction is macOS/launchd, which this PR intentionally leaves unchanged.
  • P1: tightened requiresAttachedChildrenForServiceLifecycle() in src/process/supervisor/adapters/child.ts so Linux detach requires the exact gateway marker pair (OPENCLAW_SERVICE_MARKER=openclaw + OPENCLAW_SERVICE_KIND=gateway) and a systemd-native hint (INVOCATION_ID/SYSTEMD_EXEC_PID/JOURNAL_STREAM) confirming real systemd supervision, instead of trusting any non-empty marker. Added 3 regression tests (child.test.ts) proving the previously-accepted-but-unconfirmed cases now stay attached; confirmed they fail against the prior predicate. Full evidence and commands are in the updated PR body.

Not in scope for this pass: detecting a unit that was generated correctly but had its KillMode hand-edited away from control-group afterward — that needs a live systemctl show check from gateway startup (larger change to the boot sequence); openclaw doctor's existing systemd-kill-mode-process-or-none audit already flags that drift today. Flagging as a known follow-up rather than folding it into this fix.

Commit: 06ee009

@chelsealong

Copy link
Copy Markdown
Contributor Author

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) —

  • Leg 1: unmocked createChildAdapter test with real spawned processes, showing the confirmed-control-group path group-kills a child's forked grandchild, and the unconfirmed path leaves the grandchild orphaned (reproducing the pre-fix bug).
  • Leg 2: a real systemd --user unit with KillMode=control-group (matching src/daemon/systemd-unit.ts), proving systemctl stop reaps a gateway-stand-in process tree even when each hop has its own process group.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@chelsealong

Copy link
Copy Markdown
Contributor Author

The 5 failing checks on this head (06ee0095a46) all trace to unrelated content on main, pulled in through the PR merge-ref, not to this diff. This PR's entire diff is src/process/supervisor/adapters/child.ts + src/process/supervisor/adapters/child.test.ts (git diff --stat against the merge-base confirms only those two files change).

No code changes made — the child-adapter fix stays as-is. These are pre-existing main issues from other merged PRs, unrelated to this diff.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 8, 2026
@chelsealong

Copy link
Copy Markdown
Contributor Author

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 git diff 06ee0095a46..09b9f1525de -- src/process/supervisor/adapters/child.ts src/process/supervisor/adapters/child.test.ts in this checkout, where the full object graph is available. The only delta is one field, oomScoreWrapperSelected, plus its test assertion — traced to upstream main commit 90acd2bc903 (#117911, an unrelated OOM-score explainer) pulled in by the merge. This fix's own functions (isServiceManagedRuntime, isConfirmedUnderSystemdSupervision, hasConfirmedLinuxControlGroupLifecycle, requiresAttachedChildrenForServiceLifecycle, the useDetached call site) are byte-identical between the two commits. Re-ran the full test/lint/type evidence at head 09b9f1525de to confirm nothing else regressed — full output now in the PR body.

The effective-KillMode-verification question stays a maintainer policy call, as already noted in the earlier reply on this thread; no code change made there pending that decision.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 9, 2026
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.
@chelsealong

Copy link
Copy Markdown
Contributor Author

Addressed the outstanding P1 ("Gate detachment on the effective systemd KillMode"), option 1 from the review's maintainer options.

  • src/gateway/server-startup-plugins.ts: gateway startup now confirms the running service unit's live KillMode via readSystemdServiceRuntime() (systemctl show, 5s bound) once per boot, before any tool run can start, when the process looks like the gateway's own Linux systemd service. Any probe failure/ambiguous read fails safe (unconfirmed).
  • src/process/supervisor/adapters/child.ts: hasConfirmedLinuxControlGroupLifecycle() now additionally requires that live-confirmed fact (a new single-slot, lifecycle-owned cache) instead of trusting the marker/hint env vars alone — a hand-edited unit or a later KillMode drop-in now keeps children attached instead of being silently trusted.

Added regression coverage in both files' test suites, including "process"/"none" override and probe-failure cases; confirmed the key new case (passes detached:false ... when the startup probe has not confirmed control-group yet) fails against the pre-fix child.ts and passes with it. Full run: node scripts/run-vitest.mjs src/process/supervisor/adapters/child.test.ts src/process/kill-tree.test.ts src/gateway/server-startup-plugins.test.ts — 61 + 30 tests pass. pnpm tsgo, pnpm check:test-types, pnpm check:import-cycles, and oxlint/oxfmt on the touched files are all clean.

Head: e2cae35.

@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Aug 10, 2026
@clawsweeper clawsweeper Bot added status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 10, 2026
…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).
@chelsealong

Copy link
Copy Markdown
Contributor Author

Addressed the P1 ("Confirm the unit that owns this gateway process"): confirmLinuxControlGroupKillModeAtStartup in src/gateway/server-startup-plugins.ts now also requires that the systemd unit readSystemdServiceRuntime resolved actually owns this running process (runtime.pid === process.pid) before trusting its live KillMode. readSystemdServiceRuntime/findInstalledSystemdGatewayScope are user-first on a dueling user/system install, so without this check a coexisting unit reporting control-group could confirm control-group lifecycle for a process it does not own. Any PID mismatch (as well as the existing probe-failure/ambiguous-read cases) now falls back to unconfirmed, keeping children attached.

Added a dueling-scope regression test (server-startup-plugins.test.ts) that mocks a resolved unit reporting control-group with a PID that does not match process.pid, and confirmed it fails against the pre-fix code (mismatch was ignored, confirming true) and passes with the fix.

Evidence at this head:

$ node scripts/run-vitest.mjs src/gateway/server-startup-plugins.test.ts src/process/supervisor/adapters/child.test.ts src/process/kill-tree.test.ts
 Test Files  1 passed (1) / Test Files  2 passed (2)
      Tests  31 passed (31) / 61 passed (61)

$ pnpm tsgo        # clean

$ pnpm check:test-types   # clean

Not addressed in this pass (unchanged from earlier reply): a unit generated correctly but hand-edited to drop KillMode=control-group after install is already covered by the live probe itself, which reads the unit's current effective KillMode rather than trusting the generated file.

…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.
@chelsealong

Copy link
Copy Markdown
Contributor Author

Addressed the outstanding P3 ("Restore inherited systemd environment after this suite"): child.test.ts's beforeEach deletes five service-related env vars (OPENCLAW_SERVICE_MARKER, OPENCLAW_SERVICE_KIND, INVOCATION_ID, SYSTEMD_EXEC_PID, JOURNAL_STREAM), but afterAll only restored OPENCLAW_SERVICE_MARKER. Now all five are captured up front and restored in afterAll.

$ node scripts/run-vitest.mjs src/process/supervisor/adapters/child.test.ts src/gateway/server-startup-plugins.test.ts src/process/kill-tree.test.ts
 Test Files  1 passed (1) / 2 passed (2)
      Tests  31 passed (31) / 61 passed (61)

$ pnpm tsgo         # clean
$ pnpm check:test-types   # clean

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.

@chelsealong

Copy link
Copy Markdown
Contributor Author

The two newest failing checks (Opengrep OSS, Scan changed paths (precise)) both flag the same finding introduced by the last commit (7ce019a9003): the afterAll env-restore loop in child.test.ts:175-181 matches the generic pattern for GHSA-82G8-464F-2MV7 (openclaw-skill-env-host-injection) — any for (const [key, value] of Object.entries(...)) { process.env[key] = value } shape trips it. This loop only restores five previously-captured local env values in test teardown; it isn't copying untrusted skill overrides, so this reads as a false positive against that advisory's actual pattern.

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 (nosemgrep, a sanitizeEnvVars wrapper, or a rule-scope tweak in security/opengrep/precise.yml) would add more code on top of that, so I'm leaving it for a maintainer to pick the right remedy (targeted suppression vs. narrowing the rule) rather than growing this PR further. No code changes made in this pass.

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. label Aug 15, 2026
@chelsealong

Copy link
Copy Markdown
Contributor Author

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 (9720065bd7e) and never ran it against a real, owning systemd unit. Ran an unmocked check at exact head 7ce019a9003 on a real systemd --user instance — a real unit (rendered by this PR's own buildSystemdUnit(), KillMode=control-group) whose MainPID is the process calling readSystemdServiceRuntime, confirming the ownership predicate resolves true, then a real createChildAdapter spawn + forked grandchild + kill() (the abort/timeout path), showing both the child and its forked grandchild die from one call. Full commands/output are in the new "Update: exact-head MainPID-ownership + timeout-cleanup proof" section of the PR body.

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 main, resolving the owned-worker conflict) are also unchanged pending a maintainer call on scope, given the same budget constraint.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 17, 2026
@clawsweeper

clawsweeper Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

@clawsweeper clawsweeper Bot closed this Aug 17, 2026
@clawsweeper

clawsweeper Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper could not autoclose this item.

Reason: structured ClawSweeper close marker: close-required (sha=7ce019a90031a44900955317d4124384c1a1c1ba)

Usage: /autoclose <maintainer close reason>. I will close this item and any open same-repo items explicitly referenced in the command text.

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

Labels

gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant