Skip to content

Commit 722ea9b

Browse files
Radu028claude
andcommitted
fix(acp-registry): Copilot SDK checks start times before killing and reports refused signals
A frozen process can still be killed by someone else and its pid reused, so T3 records each process's start time when it freezes it and kills only a pid that still has that start time. A signal a process refuses, such as one running under sudo, is now reported as a cleanup failure instead of success. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent dd0759b commit 722ea9b

2 files changed

Lines changed: 104 additions & 46 deletions

File tree

‎packages/provider-acp-registry/src/server/copilotSdk.ts‎

Lines changed: 67 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -89,12 +89,21 @@ export function descendantPids(listing: string, rootPid: number): ReadonlyArray<
8989
return found;
9090
}
9191

92-
/** A process's parent pid from /proc; undefined once it is gone. */
93-
async function linuxParentOf(pid: string | number): Promise<string | undefined> {
92+
/** Which process holds a pid: its parent, and its start time to tell a reused pid apart. */
93+
export interface ProcessIdentity {
94+
readonly parent: number;
95+
readonly started: string;
96+
}
97+
98+
/** From /proc; undefined once the process is gone. */
99+
async function linuxIdentity(pid: string | number): Promise<ProcessIdentity | undefined> {
94100
try {
95-
// The command name in parentheses may hold spaces; the parent pid follows its state.
101+
// The command name in parentheses may hold spaces. After it come the state, the parent
102+
// pid, and 17 more fields up to the start time in clock ticks since boot.
96103
const stat = await NodeFSP.readFile(`/proc/${pid}/stat`, "utf8");
97-
return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1];
104+
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
105+
const started = fields[19];
106+
return started === undefined ? undefined : { parent: Number(fields[1]), started };
98107
} catch {
99108
return undefined;
100109
}
@@ -117,25 +126,30 @@ const runPs = (args: ReadonlyArray<string>) =>
117126
const listProcesses = async (): Promise<string> => {
118127
if (!(await hasProc())) return runPs(["-A", "-o", "pid=,ppid="]);
119128
const entries = (await NodeFSP.readdir("/proc")).filter((entry) => /^[1-9][0-9]*$/.test(entry));
120-
const parents = await Promise.all(entries.map(linuxParentOf));
121-
return entries.map((entry, index) => `${entry} ${parents[index] ?? ""}`).join("\n");
129+
const identities = await Promise.all(entries.map(linuxIdentity));
130+
return entries.map((entry, index) => `${entry} ${identities[index]?.parent ?? ""}`).join("\n");
122131
};
123132

124-
const parentOf = async (pid: number): Promise<number | undefined> => {
125-
const parent = (await hasProc())
126-
? await linuxParentOf(pid)
127-
: await runPs(["-o", "ppid=", "-p", String(pid)]).then(
128-
(stdout) => stdout.trim(),
129-
() => undefined,
130-
);
131-
return parent === undefined || parent === "" ? undefined : Number(parent);
133+
const identify = async (pid: number): Promise<ProcessIdentity | undefined> => {
134+
if (await hasProc()) return linuxIdentity(pid);
135+
// lstart is the start time to the second, e.g. "Thu Oct 30 13:01:02 2026".
136+
const line = await runPs(["-o", "ppid=,lstart=", "-p", String(pid)]).then(
137+
(stdout) => stdout.trim(),
138+
() => "",
139+
);
140+
const [parent, ...started] = line.split(/\s+/);
141+
return parent === undefined || parent === "" || started.length === 0
142+
? undefined
143+
: { parent: Number(parent), started: started.join(" ") };
132144
};
133145

134-
const signalQuietly = (pid: number, signal: NodeJS.Signals) => {
146+
/** False when the process refused the signal, such as one running as root; gone counts as sent. */
147+
const signalProcess = (pid: number, signal: NodeJS.Signals): boolean => {
135148
try {
136149
process.kill(pid, signal);
137-
} catch {
138-
// Already gone.
150+
return true;
151+
} catch (cause) {
152+
return cause instanceof Error && "code" in cause && cause.code === "ESRCH";
139153
}
140154
};
141155

@@ -150,44 +164,59 @@ export async function stopProcessTree(input: {
150164
readonly rootPid: number;
151165
readonly rootExited: () => boolean;
152166
readonly list: () => Promise<string>;
153-
readonly parentOf: (pid: number) => Promise<number | undefined>;
154-
readonly signal: (pid: number, signal: NodeJS.Signals) => void;
167+
readonly identify: (pid: number) => Promise<ProcessIdentity | undefined>;
168+
/** False when the process refused the signal; a process already gone counts as signalled. */
169+
readonly signal: (pid: number, signal: NodeJS.Signals) => boolean;
155170
readonly selfPid: number;
156171
}): Promise<string | undefined> {
157-
// Each was a child of the CLI or of a frozen process when frozen, and a frozen process
158-
// cannot exit, so every pid here stays Copilot's on every path below.
159-
const frozen: Array<number> = [];
160-
const killFrozen = (failure: string | undefined) => {
161-
for (const pid of [...frozen].reverse()) input.signal(pid, "SIGKILL");
162-
return failure;
172+
// Start times by pid, parents first. Each was under the CLI or a frozen process when frozen.
173+
const frozen = new Map<number, string>();
174+
const refused = new Set<number>();
175+
const send = (pid: number, signal: NodeJS.Signals) => {
176+
const sent = input.signal(pid, signal);
177+
if (!sent) refused.add(pid);
178+
return sent;
179+
};
180+
const killFrozen = async (failure: string | undefined) => {
181+
for (const [pid, started] of [...frozen].reverse()) {
182+
// Someone else can kill a frozen process too, and its pid can then be reused. Checking
183+
// the start time leaves only the instant before the signal, as for the ACP path.
184+
if ((await input.identify(pid))?.started === started) send(pid, "SIGKILL");
185+
}
186+
if (failure !== undefined) return failure;
187+
return refused.size === 0
188+
? undefined
189+
: `Copilot's processes ${[...refused].join(", ")} refused to stop`;
163190
};
164191
const exitedFailure = "Copilot exited before all of its processes were found";
165-
input.signal(input.rootPid, "SIGSTOP");
192+
send(input.rootPid, "SIGSTOP");
166193
try {
167194
for (let pass = 0; pass < MAX_FREEZE_PASSES; pass += 1) {
168195
const listing = await input.list();
169196
// Once the CLI exited its pid can be reused, so this listing may show another tree.
170-
if (input.rootExited()) return killFrozen(exitedFailure);
197+
if (input.rootExited()) return await killFrozen(exitedFailure);
171198
const fresh = descendantPids(listing, input.rootPid).filter(
172-
(pid) => pid !== input.selfPid && !frozen.includes(pid),
199+
(pid) => pid !== input.selfPid && !frozen.has(pid) && !refused.has(pid),
173200
);
174-
if (fresh.length === 0) return killFrozen(undefined);
201+
if (fresh.length === 0) return await killFrozen(undefined);
175202
// Parents come first, so each one's parent is frozen by the time it is checked.
176203
for (const pid of fresh) {
177204
// A listed pid can exit and be reused before its SIGSTOP; its parent tells them apart.
178-
const parent = await input.parentOf(pid);
179-
if (input.rootExited()) return killFrozen(exitedFailure);
180-
if (parent !== input.rootPid && (parent === undefined || !frozen.includes(parent))) {
205+
const identity = await input.identify(pid);
206+
if (input.rootExited()) return await killFrozen(exitedFailure);
207+
if (
208+
identity === undefined ||
209+
(identity.parent !== input.rootPid && !frozen.has(identity.parent))
210+
) {
181211
continue;
182212
}
183-
input.signal(pid, "SIGSTOP");
184-
frozen.push(pid);
213+
if (send(pid, "SIGSTOP")) frozen.set(pid, identity.started);
185214
}
186215
}
187-
return killFrozen(`Copilot kept starting processes after ${MAX_FREEZE_PASSES} passes`);
216+
return await killFrozen(`Copilot kept starting processes after ${MAX_FREEZE_PASSES} passes`);
188217
} catch (cause) {
189218
const reason = cause instanceof Error ? cause.message : String(cause);
190-
return killFrozen(`listing Copilot's processes failed: ${reason}`);
219+
return await killFrozen(`listing Copilot's processes failed: ${reason}`);
191220
}
192221
}
193222

@@ -227,8 +256,8 @@ export function copilotClientProcess(client: object): CopilotProcess | undefined
227256
rootPid: pid,
228257
rootExited: hasExited,
229258
list: listProcesses,
230-
parentOf,
231-
signal: signalQuietly,
259+
identify,
260+
signal: signalProcess,
232261
selfPid: process.pid,
233262
}),
234263
exited: stdioClosed

‎packages/provider-acp-registry/src/server/copilotSdkAdapter.test.ts‎

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ import {
5050
copilotClientProcess,
5151
copilotSdkCliCandidates,
5252
descendantPids,
53+
type ProcessIdentity,
5354
stopProcessTree,
5455
type CopilotSdkClient,
5556
type CopilotSdkClientOptions,
@@ -1819,13 +1820,15 @@ describe("CopilotSdkAdapterV2", () => {
18191820
it("freezes every generation of Copilot's processes before killing them", async () => {
18201821
const signals: Array<string> = [];
18211822
// Each listing is a `pid ppid` table, or an Error for a listing that fails. The last one
1822-
// repeats once the queue runs out. Parents come from the latest table unless reassigned.
1823+
// repeats once the queue runs out. Identities come from the latest table, with start time
1824+
// "t0", unless a test replaces one; `refusing` pids reject every signal.
18231825
const stop = (
18241826
listings: Array<string | Error>,
18251827
options: {
18261828
readonly onList?: (count: number) => void;
18271829
readonly rootExited?: () => boolean;
1828-
readonly reassigned?: ReadonlyMap<number, number>;
1830+
readonly replaced?: Map<number, ProcessIdentity>;
1831+
readonly refusing?: ReadonlySet<number>;
18291832
} = {},
18301833
) => {
18311834
let current = "";
@@ -1840,13 +1843,19 @@ describe("CopilotSdkAdapterV2", () => {
18401843
current = next;
18411844
return next;
18421845
},
1843-
parentOf: async (pid) =>
1844-
options.reassigned?.get(pid) ??
1845-
current
1846+
identify: async (pid) => {
1847+
const replaced = options.replaced?.get(pid);
1848+
if (replaced) return replaced;
1849+
const parent = current
18461850
.split("\n")
18471851
.map((line) => line.trim().split(/\s+/).map(Number))
1848-
.find(([listed]) => listed === pid)?.[1],
1849-
signal: (pid, name) => void signals.push(`${name} ${pid}`),
1852+
.find(([listed]) => listed === pid)?.[1];
1853+
return parent === undefined ? undefined : { parent, started: "t0" };
1854+
},
1855+
signal: (pid, name) => {
1856+
signals.push(`${name} ${pid}`);
1857+
return !options.refusing?.has(pid);
1858+
},
18501859
selfPid: 1,
18511860
});
18521861
};
@@ -1881,10 +1890,30 @@ describe("CopilotSdkAdapterV2", () => {
18811890
// parent shows that, so it is never stopped, even when the next listing fails.
18821891
signals.length = 0;
18831892
const reused = await stop(["101 100", new Error("ps timed out")], {
1884-
reassigned: new Map([[101, 999]]),
1893+
replaced: new Map([[101, { parent: 999, started: "t1" }]]),
18851894
});
18861895
assert.include(reused, "ps timed out");
18871896
assert.deepStrictEqual(signals, ["SIGSTOP 100"]);
1897+
1898+
// Something else killed the frozen 101 and its pid was reused while the CLI exited. The
1899+
// start time no longer matches, so the new process is not killed.
1900+
signals.length = 0;
1901+
const replaced = new Map<number, ProcessIdentity>();
1902+
const killedElsewhere = await stop(["101 100", "101 100"], {
1903+
onList: (count) => {
1904+
if (count > 1) replaced.set(101, { parent: 999, started: "t1" });
1905+
},
1906+
rootExited: () => replaced.size > 0,
1907+
replaced,
1908+
});
1909+
assert.include(killedElsewhere, "exited");
1910+
assert.deepStrictEqual(signals, ["SIGSTOP 100", "SIGSTOP 101"]);
1911+
1912+
// A process T3 may not signal, such as one under sudo, is reported, not counted as stopped.
1913+
signals.length = 0;
1914+
const refused = await stop(["101 100\n102 100"], { refusing: new Set([102]) });
1915+
assert.include(refused, "102 refused to stop");
1916+
assert.deepStrictEqual(signals, ["SIGSTOP 100", "SIGSTOP 101", "SIGSTOP 102", "SIGKILL 101"]);
18881917
});
18891918

18901919
it("lists the processes under Copilot's CLI from a ps listing", () => {

0 commit comments

Comments
 (0)