Skip to content

Processes started by an automation script keep running after the script ends, and after bb quits #6505

Closed

Description

@bdestrempes

Summary

bb starts each automation script in its own process group, and it stops that group only when the script hits its time limit or output limit. In every other case, bb leaves the script's processes running: when the script exits by itself and leaves a child behind, and when bb stops while the script is still running. In the second case, bb then records the run as interrupted, so the next tick can start a second copy, although the docs say an automation has at most one active run.

Versions and environment

  • bb 0.48.0 (desktop app), macOS 26.6.2 (25G83), Apple silicon
  • Also reproduced on main at 0950d00f962029433790f9fed432c7061051a32e
  • Node 24.22.1 for the repro test
  • No agent provider involved. The bug is in the automations plugin's script runner.

Steps to reproduce

Case A: the script exits and leaves a child behind. The test below runs a 3-line script through the real automation runner. The script starts sleep 30 in the background, prints its process ID, and exits. The test then checks whether sleep is still running. It runs once with exit code 0 and once with exit code 1.

  1. Clone the repo at main and install the automations plugin:

    git clone https://github.com/get-bb/bb.git && cd bb
    git checkout 0950d00f962029433790f9fed432c7061051a32e
    pnpm install --frozen-lockfile --filter 'bb-plugin-automations...' --ignore-scripts
    pnpm exec turbo run build --filter=@get-bb/plugin-sdk
  2. Save this as plugins/automations/src/leftover-group.repro.test.ts:

    import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
    import { tmpdir } from "node:os";
    import { join } from "node:path";
    import { describe, expect, it } from "vitest";
    import { executeStoredScript } from "./script-runner.js";
    import { automationScriptDir, scriptsRoot } from "./script-files.js";
    
    function isRunning(pid: number): boolean {
      try {
        process.kill(pid, 0);
        return true;
      } catch {
        return false;
      }
    }
    
    describe("script process containment after the script exits", () => {
      for (const exitCode of [0, 1]) {
        it(`stops a detached-stdio descendant when the script exits ${exitCode} before its timeout`, async () => {
          const pluginDataDir = await mkdtemp(join(tmpdir(), "bb-auto-leftover-"));
          const scriptDir = automationScriptDir(pluginDataDir, "auto_leftover");
          await mkdir(scriptDir, { recursive: true });
          await writeFile(
            join(scriptDir, "script.sh"),
            `sleep 30 >/dev/null 2>&1 &\nprintf 'child_pid=%s\\n' "$!"\nexit ${exitCode}\n`,
          );
          let childPid = Number.NaN;
          try {
            const result = await executeStoredScript({
              pluginDataDir,
              automationId: "auto_leftover",
              runId: "run_leftover",
              projectId: "proj_test",
              scriptFile: "script.sh",
              interpreter: "bash",
              timeoutMs: 15 * 60_000,
              serverUrl: "http://127.0.0.1:38886",
              workingDir: scriptsRoot(pluginDataDir),
            });
            childPid = Number.parseInt(
              result.output.match(/^child_pid=(\d+)$/mu)?.[1] ?? "",
              10,
            );
            expect(result.timedOut).toBe(false);
            expect(result.exitCode).toBe(exitCode);
            await new Promise((resolve) => setTimeout(resolve, 500));
            console.log(
              `exit ${exitCode}: run settled, descendant pid ${childPid} running=${isRunning(childPid)}`,
            );
            expect(isRunning(childPid)).toBe(false);
          } finally {
            if (Number.isSafeInteger(childPid) && isRunning(childPid))
              process.kill(childPid, "SIGKILL");
            await rm(pluginDataDir, { recursive: true, force: true });
          }
        });
      }
    });
  3. Run it:

    cd plugins/automations
    npx vitest run --config vitest.config.ts src/leftover-group.repro.test.ts

Did not reproduce without >/dev/null 2>&1 on sleep. In that case sleep holds the script's output open, so bb keeps waiting until the time limit, and the time-limit cleanup then stops it. In my real incident, the leftover processes wrote to the Python script's own pipes, not to bb's, so bb saw the script end right away.

Case B: bb stops while the script is still running. I did not test this end to end in bb. I checked the spawn options that the runner uses, with a Node parent that exits while the script runs:

node -e '
const { spawn } = require("node:child_process");
const c = spawn("bash", ["-c", "sleep 30 >/dev/null 2>&1 & echo $!; sleep 30"], { detached: true, stdio: ["ignore", "pipe", "pipe"] });
c.stdout.once("data", d => { require("fs").writeFileSync("/tmp/quit-test.pids", c.pid + " " + String(d).trim()); process.exit(0); });
'
sleep 0.5; read leader bg < /tmp/quit-test.pids
for p in $leader $bg; do kill -0 $p 2>/dev/null && echo "pid $p alive after Node parent exited" || echo "pid $p gone"; done
kill -KILL -$leader

Expected vs actual

Expected: when a run ends, for any reason, no process is left in the script's process group.
When bb stops, it stops the scripts that are running, or it does not report them as stopped.

Actual, case A on main:

exit 0: run settled, descendant pid 10152 running=true
exit 1: run settled, descendant pid 10196 running=true
     × stops a detached-stdio descendant when the script exits 0 before its timeout 516ms
     × stops a detached-stdio descendant when the script exits 1 before its timeout 509ms
AssertionError: expected true to be false // Object.is equality
      Tests  2 failed (2)

Actual, case B with the runner's spawn options:

pid 15232 alive after Node parent exited
pid 15233 alive after Node parent exited

Evidence

