Skip to content

setsid()'d bash-tool descendants are never reaped once their leader exits — unbounded process leak over long sessions #476

Closed

Description

Summary

A setsid()'d (or otherwise process-group-escaped) descendant of a bash-tool-spawned command is never reaped once its leader has exited — it survives revoke()/session teardown indefinitely. Over a long session this accumulates: a real overnight run left 362 orphaned processes (mostly leftover sh and Python interpreter processes) sitting in the user's systemd session, discovered only because their accumulated memory eventually tripped systemd-oomd's pressure threshold and killed the entire desktop session as a side effect.

This is distinct from #465 (no way to intentionally outlive a tool call) — this is the opposite problem: processes that were not meant to survive leak anyway, silently, with no error surfaced anywhere.

Root cause

groupMembers() in backend/cli/src/credentials/process-ledger.ts has two ways of finding a leader's descendants:

async function groupMembers(entry: Entry): Promise<{ members: Member[]; unverified: boolean }> {
  const currentLeader = await identity(entry.pid)
  if (currentLeader && currentLeader !== entry.identity) return { members: [], unverified: false }
  const rows = await processTable()
  const selected = new Map<number, boolean>()
  for (const row of rows) {
    if (row.pgid === entry.pid) selected.set(row.pid, true)   // plain PGID match
  }
  if (currentLeader === entry.identity) {                      // <-- gated on leader still being alive
    const descendants = new Set([entry.pid])
    ... // PPID-chain walk — the ONLY thing that can find a setsid()'d escapee
  }
  ...

The doc comment above it is explicit about the scope: "The latter catches direct setsid()/start_new_session escapes while the registered leader is still alive."

But groupMembers() (via teardownGroup()) is only ever invoked from complete(), which is only wired to process.once("exit", complete) (backend/cli/src/science/command/registry.ts) — i.e. it never runs until the OS process has already exited. By that point identity(entry.pid) on the now-dead leader returns undefined, so currentLeader is falsy, and the PPID-walk branch is never taken on this path. Only the plain pgid === entry.pid match still runs — but a setsid()'d process has, by definition, already changed its own pgid away from the leader's, so it's invisible to that check too.

This isn't just a code-ordering bug that can be patched by reordering the checks: the escape is unrecoverable by the time complete() runs at all. The moment a process's parent dies, the kernel reparents any orphaned children immediately (to PID 1, or a subreaper) — synchronously, before Node/Bun's event loop even gets notified of the exit. So there is no window, however the checks are ordered, in which post-mortem PPID-chain-walking could still find a setsid()'d escapee. Whatever fix is chosen has to either track descendants while the leader is still alive, or use a mechanism that isn't defeated by the escape+reparent in the first place.

Confirmed reproduction

Added to test/credentials/process-ledger.test.ts, alongside the existing (passing) "revocation reaps a same-group descendant after its recorded leader exits" test — the difference is this descendant calls setsid() before the leader exits, matching a cmd & disown / setsid cmd & pattern:

linuxTest(
  "revocation fails to reap a setsid()'d descendant once its recorded leader has already exited",
  async () => {
    const root = await fs.mkdtemp(path.join(os.tmpdir(), "openscience-credential-setsid-"))
    const marker = path.join(root, "escapee.pid")
    const projectID = `project-setsid-${crypto.randomUUID()}`
    const id = `command-setsid-${crypto.randomUUID()}`
    const leader = spawn(
      "/bin/sh",
      [
        "-c",
        'setsid sleep 600 < /dev/null > /dev/null 2>&1 & printf "%s" "$!" > "$1"; sleep 0.2; exit 0',
        "credential-ledger",
        marker,
      ],
      { detached: true, stdio: "ignore" },
    )
    let escapeePID = 0
    let escapeeIdentity: string | undefined
    try {
      expect(
        await CredentialProcessLedger.register({
          id, kind: "command", pid: leader.pid!, detached: true, projectID, sessionID: "session-setsid",
        }),
      ).toBe(true)
      escapeePID = Number(await waitText(marker))
      escapeeIdentity = await CredentialProcessLedger.identity(escapeePID)
      expect(escapeeIdentity).toMatch(/^[a-f0-9]{64}$/)
      await new Promise<void>((resolve, reject) => {
        leader.once("exit", () => resolve())
        leader.once("error", reject)
      })
      expect(await CredentialProcessLedger.owns(escapeePID, escapeeIdentity)).toBe(true)

      await CredentialProcessLedger.revoke({ kind: "command", projectID })
      expect(await CredentialProcessLedger.owns(escapeePID, escapeeIdentity)).toBe(false)
    } finally {
      await CredentialProcessLedger.revoke({ kind: "command", projectID }).catch(() => undefined)
      if (escapeePID && (await CredentialProcessLedger.owns(escapeePID, escapeeIdentity))) {
        process.kill(escapeePID, "SIGKILL")
      }
      if (leader.exitCode === null && leader.signalCode === null) leader.kill("SIGKILL")
      await fs.rm(root, { recursive: true, force: true })
    }
  },
)

Result on current main:

error: expect(received).toBe(expected)
Expected: false
Received: true
  revocation fails to reap a setsid()'d descendant once its recorded leader has already exited

The escapee survives revoke() entirely.

Why this matters in practice

Confirmed against a real incident, not just synthetically: systemd-oomd's own pre-kill diagnostic log showed the top memory consumers right before it killed an entire desktop session were three local MCP server processes (unrelated leak, reported separately) and the accumulated leftover-process count for the whole session was 362 at cleanup time — an order of magnitude more than any single in-flight task should produce. A long agentic session that runs many bash commands over many hours, where even a small fraction background something via setsid/disown (directly, or indirectly via a script/wrapper the model runs that does this itself), accumulates unboundedly with zero visibility — no error, no warning, nothing in the session transcript to indicate a leak occurred.

Proposed directions (not implemented — flagging for design discussion per CONTRIBUTING.md, since this is core containment behavior, not a small patch)

  1. Extend the existing (currently Windows-only-gated) subreaper path to ordinary Linux commands. teardownLinuxSubreaper() already exists and handles exactly this class of problem cooperatively (the launcher becomes a subreaper, catches reparented orphans via waitpid, and drains them before exiting) — but it's only reachable when linux_subreaper is set, which requires options.windowsRelease (registry.ts: linuxSubreaper: process.platform === "linux" && !!options.windowsRelease) — a flag that's essentially never true for a plain bash-tool spawn. Wiring ordinary command registration through a lightweight subreaper-launcher wrapper (not just the Windows Job Object path) would close this using machinery that already exists and is already tested for the Darwin/Windows-equivalent cases.
  2. Per-command cgroup v2 scope. Place each command's leader in its own delegated cgroup at spawn time; setsid()/start_new_session() doesn't escape cgroup membership (unlike PGID/session), so the whole tree stays discoverable via cgroup.procs and killable via cgroup.kill regardless of internal reparenting. This is the modern Linux-native answer to this exact containment problem (same idea as systemd-run --scope), at the cost of needing user-session cgroup delegation to already be available.

Happy to help prototype either direction, or just discuss which fits the existing architecture better — flagging this now with a solid repro rather than attempting a redesign unreviewed.

Activity

  1. ishaan1124 commented on Sep 5, 2026

    @ishaan1124
    Member

    Fixed in the current release line and re-verified on current main. Linux command launches now use verified child-subreaper containment rather than relying on a dead leader’s process group. Native Linux Deep CI covers normal-completion setsid escapees, adopted double-forks, fail-closed subreaper initialization, and PID-namespace cleanup; the corresponding macOS ownership checks also pass. Evidence: https://github.com/synthetic-sciences/openscience/actions/runs/33953467355 . Thank you for the precise reproduction and containment analysis. This closes the reported unowned-descendant leak, not the separate request for intentionally persistent work.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions