Skip to content

armgit / pibot

Public Imported from GitHub
0

Open-source, local-first AI agent team for your desktop: multi-agent group chats, computer use, browser, MCP, routines and approvals. macOS, Windows, Linux + Android. Built on pi.

fix(execution): Windows command cleanup survives a stalled brain and keeps to its own tree

leen.zhou5244b6061599
diff --git a/packages/execution/src/command/background/processes.ts b/packages/execution/src/command/background/processes.ts
index 82121d3..13be394 100644
--- a/packages/execution/src/command/background/processes.ts
+++ b/packages/execution/src/command/background/processes.ts
@@ -23,6 +23,19 @@ function createdAtOrAfter(row: ProcessRow, earliest: bigint) {
}
}
+/**
+ * Windows: ParentProcessId keeps naming a creator after it exits, and that PID may now belong to
+ * another process. A real child started after its parent; an older one is not ours to kill.
+ */
+function startedAfter(row: ProcessRow, parent: ProcessRow) {
+ try {
+ return BigInt(row.started) >= BigInt(parent.started);
+ } catch {
+ // An unreadable time cannot prove the relation, and this set is killed.
+ return false;
+ }
+}
+
/**
* Why a process tree did not provably exit: kept as a class so the cleanup retry can tell an
* unconfirmed tree (processes remain) from a failed snapshot (existence unknown).
@@ -147,11 +160,13 @@ export function createBackgroundProcesses(deps: BackgroundDependencies) {
// Descendants started by the recorded processes after the last record.
for (let grew = true; grew; ) {
grew = false;
- for (const row of rows)
- if (!found.has(row.pid) && found.has(row.parent)) {
- found.set(row.pid, row);
- grew = true;
- }
+ for (const row of rows) {
+ const parent = found.get(row.parent);
+ if (found.has(row.pid) || !parent) continue;
+ if (platform === "win32" && !startedAfter(row, parent)) continue;
+ found.set(row.pid, row);
+ grew = true;
+ }
}
return [...found.values()];
};
diff --git a/packages/execution/src/command/process-tree.ts b/packages/execution/src/command/process-tree.ts
index c346253..02db10b 100644
--- a/packages/execution/src/command/process-tree.ts
+++ b/packages/execution/src/command/process-tree.ts
@@ -1,4 +1,5 @@
import { spawn } from "node:child_process";
+import { stallTolerantTimeout } from "../core/deadline.ts";
import { ExecError } from "../core/types.ts";
export type ProcessRow = { pid: number; parent: number; group: number; started: string };
@@ -17,6 +18,13 @@ const POLL_FAILURE_LIMIT = 3;
// cleanup never learns about. Time counts even before the failure limit is reached (W6-1 review):
// two timed-out snapshots put the real blind window at roughly 11s, not the 6s threshold alone.
const POLL_BLIND_MS = 6_000;
+/** .NET ticks (100 ns since 0001-01-01) of the Unix epoch, the unit of Windows CreationDate. */
+const EPOCH_TICKS = 621355968000000000n;
+
+function ticks(value: string | undefined) {
+ if (value === undefined || !/^\d+$/.test(value)) return undefined;
+ return BigInt(value);
+}
/** Compare ps start times as well as ancestry to avoid retaining stale process identities. */
export async function snapshot(
@@ -42,7 +50,9 @@ export async function snapshot(
windowsHide: true,
});
let text = "";
- const timer = setTimeout(
+ // A stalled brain must not turn a finished snapshot into a timeout (Windows 2026-11-21: a
+ // ~9 s stall failed a worktree add's cleanup as unconfirmed although nothing was left).
+ const timer = stallTolerantTimeout(
() => {
ps.kill("SIGKILL");
reject(new ExecError("command_failed", "process_snapshot_timeout"));
@@ -59,11 +69,11 @@ export async function snapshot(
}
});
ps.once("error", () => {
- clearTimeout(timer);
+ timer.clear();
reject(new ExecError("command_failed", "process_snapshot_failed"));
});
ps.once("close", (code) => {
- clearTimeout(timer);
+ timer.clear();
if (code !== 0) return reject(new ExecError("command_failed", "process_snapshot_failed"));
const rows: ProcessRow[] = [];
for (const line of text.split("\n")) {
@@ -90,6 +100,9 @@ export function createTreeState(root: number, platform: NodeJS.Platform, spawned
const known = new Map<number, string>();
let firstSnapshot = true;
let rootStarted: string | undefined;
+ // Windows: the latest creation time a child of the exited root can have. Its PID may be reused
+ // by an unrelated process whose children then name the same parent; those start later.
+ let rootEnded: bigint | undefined;
return {
get rootStarted() {
return rootStarted;
@@ -101,6 +114,13 @@ export function createTreeState(root: number, platform: NodeJS.Platform, spawned
firstSnapshot = false;
}
const rootReused = live.has(root) && live.get(root)?.started !== rootStarted;
+ if (platform === "win32" && rootEnded === undefined && (rootReused || !live.has(root))) {
+ // The update runs after the snapshot was read, so "now" is no earlier than the exit; a
+ // reusing process was created after the root ended.
+ const now = BigInt(Date.now()) * 10_000n + EPOCH_TICKS;
+ const reuser = rootReused ? ticks(live.get(root)?.started) : undefined;
+ rootEnded = reuser !== undefined && reuser < now ? reuser : now;
+ }
for (const [pid, started] of known) if (live.get(pid)?.started !== started) known.delete(pid);
const children = new Map<number, ProcessRow[]>();
for (const row of rows) {
@@ -117,11 +137,12 @@ export function createTreeState(root: number, platform: NodeJS.Platform, spawned
if (known.has(row.pid)) continue;
if (platform === "win32") {
const creator = known.get(row.parent) ?? rootStarted;
- const earliest = creator
- ? BigInt(creator)
- : BigInt(spawnedAt) * 10_000n + 621355968000000000n;
+ const earliest = creator ? BigInt(creator) : BigInt(spawnedAt) * 10_000n + EPOCH_TICKS;
// ParentProcessId can refer to a recycled PID: older orphans are not our descendants.
if (BigInt(row.started) < earliest) continue;
+ // Nor are children started after the root ended, by whatever reused its PID.
+ if (row.parent === root && rootEnded !== undefined && BigInt(row.started) > rootEnded)
+ continue;
}
known.set(row.pid, row.started);
queue.push(row.pid);
@@ -160,6 +181,11 @@ export function trackProcessTree(
});
return scanning;
};
+ // A scan already running may have read the table before the exit or kill it must confirm.
+ const fresh = async () => {
+ await scanning?.catch(() => {});
+ return scan();
+ };
// Only the kill paths below are hard errors: they cannot afford to guess without a snapshot.
const poll = () =>
void scan().then(
@@ -191,7 +217,8 @@ export function trackProcessTree(
);
poll();
return {
- members: scan,
+ /** `fresh`: only a snapshot started after this call counts (proof that something ended). */
+ members: (requireFresh = false) => (requireFresh ? fresh() : scan()),
record: () => ({
group: root,
processes: latest.map(({ pid, started }) => ({ pid, started })),
diff --git a/packages/execution/src/command/process.ts b/packages/execution/src/command/process.ts
index 9f3244d..808aa46 100644
--- a/packages/execution/src/command/process.ts
+++ b/packages/execution/src/command/process.ts
@@ -2,7 +2,7 @@ import { type ChildProcess, spawn } from "node:child_process";
import type { Readable, Writable } from "node:stream";
import { StringDecoder } from "node:string_decoder";
import { z } from "zod";
-import { withDeadline } from "../core/deadline.ts";
+import { stallTolerantTimeout, withDeadline } from "../core/deadline.ts";
import { ExecError, type ExecRedactor } from "../core/types.ts";
import {
MAX_REPORTED_VIOLATIONS,
@@ -75,35 +75,39 @@ export async function windowsTree(
env: NodeJS.ProcessEnv,
signal: AbortSignal,
) {
- const members = await tree.members();
+ // Fresh reads only: a scan started before the exit lists PIDs that may be reused by now, and one
+ // started before taskkill would report the processes it just ended as still running.
+ const members = await tree.members(true);
if (!members.length) return;
// Explicit descendant PIDs still work after the original PowerShell has exited.
for (let offset = 0; offset < members.length; offset += 128) {
signal.throwIfAborted();
const batch = members.slice(offset, offset + 128);
- await new Promise<void>((resolve, reject) => {
+ await new Promise<void>((resolve) => {
const killer = spawn(
`${env.SystemRoot}\\System32\\taskkill.exe`,
[...batch.flatMap(({ pid }) => ["/PID", String(pid)]), "/T", "/F"],
{ env, stdio: "ignore", windowsHide: true },
);
- const timer = setTimeout(() => {
+ // taskkill's own outcome proves nothing either way: it reports PIDs that already exited as
+ // not found and may hang under load. The fresh snapshot below is the only proof.
+ const timer = stallTolerantTimeout(() => {
killer.kill();
killer.unref();
- reject(new ExecError("command_failed", "process_kill_failed"));
+ resolve();
}, 2000);
killer.once("error", () => {
- clearTimeout(timer);
- reject(new ExecError("command_failed", "process_kill_failed"));
+ timer.clear();
+ resolve();
});
killer.once("close", () => {
- clearTimeout(timer);
- // taskkill may report missing PIDs in a partly-exited batch; verify the whole tree below.
+ timer.clear();
resolve();
});
});
}
- if ((await tree.members()).length) throw new ExecError("command_failed", "process_kill_failed");
+ if ((await tree.members(true)).length)
+ throw new ExecError("command_failed", "process_kill_failed");
}
export async function executeProcess(options: {
@@ -143,7 +147,7 @@ export async function executeProcess(options: {
let preparing: Promise<void> | undefined;
let exitCode: number | null = null;
let killTask: Promise<void> | undefined;
- let forceDrain: ReturnType<typeof setTimeout> | undefined;
+ let forceDrain: ReturnType<typeof stallTolerantTimeout> | undefined;
let finishWait: (() => void) | undefined;
let rootClosed = false;
let drained = false;
@@ -184,8 +188,9 @@ export async function executeProcess(options: {
);
const terminate = () => {
if (killTask) return;
- // Neither an escaped session retaining pipes nor failed OS cleanup may hold busy forever.
- forceDrain = setTimeout(() => {
+ // Neither an escaped session retaining pipes nor failed OS cleanup may hold busy forever. A
+ // stalled brain must not read as an escaped pipe holder before the queued close is seen.
+ forceDrain = stallTolerantTimeout(() => {
failed = true;
child.stdout?.destroy();
child.stderr?.destroy();
@@ -359,7 +364,7 @@ export async function executeProcess(options: {
await closed;
// The force-drain timer only exists to unblock a wait that pipes never end; once close is
// observed, a long cleanup snapshot must not be mistaken for an escaped pipe holder.
- clearTimeout(forceDrain);
+ forceDrain?.clear();
clearTimeout(startupTimer);
terminate();
await killTask;
@@ -370,7 +375,7 @@ export async function executeProcess(options: {
// it must not surface as the transient monitor fault the model is told to retry (found in
// review).
const leftovers = tree
- ? await tree.members().then(
+ ? await tree.members(true).then(
(members) => members.length,
() => {
throw cleanupFailed();
@@ -404,7 +409,7 @@ export async function executeProcess(options: {
: truncatedOutput,
};
} finally {
- clearTimeout(forceDrain);
+ forceDrain?.clear();
clearTimeout(startupTimer);
clearTimeout(finishTimer);
options.signal.removeEventListener("abort", terminate);
diff --git a/packages/execution/src/core/deadline.ts b/packages/execution/src/core/deadline.ts
index c5a8872..04d8646 100644
--- a/packages/execution/src/core/deadline.ts
+++ b/packages/execution/src/core/deadline.ts
@@ -34,3 +34,35 @@ export function withDeadline<T>(
if (signal?.aborted) abort();
});
}
+
+/** A firing this late means the brain's own thread was stalled, not that the dependency was slow. */
+const STALL_MS = 1_000;
+/** Enough for one loop turn to read the I/O that completed during the stall. */
+const STALL_GRACE_MS = 1_000;
+/** A brain that keeps stalling still reaches the deadline. */
+const STALL_DEFERRALS = 3;
+
+/**
+ * setTimeout for deadlines on child processes. After a main-thread stall Node runs due timers
+ * before the I/O that completed meanwhile (measured: a child that exited during a 3 s stall still
+ * had exitCode null when its 1 s timer fired), so a plain timer reported finished Windows process
+ * snapshots as timed out and their commands' cleanup as unconfirmed. A late firing first gives
+ * that I/O a short, bounded grace.
+ */
+export function stallTolerantTimeout(callback: () => void, milliseconds: number) {
+ let deferrals = 0;
+ let timer: ReturnType<typeof setTimeout>;
+ const arm = (delay: number) => {
+ const due = performance.now() + delay;
+ timer = setTimeout(() => {
+ if (performance.now() - due >= STALL_MS && deferrals < STALL_DEFERRALS) {
+ deferrals += 1;
+ arm(STALL_GRACE_MS);
+ return;
+ }
+ callback();
+ }, delay);
+ };
+ arm(milliseconds);
+ return { clear: () => clearTimeout(timer) };
+}