Cause, from reading the code

  • bb starts each script as the leader of a new process group. detached: true also means the group does not end when bb ends: script-runner.ts#L208-L213.
  • When the script exits, bb kills the group only if the run hit the time limit or the output limit: script-runner.ts#L242-L247.
  • The run gets no stop signal. The sweep service receives an abort signal (server.ts#L54-L75), but executeStoredScript takes none (run.ts#L301-L312). So nothing stops a running script when bb stops.
  • On the next start, bb marks every script run that was still running as skipped, with "interrupted: the server restarted while the script was running". It does not check whether the script still runs: run.ts#L407-L413.
  • The docs say "An automation has at most one active run", and they mention group cleanup only for the two limits: script-runtime.md#L84-L95.

From these, I infer that after a restart the old copy of a long script can still run while the next tick starts a new one. I have not reproduced two overlapping runs.

Observed: my incident on 0.48.0 (case A)

This is how I found the gap. It was not the root cause.

  • Run arun_grgav3rhzcs started at 21:07:44 local time, with a 15-minute limit. My Python script called bb twice and hit Script automations that call bb spawn bb endlessly until the server runs out of memory #6435 each time, where each bb call starts a copy of itself without end. My script used subprocess.run(..., timeout=180), which kills only the direct child, so each timeout left the rest of the chain running. The script exited with code 1 at 21:16:24, and bb recorded the run as failed. Source: ~/.bb/plugins/automations/data.db, table automation_runs.
  • At 21:21:25, after the run had ended and after I quit bb, ps showed 2,690 bb.js tasks list --project MON --limit 200 --json processes and 1,702 bb.js cockpit bots message ... processes, at about 52 MB RSS each. I counted them with ps -axo command | grep -c 'bb.js tasks' (and 'bb.js cockpit'), and read the parent IDs and RSS from ps -axo pid,ppid,rss,etime,command. Activity Monitor showed about 80 GB for bb, and I had to restart the computer.
  • The chain stayed in the script's process group. In a later repro with the same launcher loop, my harness counted up to 90 bb.js processes with the script's process group ID within 8 seconds.
  • Cleanup at exit would have stopped the chains at 21:16:24, about 8 minutes after they started. Without my script's own timeout, bb's 15-minute limit would have stopped them at 21:22:44. So this gap made the damage last longer, but Script automations that call bb spawn bb endlessly until the server runs out of memory #6435 and my script caused it.

Precedent

launchd kills a job's remaining process group when the job exits, unless AbandonProcessGroup is set (man launchd.plist). systemd kills a unit's remaining processes by default. cron does not clean up. bb already treats the group as its own on timeout.

Suggested fix, for discussion

  • When a run ends on any path, send SIGTERM to the script's process group, then SIGKILL after a short delay, as the timeout path does now.
  • When the automations service stops, do the same for every running script, so that the restart recovery is true when it marks runs as interrupted.
  • Document it as best effort. A child that calls setsid() leaves the group, for example Python's start_new_session=True, tmux, or a daemon. Real containment needs cgroups on Linux, and macOS has no unprivileged equivalent.

I can send a PR once you agree on the behavior.

What you ruled out

  • Not Script automations that call bb spawn bb endlessly until the server runs out of memory #6435 or Stop bb-app's CLI entry from re-launching itself through BB_CLI #6436. Those fix bb starting copies of itself. This is about the lifetime of the script's processes. The case A repro uses sleep, not bb.
  • Still happens on main at 0950d00f962029433790f9fed432c7061051a32e.
  • Not the time-limit path. The existing test "terminates descendant processes when a script times out" passes, and my repro sets a 15-minute limit that never fires.
  • "The script should clean up its own children." Mine should have, and I fixed it to kill its children's process group on timeout. bb owns the run's lifetime, its time limit, and the one-active-run rule, so it should not depend on each script getting this right.
  • No intended use of leftover processes that I could find. None of my automation scripts, and not the marketplace k8s-watch.sh, start a background process on purpose.
  • No open or closed issue about processes left behind by automations. I searched for "automation script process group" and "automation background process survives".

Investigation was done in a local agent session; there is no public thread or report link.

AGENT GENERATED

Suggested priority and effort (optional)

Medium. It needs a hung or runaway child, or a long script during a restart, but then nothing stops the processes, and a restart can break the one-active-run rule. Effort probably Low.

Checks

  • I reproduced this on the latest release or on main, or I say above that I could not.
  • I searched open and closed issues for the same problem.
  • If an agent wrote this, the body ends with > AGENT GENERATED and links the thread or report.

Activity

  1. added theissue type on Oct 29, 2026
  2. added
    plugins
    automations
    confirmed-repro
    on Oct 29, 2026
  3. bb-slop-cop commented on Oct 29, 2026

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    • Classification: Bug · Priority High (runaway workers can exhaust the host) · Effort Low. Applied labels: plugins, automations, confirmed-repro.
    • Reproduction and root-cause report: REPRODUCED, root-cause confidence high. Repeated on two clean trusted-main checkouts; macOS desktop shutdown and memory exhaustion were not exercised.
    • Root cause: Ordinary completion clears the runner's timers without killing remaining process-group members; cleanup was conditional on timeout or output overflow.
    • Regression: An authored Node-worker test with ignored stdio fails on main for parent exit codes 0 and 7, then passes after unconditional close-time cleanup.
    • Ready fix: #6507, not merged. 61 changed text lines across 3 automations files. All 142 automations tests, lint, typecheck, formatting and diff checks pass; lint retains four existing warnings in unchanged UI code.

    AGENT GENERATED

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

    automationsconfirmed-reproplugins

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions