From c0b0517dc36553bd4628ff8fb4a61f7c5e542f16 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:22:35 -0600 Subject: [PATCH] fix(antigravity): stop every process a swarm's CLI started before reporting its outcome (#22875) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Google Antigravity agents can run Google's native `/swarm` on the native Runner (experimental flag, #22733, #22865) > - In a live run, the `agy acp` CLI process was killed mid-swarm. Its helper shell commands kept running for about 14 s, and one wrote a file in the task folder 14 s after the kill > - The failure was recorded only when those helpers exited, because they held the CLI's output pipe open. Automatic recovery then starts a fresh swarm in the same folder, so old helpers can race it > - Recovery must just work, and nothing may write in a task folder after its run ended > - This pull request records every process the CLI starts and stops all of them before a failed or stopped swarm turn is reported and on shutdown, and detects a lost CLI on exit > - The benefit is that a crashed, stopped, timed-out or shut-down swarm leaves no process behind and recovery never races old helpers ## Linked Issues or Issue Description Refs #22733, #22865 **What happened?** After a `kill -9` of the swarm's `agy acp` process, three helper commands outlived it by about 14 s. One wrote a file in the task folder 14 s after the kill. The run failure was recorded about 15 s after the kill, right after the last helper exited. On a user Stop the helpers were gone in 0.2 s, because the CLI stops them itself. **What did you expect?** When the CLI exits for any reason, every process it or its helpers started stops within about 2 s, before Paperclip records the outcome and before recovery starts in the same folder. **Steps to reproduce** Start `/swarm` on a task with helpers that run shell commands. Kill the `agy acp` process. Watch the helper processes and the task folder. **Why it happened** - `retireAntigravityProcess` signals only the launcher's process group. The CLI starts each helper command as its own process-group leader, and when the CLI dies those commands are re-parented. - The swarm connection detected a lost CLI on the child's `close` event. `close` waits until every copy of stdout is closed, and the helpers inherited that pipe. - runnerd already records the full process lineage of the sidecar (`process_lineage.rs`) and stops it when the sidecar is torn down. That happens after the turn outcome is published, so it cannot keep the helpers from writing first. ## What Changed - New `antigravity-process-lineage.ts`: records the lineage of the CLI launcher while it runs, with runnerd's `LineageTracker` membership rules, scoped to the CLI's subtree. A process belongs when its parent belongs, or when it is in a group or session that a member leads and started no earlier than that leader (sessions on Linux; macOS `ps` reports no session id). Identity is PID plus start time, re-read just before each signal, so a reused PID is never signalled. A recorded member that exists but cannot be read stays unresolved, and a table read that does not list this process is rejected; neither proves the lineage gone. Membership never depends on a command name, so other `agy` processes of the same user are never touched. It reads `/proc` on Linux and `/bin/ps` (numbers only) on macOS, every 200 ms while the CLI runs. `terminate()` re-reads the table each round, sends SIGKILL to every live member (the first round before any deadline), and proves none remain within 1.5 s. - Why not runnerd's tracker directly: it is rooted at the sidecar and stops the whole lineage, the sidecar included, only at sidecar teardown. It has no operation for one subtree. The swarm must stop the CLI subtree while the sidecar keeps serving the run, also on Stop and helper timeout, when the CLI is still alive. Reusing it needs a new sidecar-to-runnerd operation and a Rust change, which is out of scope here. The macOS retirement check in `antigravity-process.ts` now uses the same process-table reader. - `antigravity-swarm-runtime.ts`: the CLI's retirement now also terminates that lineage. A swarm turn that did not complete (CLI lost, Stop, helper timeout, refusal) retires the CLI and its lineage before the outcome is returned. `close()` (runner shutdown) does the same. A swarm turn is the port's only turn, so nothing else uses the CLI after it. - Cleanup fails closed. A failed or incomplete process-table read is retried. If the helpers still cannot be proven stopped after three attempts, the turn fails as not retryable with plain text, so Paperclip does not continue the task on its own in that folder. A failed retirement is not cached, so `close()` tries again. - A lost CLI is detected on the child's `exit` event. Output already written is read for up to 200 ms after exit; the inherited pipe no longer delays the failure. - Fake CLI scenario `orphan-helpers`: a helper that leads its own process group, holds the CLI's output pipe, and writes `late.txt` after a delay. The CLI never stops it itself. - Qualification ledger: the live re-check of #22865 (Stop usage 36,910 in / 869 out; killed-run usage still 0 with CLI 1.5.15; kill text and automatic recovery; receipt event; clean thread text) and this fix (fake-CLI proof, live proof pending). Investigated and not changed here: an ordinary (non-swarm) Antigravity run read the instance's run logs and the CLI's private files outside its task folder. No existing Runner policy confines reads for this harness; confining them would be a new policy, so it is reported separately. ## Verification - Red/green: with only the runtime change reverted, the new swarm tests fail (the failure waited on the pipe; helper alive after Stop; helper alive after shutdown; unproven cleanup reported as recoverable). With the change they pass. - Swarm tests kill the fake CLI with SIGKILL and check that the helper is dead when the failure is reported, that `late.txt` is never written (the helper writes it after 3 s, so a report that waited on its pipe would fail), and that an unrelated process of the same user survives. They also cover Stop, runtime close mid-swarm, and a failing process listing (not retryable; the helper stays alive past the cleanup budget and the later close stops it). - Lineage unit tests: re-parented helpers and their children are kept; session members are kept; a reused PID, a reused group id and an earlier-started process are never claimed; zombies are dropped; unreadable members stay unresolved; failed, empty, self-less and unreadable reads never prove the lineage gone and a later call retries; a PID whose start time changed is never signalled; the first kill round runs even when its read exceeds the deadline; pure macOS `ps` and Linux `/proc` parsers; a detached grandchild of a dead root is stopped and an unrelated process survives. Each review-driven rule was checked by reverting it and seeing its test fail. - All Antigravity driver suites (packages/paperclip-runner): 20 files, 363 tests passed. `tsc --noEmit` for the Runner package passed. - `pnpm verify` exited 2 (the fake CLI fixture is a broad input), so CI supplies the broad coverage. `tests/runner-e2e/source-sdk-public-inputs.mjs --write` reported no change. - Not run: a live swarm (live proof is pending and recorded as pending in the ledger). Linux ran only in CI. ## Risks - A sampler reads the process table every 200 ms while a swarm CLI runs (`ps` on macOS, about 25 ms wall time; `/proc` on Linux). Only swarm turns run it. - A helper that starts and leaves its group and session within one 200 ms sample, before it is seen, can escape this tracker. runnerd's sidecar lineage still stops it at sidecar teardown. - A swarm turn that ended without completing now stops the CLI before reporting. The port already refuses a second swarm turn, so no later turn depended on that CLI. - If cleanup cannot be proven (for example the process table cannot be read), the swarm fails without automatic recovery instead of risking a race. - macOS start times have one-second resolution, so a PID reused within the same second as the original start could match. The group and parent rules also need a recorded member, which keeps this narrow. - On macOS there is no session rule, because `ps` reports no session id. A helper that calls `setsid` is still recorded as a group leader when a sample sees it. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../2026-11-22-antigravity-qualification.md | 11 + .../acpx/antigravity-process-lineage.test.ts | 150 +++++++++++ .../acpx/antigravity-process-lineage.ts | 238 ++++++++++++++++++ .../src/drivers/acpx/antigravity-process.ts | 12 +- .../acpx/antigravity-swarm-runtime.test.ts | 92 +++++++ .../drivers/acpx/antigravity-swarm-runtime.ts | 40 ++- .../antigravity-cli/fake-agy-acp.mjs | 12 + 7 files changed, 545 insertions(+), 10 deletions(-) create mode 100644 packages/paperclip-runner/src/drivers/acpx/antigravity-process-lineage.test.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/antigravity-process-lineage.ts diff --git a/doc/plans/2026-11-22-antigravity-qualification.md b/doc/plans/2026-11-22-antigravity-qualification.md index ec1f7c659ce..e4345481acc 100644 --- a/doc/plans/2026-11-22-antigravity-qualification.md +++ b/doc/plans/2026-11-22-antigravity-qualification.md @@ -410,3 +410,14 @@ profile stays **pending** until an operator grants the flip. Facts above: local darwin-arm64 instance at commit 438ae60922, 2026-11-25, Google subscription sign-in. + +### Re-check of the swarm fixes (local, 2026-11-25, commit cd8bcfba16) + +| Gate | Result | +| --- | --- | +| Usage on Stop (Flash) | Passed live: the stopped run recorded 36,910 in / 869 out tokens | +| Usage on a killed CLI | Still 0 live: CLI 1.5.15 streams no token counts during a swarm prompt and reports them only when the turn ends, so a killed run has nothing to keep. Documented; not estimated | +| Kill text and automatic recovery | Passed live: the failure says the CLI exited and files stay in the task folder, with no Retry; Paperclip recovered with a fresh swarm and the task finished | +| Settings receipt in the run record | Passed live: one provider notice with requested and confirmed model, thinking level, mode, channel, CLI version and account match | +| Thread text | Passed live: no terminal hint, no stray ".", no local paths or `file://` links, no mention of the swarm rules | +| Helper processes after a killed CLI | Gap found live: helper shell commands lead their own process groups, outlived the killed CLI by about 14 s, one wrote a file 14 s after the kill, and the failure was recorded only when they exited (they held the CLI's output pipe). Fixed in a later pull request: the swarm records every process the CLI starts and stops them all before a failed or stopped turn is reported and on shutdown, and a lost CLI is detected on exit. Proven with the fake CLI (kill, Stop, shutdown; an unrelated process survives); live proof pending | diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-process-lineage.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-process-lineage.test.ts new file mode 100644 index 00000000000..900a249afac --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-process-lineage.test.ts @@ -0,0 +1,150 @@ +import { spawn } from "node:child_process"; +import { describe, expect, it } from "vitest"; +import { + LineageState, parseProcStat, parsePsTable, readProcessTable, trackAntigravityProcessLineage, + type LineageEntry, type ProcessTableRead, +} from "./antigravity-process-lineage.js"; + +const entry = (pid: number, ppid: number, pgid: number, started: number, extra: Partial = {}): LineageEntry => + ({ pid, ppid, pgid, sid: null, started, zombie: false, ...extra }); +const pids = (observation: { live: LineageEntry[] }) => observation.live.map(item => item.pid).sort((a, b) => a - b); +const self = () => entry(process.pid, 1, process.pid, 1); +const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } }; +/** A tracker whose first read records `member` and whose later reads come from `later`. */ +const trackWith = (member: LineageEntry, later: () => Promise) => { + let reads = 0; + return trackAntigravityProcessLineage(member.pid, { sampleIntervalMs: 60_000, + readTable: async () => (++reads === 1 ? { entries: [self(), member], unreadable: [] } : later()) }); +}; + +describe("Antigravity process lineage", () => { + it("keeps a helper that leads its own group after the CLI dies and it is re-parented, with its children", () => { + const state = new LineageState(100); + // CLI 100 starts helper shell 200 as its own group leader; 200 starts 201. + expect(pids(state.observe([entry(100, 50, 100, 10), entry(200, 100, 200, 11), entry(201, 200, 200, 12), entry(300, 1, 300, 5)]))).toEqual([100, 200, 201]); + // CLI killed: 200 is re-parented to init; 201 forks 202 after its parent exited. + expect(pids(state.observe([entry(200, 1, 200, 11), entry(202, 1, 200, 13), entry(300, 1, 300, 5)]))).toEqual([200, 202]); + }); + + it("keeps a process in a session a member leads after it left the member's group and its parent exited", () => { + const state = new LineageState(100); + // Helper 200 calls setsid (session and group 200); its wrapper 201 starts a job that moves to group 202. + state.observe([entry(100, 50, 100, 10, { sid: 40 }), entry(200, 100, 200, 11, { sid: 200 }), entry(201, 200, 200, 12, { sid: 200 })]); + // The wrapper exited before the job was ever seen; the job is re-parented to init. + expect(pids(state.observe([entry(200, 100, 200, 11, { sid: 200 }), entry(202, 1, 202, 13, { sid: 200 }), entry(300, 1, 300, 14, { sid: 40 })]))).toEqual([200, 202]); + }); + + it("never claims an unrelated process: same user, earlier start, a reused PID or a reused group id", () => { + const state = new LineageState(100); + state.observe([entry(100, 50, 100, 10), entry(200, 100, 200, 11)]); + // 200 exits; an unrelated process later reuses PID 200 and leads group 200. + expect(pids(state.observe([entry(100, 50, 100, 10), entry(200, 1, 200, 99), entry(201, 200, 200, 100), entry(400, 50, 400, 9)]))).toEqual([100]); + // A process that started before the CLI is never its child. + expect(pids(state.observe([entry(100, 50, 100, 10), entry(500, 100, 500, 3)]))).toEqual([100]); + }); + + it("drops zombies and a root whose PID now names another process", () => { + const state = new LineageState(100); + state.observe([entry(100, 50, 100, 10), entry(200, 100, 200, 11)]); + expect(pids(state.observe([entry(100, 50, 100, 10), entry(200, 100, 200, 11, { zombie: true })]))).toEqual([100]); + expect(pids(state.observe([entry(100, 50, 100, 77)]))).toEqual([]); + }); + + it("keeps a member whose details could not be read unresolved instead of treating it as gone", () => { + const state = new LineageState(100); + state.observe([entry(100, 50, 100, 10), entry(200, 100, 200, 11)]); + expect(state.observe({ entries: [], unreadable: [200] })).toEqual({ live: [], unresolved: [200] }); + expect(state.observe({ entries: [], unreadable: [] })).toEqual({ live: [], unresolved: [] }); + }); + + it("parses macOS ps output: live, zombie and unreadable rows; rejects output that is not a process table", () => { + const read = parsePsTable([ + " 100 1 100 Ss Tue Nov 24 10:00:00 2026", + " 200 100 200 Z Tue Nov 24 10:00:01 2026", + " 300 100 200 S+ garbled", + "", + ].join("\n")); + expect(read.entries).toEqual([ + { pid: 100, ppid: 1, pgid: 100, sid: null, started: Date.UTC(2026, 10, 24, 10, 0, 0), zombie: false }, + { pid: 200, ppid: 100, pgid: 200, sid: null, started: Date.UTC(2026, 10, 24, 10, 0, 1), zombie: true }, + ]); + expect(read.unreadable).toEqual([300]); + expect(parsePsTable("")).toEqual({ entries: [], unreadable: [] }); + expect(() => parsePsTable("PID PPID PGID STAT STARTED\n")).toThrow(/Unexpected/); + }); + + it("parses Linux /proc stat lines, including a command name with spaces and parentheses", () => { + const fields = ["S", "100", "200", "300", ...Array.from({ length: 15 }, () => "0"), "123456", "0"]; + expect(parseProcStat(42, `42 (a (b) c) ${fields.join(" ")}`)).toEqual({ pid: 42, ppid: 100, pgid: 200, sid: 300, started: 123456, zombie: false }); + expect(parseProcStat(42, "42 (x) Z")).toBeNull(); + }); + + it("reads this host's process table, including this process with its parent", async () => { + const table = await readProcessTable(); + const current = table.entries.find(item => item.pid === process.pid); + expect(current).toMatchObject({ ppid: process.ppid, zombie: false }); + expect(Number.isSafeInteger(current?.started)).toBe(true); + }); + + it.each<[string, () => Promise]>([ + ["a failed read", async () => { throw new Error("unavailable"); }], + ["an empty read", async () => ({ entries: [], unreadable: [] })], + ["a read that does not list this process", async () => ({ entries: [entry(4, 1, 4, 1)], unreadable: [] })], + ["a read where the recorded member is unreadable", async () => ({ entries: [self()], unreadable: [999_999] })], + ])("never proves the lineage gone from %s, and a later call tries again", async (_name, bad) => { + let read = bad; + const lineage = trackWith(entry(999_999, 1, 999_999, 2), () => read()); + await new Promise(resolve => setTimeout(resolve, 20)); + await expect(lineage.terminate()).rejects.toThrow(/could not be stopped/); + read = async () => ({ entries: [self()], unreadable: [] }); + await expect(lineage.terminate()).resolves.toBeUndefined(); + }, 10_000); + + it("signals the members it found even when that read was slower than the whole deadline", async () => { + const helper = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { detached: true, stdio: "ignore" }); + try { + let reads = 0; + const lineage = trackAntigravityProcessLineage(helper.pid, { sampleIntervalMs: 60_000, readTable: async () => { + const table = await readProcessTable(); + if (++reads === 2) await new Promise(resolve => setTimeout(resolve, 1_700)); + return table; + } }); + await new Promise(resolve => setTimeout(resolve, 200)); + await lineage.terminate(); + expect(alive(helper.pid!)).toBe(false); + } finally { try { process.kill(helper.pid!, "SIGKILL"); } catch { /* gone */ } } + }, 10_000); + + it("never signals a recorded PID whose start time no longer matches", async () => { + const unrelated = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { detached: true, stdio: "ignore" }); + try { + await new Promise(resolve => setTimeout(resolve, 100)); + const real = (await readProcessTable()).entries.find(item => item.pid === unrelated.pid)!; + // The tracker's reads say an older process held this PID; the re-read before the signal disagrees. + let reads = 0; + const older = { ...real, started: real.started - 5_000 }; + const lineage = trackAntigravityProcessLineage(unrelated.pid, { sampleIntervalMs: 60_000, + readTable: async () => ({ entries: [self(), ...(++reads <= 2 ? [older] : [])], unreadable: [] }) }); + await new Promise(resolve => setTimeout(resolve, 20)); + await lineage.terminate(); + expect(alive(unrelated.pid!)).toBe(true); + } finally { try { process.kill(unrelated.pid!, "SIGKILL"); } catch { /* gone */ } } + }); + + it("stops a detached grandchild of a dead root and leaves an unrelated process running", async () => { + const unrelated = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { detached: true, stdio: "ignore" }); + // The root starts a detached grandchild (its own group) and exits soon after. + const root = spawn(process.execPath, ["-e", `const c = require("node:child_process").spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { detached: true, stdio: "ignore" }); console.log(c.pid); setTimeout(() => process.exit(0), 300);`], { stdio: ["ignore", "pipe", "ignore"] }); + const lineage = trackAntigravityProcessLineage(root.pid, { sampleIntervalMs: 20 }); + const grandchild = await new Promise(resolve => root.stdout.once("data", chunk => resolve(Number(String(chunk).trim())))); + await new Promise(resolve => root.once("exit", resolve)); + try { + expect(alive(grandchild)).toBe(true); + await lineage.terminate(); + expect(alive(grandchild)).toBe(false); + expect(alive(unrelated.pid!)).toBe(true); + } finally { + for (const pid of [grandchild, unrelated.pid!]) { try { process.kill(pid, "SIGKILL"); } catch { /* gone */ } } + } + }); +}); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-process-lineage.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-process-lineage.ts new file mode 100644 index 00000000000..ddbe65e6fdf --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-process-lineage.ts @@ -0,0 +1,238 @@ +import { execFile } from "node:child_process"; +import { readdir, readFile } from "node:fs/promises"; + +/** + * Every process the swarm route's `agy acp` launcher and its helpers start, + * recorded while they are still visible, so they can all be stopped when the + * CLI exits for any reason. + * + * The CLI starts each helper shell command as its own process-group leader. + * When the CLI dies those commands are re-parented, so signalling the + * launcher's group (retireAntigravityProcess) does not reach them. + * + * runnerd's LineageTracker (runner-core process_lineage.rs) records the whole + * sidecar's lineage and stops all of it, the sidecar included, when the + * sidecar is torn down. It has no operation for one subtree, and the swarm + * needs this subtree stopped while the sidecar keeps serving the run: before a + * lost, stopped or timed-out swarm turn is reported. This tracker applies + * runnerd's membership rules to the CLI's subtree only: + * - a process belongs when its parent belongs (and started no later than it); + * - or when it is in a group or session a member leads and started no earlier + * than that leader (sessions on Linux; macOS `ps` reports no session id); + * - identity is PID plus start time, re-read immediately before each signal, + * so a reused PID is never signalled; + * - a recorded member whose details cannot be read stays unresolved, and a + * table read that does not list this process is rejected: neither proves + * the lineage gone; + * - membership never depends on a command name, so other `agy` processes of + * the same user are never touched. + */ +export interface LineageEntry { pid: number; ppid: number; pgid: number; sid: number | null; started: number; zombie: boolean } + +/** One read of the process table: readable entries, and PIDs that exist but could not be read. */ +export interface ProcessTableRead { entries: LineageEntry[]; unreadable: number[] } + +export interface LineageObservation { live: LineageEntry[]; unresolved: number[] } + +export class LineageState { + readonly #members = new Map(); + readonly #groups = new Map(); + readonly #sessions = new Map(); + readonly #root: { pid: number; started: number | null }; + + constructor(rootPid: number) { this.#root = { pid: rootPid, started: null }; } + + /** Updates membership from one table read, applied in the order reads were taken. */ + observe(read: ProcessTableRead | readonly LineageEntry[]): LineageObservation { + const { entries, unreadable } = Array.isArray(read) ? { entries: read as readonly LineageEntry[], unreadable: [] as number[] } : read as ProcessTableRead; + const byPid = new Map(entries.map(entry => [entry.pid, entry])); + const unknown = new Set(unreadable); + const root = byPid.get(this.#root.pid); + if (root && !root.zombie && (this.#root.started === null || this.#root.started === root.started)) { + this.#root.started = root.started; + this.#members.set(root.pid, root.started); + } + // A PID that now names a different process is forgotten first, so it can + // never admit that process's children. Members that merely exited are + // forgotten only after admission: a child whose parent exited since the + // last read is still found through that parent's recorded group or session. + for (const records of [this.#members, this.#groups, this.#sessions]) { + for (const [id, started] of records) { + const current = byPid.get(id); + if (current && current.started !== started) records.delete(id); + } + } + const record = (entry: LineageEntry) => { + this.#members.set(entry.pid, entry.started); + if (entry.pgid === entry.pid) this.#groups.set(entry.pid, entry.started); + if (entry.sid === entry.pid) this.#sessions.set(entry.pid, entry.started); + }; + for (let changed = true; changed;) { + changed = false; + for (const entry of entries) { + if (entry.zombie || this.#members.has(entry.pid) || entry.pid <= 1 || entry.pid === process.pid) continue; + const leader = (records: Map, id: number | null) => id !== null && (records.get(id) ?? Infinity) <= entry.started; + if (leader(this.#members, entry.ppid) || leader(this.#groups, entry.pgid) || leader(this.#sessions, entry.sid)) { + record(entry); + changed = true; + } + } + } + const live: LineageEntry[] = []; + const unresolved: number[] = []; + for (const [pid, started] of this.#members) { + const entry = byPid.get(pid); + if (!entry) { + // Its exit is proven only when the PID is absent, not when it is unreadable. + if (unknown.has(pid)) unresolved.push(pid); else this.#members.delete(pid); + continue; + } + if (entry.started !== started || entry.zombie) { this.#members.delete(pid); continue; } + record(entry); + live.push(entry); + } + return { live, unresolved }; + } +} + +/** `/bin/ps -A -o pid=,ppid=,pgid=,stat=,lstart=` output, read with LANG=C and TZ=UTC. */ +export function parsePsTable(output: string): ProcessTableRead { + const entries: LineageEntry[] = []; + const unreadable: number[] = []; + for (const line of output.split("\n")) { + if (!line.trim()) continue; + const [pid, ppid, pgid, stat, ...start] = line.trim().split(/\s+/); + if (!pid || !/^\d+$/.test(pid)) throw new Error("Unexpected process table output"); + const started = start.length === 5 ? Date.parse(`${start.join(" ")} UTC`) : Number.NaN; + if (!/^\d+$/.test(ppid ?? "") || !/^\d+$/.test(pgid ?? "") || !/^[A-Za-z+<>NLsWX-]+$/.test(stat ?? "") || !Number.isFinite(started)) { + unreadable.push(Number(pid)); + continue; + } + entries.push({ pid: Number(pid), ppid: Number(ppid), pgid: Number(pgid), sid: null, started, zombie: stat!.startsWith("Z") }); + } + return { entries, unreadable }; +} + +/** `/proc//stat` content: state ppid pgrp session ... starttime follow the command name. */ +export function parseProcStat(pid: number, stat: string): LineageEntry | null { + const fields = stat.slice(stat.lastIndexOf(")") + 2).trim().split(" "); + const [ppid, pgid, sid, started] = [fields[1], fields[2], fields[3], fields[19]].map(Number); + if (![ppid, pgid, sid, started].every(Number.isSafeInteger) || !fields[0]) return null; + return { pid, ppid: ppid!, pgid: pgid!, sid: sid!, started: started!, zombie: fields[0] === "Z" || fields[0] === "X" }; +} + +async function readLinuxEntry(pid: number): Promise { + try { return parseProcStat(pid, await readFile(`/proc/${pid}/stat`, "utf8")) ?? "unreadable"; } + catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" || (error as NodeJS.ErrnoException).code === "ESRCH" ? "gone" : "unreadable"; } +} + +function runPs(args: string[]): Promise { + return new Promise((resolve, reject) => execFile("/bin/ps", args, { + encoding: "utf8", timeout: 2_000, maxBuffer: 8 * 1024 * 1024, env: { PATH: "/usr/bin:/bin", LANG: "C", LC_ALL: "C", TZ: "UTC" }, + }, (error, stdout) => error ? reject(error) : resolve(stdout))); +} + +/** One read of this host's process table: /proc on Linux, /bin/ps on macOS. Numbers only; never arguments or environment. */ +export async function readProcessTable(platform: NodeJS.Platform = process.platform): Promise { + let read: ProcessTableRead; + if (platform === "linux") { + const pids = (await readdir("/proc")).filter(name => /^\d+$/.test(name)).map(Number); + const rows = await Promise.all(pids.map(async pid => ({ pid, row: await readLinuxEntry(pid) }))); + read = { + entries: rows.flatMap(({ row }) => typeof row === "object" ? [row] : []), + unreadable: rows.flatMap(({ pid, row }) => row === "unreadable" ? [pid] : []), + }; + } else if (platform === "darwin") { + read = parsePsTable(await runPs(["-A", "-o", "pid=,ppid=,pgid=,stat=,lstart="])); + } else { + throw new Error("Antigravity process lineage is not supported on this platform"); + } + return assertCompleteRead(read); +} + +/** A read that does not list this very process cannot prove anything absent. */ +function assertCompleteRead(read: ProcessTableRead): ProcessTableRead { + if (!read.entries.some(entry => entry.pid === process.pid)) throw new Error("The process table read is incomplete"); + return read; +} + +/** The current start time of each PID still alive and readable (one `ps` for all of them on macOS). */ +async function currentStarts(pids: readonly number[]): Promise> { + const starts = new Map(); + if (pids.length === 0) return starts; + if (process.platform === "linux") { + for (const pid of pids) { + const row = await readLinuxEntry(pid); + if (typeof row === "object" && !row.zombie) starts.set(pid, row.started); + } + return starts; + } + const output = await runPs(["-o", "pid=,ppid=,pgid=,stat=,lstart=", "-p", pids.join(",")]).catch(() => ""); + let read: ProcessTableRead = { entries: [], unreadable: [] }; + try { read = parsePsTable(output); } catch { /* nothing is signalled */ } + for (const entry of read.entries) if (!entry.zombie) starts.set(entry.pid, entry.started); + return starts; +} + +export interface AntigravityProcessLineage { + /** + * Stops every recorded process that is still alive and proves none remain. + * A proven result is kept; a call after a failed one tries again. + */ + terminate(): Promise; +} + +const DEFAULT_SAMPLE_INTERVAL_MS = 200; +const TERMINATE_DEADLINE_MS = 1_500; + +/** Records the lineage of `rootPid` at once, then every `sampleIntervalMs` until terminate(). */ +export function trackAntigravityProcessLineage(rootPid: number | undefined, options: { + sampleIntervalMs?: number; readTable?: () => Promise; +} = {}): AntigravityProcessLineage { + if (rootPid === undefined || process.platform === "win32") return { terminate: async () => {} }; + const readTable = options.readTable ?? (() => readProcessTable()); + const state = new LineageState(rootPid); + let stopped = false; + let timer: ReturnType | undefined; + // Reads are applied in the order they were taken, never two at once. + let reading: Promise = Promise.resolve(); + const sample = (): Promise => { + const next = reading.catch(() => undefined).then(() => readTable()).then(read => state.observe(assertCompleteRead(read))); + reading = next; + return next; + }; + const loop = () => { + if (stopped) return; + void sample().catch(() => undefined).finally(() => { + if (stopped) return; + timer = setTimeout(loop, options.sampleIntervalMs ?? DEFAULT_SAMPLE_INTERVAL_MS); + timer.unref?.(); + }); + }; + loop(); + let termination: Promise | null = null; + return { + terminate: () => termination ??= (async () => { + stopped = true; + if (timer) clearTimeout(timer); + const deadline = Date.now() + TERMINATE_DEADLINE_MS; + for (let round = 0; ; round++) { + // A fresh read each round: a member that forked meanwhile is found by its parent, group or session. + // A failed read proves nothing, so it is retried until the deadline. + const observed = await sample().catch(() => null); + if (observed && observed.live.length === 0 && observed.unresolved.length === 0) return; + // The first round signals what it found even when that read was slow; later rounds keep the deadline. + if (round > 0 && Date.now() >= deadline) throw new Error("Antigravity helper processes could not be stopped"); + // Re-read the identities just before the signals: a PID reused since the read is never signalled. + const live = observed?.live ?? []; + const starts = await currentStarts(live.map(entry => entry.pid)); + for (const entry of live) { + if (starts.get(entry.pid) !== entry.started) continue; + try { process.kill(entry.pid, "SIGKILL"); } + catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; } + } + await new Promise(resolve => setTimeout(resolve, 50)); + } + })().catch(error => { termination = null; throw error; }), + }; +} diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-process.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-process.ts index 3039be5e7a3..668b0906baa 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-process.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-process.ts @@ -1,6 +1,7 @@ -import { execFile, type ChildProcessWithoutNullStreams } from "node:child_process"; +import type { ChildProcessWithoutNullStreams } from "node:child_process"; import { lstat, mkdir, realpath } from "node:fs/promises"; import { isAbsolute, join, resolve } from "node:path"; +import { readProcessTable } from "./antigravity-process-lineage.js"; export async function checkAntigravityPrivateHome(home: string): Promise { if (!isAbsolute(home) || home.includes("\0") || resolve(home) !== home || await realpath(home) !== home) throw new Error("Invalid Antigravity private home"); @@ -44,12 +45,9 @@ export async function retireAntigravityProcess(child: ChildProcessWithoutNullStr else if (code === "EPERM" && process.platform === "darwin") { // Darwin reports EPERM for some groups containing only orphaned // zombies. Read numeric state only; never process arguments/env. - const output = await new Promise((resolve, reject) => execFile("/bin/ps", ["-axo", "pid=,pgid=,stat="], { - encoding: "utf8", timeout: 1_000, maxBuffer: 1024 * 1024, env: { PATH: "/usr/bin:/bin", LANG: "C" }, - }, (error, stdout) => error ? reject(error) : resolve(stdout))); - const rows = output.trim().split("\n").filter(Boolean).map(line => line.trim().split(/\s+/)); - if (rows.some(row => row.length !== 3 || !/^\d+$/.test(row[0]!) || !/^\d+$/.test(row[1]!) || !/^[A-Za-z+<>NLsWX-]+$/.test(row[2]!))) throw new Error("Antigravity process retirement could not be confirmed"); - groupAlive = rows.some(row => Number(row[1]) === child.pid && !row[2]!.startsWith("Z")); + const table = await readProcessTable("darwin").catch(() => null); + if (!table || table.unreadable.length > 0) throw new Error("Antigravity process retirement could not be confirmed"); + groupAlive = table.entries.some(entry => entry.pgid === child.pid && !entry.zombie); } else throw error; } } diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts index 4dbe433b347..6e0555229cf 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts @@ -6,6 +6,7 @@ import { afterEach, describe, expect, it } from "vitest"; import type { AcpRuntimeEvent } from "acpx/runtime"; import { ANTIGRAVITY_SWARM_INSTRUCTIONS, antigravityCliAccountMatch, antigravitySwarmPaperclipTool, openAntigravitySwarmRuntime, type AntigravitySwarmStage } from "./antigravity-swarm-runtime.js"; import { acpxProfileActivity } from "./profile-activity.js"; +import { readProcessTable } from "./antigravity-process-lineage.js"; import { persistedAcpxTurnUsage } from "./usage-accounting.js"; import { antigravityAccountDigest } from "./antigravity-swarm-route.js"; import type { AcpxRuntimePortOpenOptions } from "./runtime-host.js"; @@ -444,6 +445,97 @@ describe("Antigravity CLI swarm runtime", () => { expect(alive(worker)).toBe(false); }); + describe("helpers that lead their own process groups", () => { + const HELPER_DELAY_MS = 2_500; + const waitFor = async (check: () => boolean, timeoutMs = 5_000) => { + const deadline = Date.now() + timeoutMs; + while (!check()) { if (Date.now() > deadline) throw new Error("timed out"); await new Promise(resolve => setTimeout(resolve, 10)); } + }; + const siblings: number[] = []; + afterEach(() => { for (const pid of siblings.splice(0)) { try { process.kill(pid, "SIGKILL"); } catch { /* gone */ } } }); + + async function startOrphanSwarm(dependencies: Parameters[1] = {}, helperDelayMs = HELPER_DELAY_MS) { + const context = setup("orphan-helpers"); + const spawnChild = context.options.command.spawn; + let cliPid = 0; + (context.options.command as { spawn: typeof spawnChild }).spawn = (args, spawnOptions = {}, lifetime) => { + // setup() builds the fake CLI's environment from process.env at spawn time. + process.env.FAKE_AGY_HELPER_DELAY_MS = String(helperDelayMs); + let child: ReturnType; + try { child = spawnChild(args, spawnOptions, lifetime); } finally { delete process.env.FAKE_AGY_HELPER_DELAY_MS; } + cliPid = child.pid!; + return child; + }; + // An unrelated process of the same OS user, not started by this run's CLI. + const sibling = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { detached: true, stdio: "ignore" }); + siblings.push(sibling.pid!); + const runtime = await openAntigravitySwarmRuntime(context.options, { lineageSampleIntervalMs: 20, cancelGraceMs: 500, ...dependencies }); + const turn = runtime.startTurn({ text: envelope(SWARM_REQUEST), requestId: "run-1:turn-1" }); + void (async () => { for await (const _event of turn.events) { /* drain */ } })(); + await waitFor(() => existsSync(context.workerPidFile) && readFileSync(context.workerPidFile, "utf8").length > 0); + const helper = Number(readFileSync(context.workerPidFile, "utf8")); + siblings.push(helper); // cleaned up after the test if it ever survives + // Let the lineage record the helper while the CLI still runs. + await new Promise(resolve => setTimeout(resolve, 150)); + expect(alive(helper)).toBe(true); + return { ...context, runtime, turn, helper, sibling: sibling.pid!, cliPid, late: join(context.cwd, "late.txt") }; + } + const settledAfterHelperDeadline = () => new Promise(resolve => setTimeout(resolve, HELPER_DELAY_MS + 500)); + + it("stops them before reporting a killed CLI, without waiting on the pipe they hold, and leaves other processes alone", async () => { + const run = await startOrphanSwarm(); + process.kill(run.cliPid, "SIGKILL"); + const result = await run.turn.result; + // The helper is already gone when the failure is reported. + expect(alive(run.helper)).toBe(false); + expect(result).toMatchObject({ status: "failed", error: { code: "ACPX_PROVIDER_PROCESS_LOST", retryable: true } }); + await run.runtime.close({ reason: "done" }); + await settledAfterHelperDeadline(); + expect(existsSync(run.late)).toBe(false); + expect(alive(run.sibling)).toBe(true); + }); + + it("does not report a recoverable failure while it cannot prove the helpers stopped, and stops them on a later close", async () => { + let tableReadable = true; + const run = await startOrphanSwarm({ readProcessTable: async () => { + if (!tableReadable) throw new Error("process table unavailable"); + return readProcessTable(); + } }, 60_000); + tableReadable = false; + process.kill(run.cliPid, "SIGKILL"); + expect(await run.turn.result).toMatchObject({ status: "failed", error: { code: "ANTIGRAVITY_SWARM_FAILED", retryable: false, + message: expect.stringMatching(/could not confirm that all of its helpers stopped/) } }); + // The helper outlives the failed cleanup, so the later close is what stops it. + expect(alive(run.helper)).toBe(true); + tableReadable = true; + await run.runtime.close({ reason: "done" }); + expect(alive(run.helper)).toBe(false); + expect(existsSync(run.late)).toBe(false); + expect(alive(run.sibling)).toBe(true); + }, 20_000); + + it("stops them on Stop before the stopped turn is reported", async () => { + const run = await startOrphanSwarm(); + await run.turn.cancel({ reason: "Stop" }); + expect(await run.turn.result).toMatchObject({ status: "cancelled" }); + expect(alive(run.helper)).toBe(false); + await run.runtime.close({ reason: "done" }); + await settledAfterHelperDeadline(); + expect(existsSync(run.late)).toBe(false); + expect(alive(run.sibling)).toBe(true); + }); + + it("stops them when the runner shuts the runtime down mid-swarm", async () => { + const run = await startOrphanSwarm(); + await run.runtime.close({ reason: "shutdown" }); + expect(alive(run.helper)).toBe(false); + expect(alive(run.cliPid)).toBe(false); + await settledAfterHelperDeadline(); + expect(existsSync(run.late)).toBe(false); + expect(alive(run.sibling)).toBe(true); + }); + }); + const trackPid = (options: AcpxRuntimePortOpenOptions) => { const tracked = { pid: 0 }; const spawnChild = options.command.spawn; diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts index f39bdd99a19..4c89d8e28f5 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts @@ -5,6 +5,7 @@ import type { AcpRuntimeEvent, AcpRuntimeTurnResult } from "acpx/runtime"; import { userInfo } from "node:os"; import { AntigravitySavedStateIncompatibleError } from "./antigravity-admission.js"; import { retireAntigravityProcess } from "./antigravity-process.js"; +import { trackAntigravityProcessLineage, type ProcessTableRead } from "./antigravity-process-lineage.js"; import { antigravityOutsideChange } from "./antigravity-swarm-paths.js"; import { antigravityAccountDigest, antigravitySwarmChannelLabel, antigravitySwarmLogFile } from "./antigravity-swarm-route.js"; import { @@ -49,6 +50,9 @@ const DEFAULT_REQUEST_TIMEOUT_MS = 60_000; const DEFAULT_HELPER_WAIT_TIMEOUT_MS = 20 * 60_000; const DEFAULT_CANCEL_GRACE_MS = 5_000; const READBACK_TIMEOUT_MS = 5_000; +const EXIT_OUTPUT_GRACE_MS = 200; +const RETIREMENT_ATTEMPTS = 3; +const CLEANUP_UNPROVEN_MESSAGE = "The swarm stopped, but Paperclip could not confirm that all of its helpers stopped, so it did not continue the task on its own. Files the helpers wrote stay in the task folder. Check them before you send /swarm again."; const SNAPSHOT_LIMIT = 20_000; const SKIPPED_DIRECTORIES = new Set([".git", "node_modules", ".venv", "__pycache__"]); // The CLI's sandbox refusing a helper's change outside the task folder. A denial @@ -69,6 +73,10 @@ export interface AntigravitySwarmRuntimeDependencies { /** Test seam: runs at every await point between launch and settle. */ onStage?: (stage: AntigravitySwarmStage) => void | Promise; awaitProviderOwnership?: (child: ChildProcess) => Promise; + /** Test seam: how often the CLI's process lineage is recorded. */ + lineageSampleIntervalMs?: number; + /** Test seam: reads the host's process table for the lineage. */ + readProcessTable?: () => Promise; } type Json = Record; @@ -106,7 +114,14 @@ class Connection { onLost: () => void = () => {}; constructor(readonly child: ChildProcessWithoutNullStreams) { - this.exited = new Promise(resolve => child.once("close", () => resolve())); + // Exit, not close: helpers the CLI started inherit its output pipe and can + // hold it open long after the CLI died. Output already written is read for + // a short moment after exit; the lost CLI cannot answer anything later. + this.exited = new Promise(resolve => child.once("exit", () => { + if (child.stdout.readableEnded || child.stdout.destroyed) { resolve(); return; } + const timer = setTimeout(resolve, EXIT_OUTPUT_GRACE_MS); + child.stdout.once("close", () => { clearTimeout(timer); resolve(); }); + })); child.stdout.setEncoding("utf8"); child.stdout.on("data", (chunk: string) => { this.#buffer += chunk; @@ -366,8 +381,15 @@ export async function openAntigravitySwarmRuntime( ? { credentialFenceFds: options.credentialFenceFds, activateCredentialFenceOwner: options.activateCredentialFenceOwner } : undefined; const child = options.command.spawn([], { cwd: options.cwd, env: { ...options.launchEnvironment } }, lifetime) as ChildProcessWithoutNullStreams; const connection = new Connection(child); + // Helpers lead their own process groups, so stopping the launcher's group is + // not enough: everything the CLI started is recorded while it runs and is + // stopped with it (see antigravity-process-lineage.ts). + const lineage = trackAntigravityProcessLineage(child.pid, { sampleIntervalMs: dependencies.lineageSampleIntervalMs, readTable: dependencies.readProcessTable }); let retirement: Promise | null = null; - const retire = () => retirement ??= retireAntigravityProcess(child, connection.exited); + // Only a proven retirement is kept: after a failure, the next call tries again. + const retire = () => retirement ??= retireAntigravityProcess(child, connection.exited) + .finally(() => lineage.terminate()) + .catch((error: unknown) => { retirement = null; throw error; }); let updateListener: ((params: Json) => void) | null = null; let readback: (() => void) | null = null; @@ -724,7 +746,19 @@ export async function openAntigravitySwarmRuntime( active = turn; const onAbort = () => { void turn.cancel(); }; input.signal?.addEventListener("abort", onAbort, { once: true }); - turn.result = runTurn(input, events, markStarted).finally(() => { + // A swarm turn is the port's only turn. Unless it completed, the CLI and + // every process it started are stopped before the outcome is reported, so + // nothing keeps writing in the task folder and recovery never races them. + turn.result = runTurn(input, events, markStarted).then(async result => { + if (result.status === "completed") return result; + for (let attempt = 1; ; attempt++) { + try { await retire(); return result; } catch { + // Without proof that every helper stopped, Paperclip must not continue + // the task on its own in the same folder: report a failure it does not recover. + if (attempt >= RETIREMENT_ATTEMPTS) return failed("ANTIGRAVITY_SWARM_FAILED", CLEANUP_UNPROVEN_MESSAGE); + } + } + }).finally(() => { markStarted(); events.end(); input.signal?.removeEventListener("abort", onAbort); diff --git a/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs b/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs index 4566aac14b8..18eb3b9a5cf 100644 --- a/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs +++ b/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs @@ -12,6 +12,10 @@ // cancel helpers keep running (a real child process) until session/cancel; the CLI // streams a token count, then answers the stopped prompt with its usage so far // die the CLI streams a token count, then exits in the middle of the swarm +// orphan-helpers a helper runs as its own process-group leader holding the CLI's output +// pipe (as the real CLI's helper shells do) and writes late.txt in the +// workspace after FAKE_AGY_HELPER_DELAY_MS; the CLI never stops it itself. +// The test kills the CLI, stops the turn or closes the runtime. // refusal the provider refusal arrives as ordinary text with end_turn // quota the 429 quota refusal, as seen live on 2026-11-24 // wrong-version | no-auto | wrong-mode | wrong-model receipt mismatches @@ -185,6 +189,14 @@ async function prompt(id, params) { } // The terminal hint arrives in pieces, as recorded live: the hint complete without its period, then the period alone. for (const chunk of ["I have configured and launched the swarm.\n", "\nRun /swarm board (default shortcut alt+s) to open the live board", "."]) say(chunk); + if (scenario === "orphan-helpers") { + const late = join(state.cwd, "late.txt"); + const helper = spawn(process.execPath, ["-e", `setTimeout(() => require("node:fs").writeFileSync(${JSON.stringify(late)}, "late"), ${Number(process.env.FAKE_AGY_HELPER_DELAY_MS ?? 3000)})`], + { detached: true, stdio: ["ignore", "inherit", "inherit"] }); + if (process.env.FAKE_AGY_WORKER_PID_FILE) writeFileSync(process.env.FAKE_AGY_WORKER_PID_FILE, String(helper.pid)); + if (!state.cancelled) await new Promise(resolve => { state.cancel = resolve; }); + return write({ jsonrpc: "2.0", id, result: { stopReason: "cancelled", usage: stoppedUsage } }); + } if (scenario === "cancel" || scenario === "die") { update(state.sessionId, { sessionUpdate: "usage_update", used: 52000, size: 1048576, _meta: { usage: streamedUsage } }); // A helper is a real descendant in the CLI's process group.