Skip to content

Commit a9d3980

Browse files
authored
refactor(acpx): complete lease ownership and remove legacy reaper heuristics (#121016)
* refactor(acpx): harden pending process leases * fix(acpx): bound retained probe leases
1 parent ab5e10f commit a9d3980

9 files changed

Lines changed: 880 additions & 302 deletions

File tree

‎docs/refactor/acp.md‎

Lines changed: 133 additions & 255 deletions
Large diffs are not rendered by default.

‎extensions/acpx/src/process-lease.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
withAcpxLeaseEnvironment,
1717
type AcpxProcessLease,
1818
} from "./process-lease.js";
19+
import { ACPX_PROCESS_LEASE_MAX_ENTRIES } from "./state.js";
1920

2021
function makeLease(index: number): AcpxProcessLease {
2122
return {
@@ -75,6 +76,23 @@ describe("createAcpxProcessLeaseStore", () => {
7576
await expect(store.load(closedLease.leaseId)).resolves.toBeUndefined();
7677
await expect(store.listOpen("gateway-test")).resolves.toEqual([openLease]);
7778
});
79+
80+
it("rejects capacity overflow without evicting existing process ownership", async () => {
81+
const store = createStore();
82+
await Promise.all(
83+
Array.from({ length: ACPX_PROCESS_LEASE_MAX_ENTRIES }, (_, index) =>
84+
store.save(makeLease(index)),
85+
),
86+
);
87+
88+
await expect(store.save(makeLease(ACPX_PROCESS_LEASE_MAX_ENTRIES))).rejects.toMatchObject({
89+
code: "PLUGIN_STATE_LIMIT_EXCEEDED",
90+
});
91+
await expect(store.load("lease-0")).resolves.toEqual(makeLease(0));
92+
await expect(store.listOpen("gateway-test")).resolves.toHaveLength(
93+
ACPX_PROCESS_LEASE_MAX_ENTRIES,
94+
);
95+
});
7896
});
7997

8098
describe("withAcpxLeaseEnvironment", () => {

‎extensions/acpx/src/process-lease.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ import { ACPX_PROCESS_LEASE_MAX_ENTRIES, ACPX_PROCESS_LEASE_NAMESPACE } from "./
1414
export const OPENCLAW_ACPX_LEASE_ID_ARG = "--openclaw-acpx-lease-id";
1515
/** CLI argument carrying the owning gateway instance id. */
1616
export const OPENCLAW_GATEWAY_INSTANCE_ID_ARG = "--openclaw-gateway-instance-id";
17+
/** Synthetic session identity for generated-wrapper health probes. */
18+
export const ACPX_PROBE_LEASE_SESSION_KEY = "openclaw:acpx:probe";
1719

1820
export type AcpxProcessLeaseIdentity = {
1921
leaseId: string;
@@ -114,6 +116,7 @@ export function openAcpxProcessLeaseStateStore(
114116
return openKeyedStore<AcpxProcessLease>({
115117
namespace: ACPX_PROCESS_LEASE_NAMESPACE,
116118
maxEntries: ACPX_PROCESS_LEASE_MAX_ENTRIES,
119+
overflowPolicy: "reject-new",
117120
});
118121
}
119122

‎extensions/acpx/src/process-reaper.test.ts‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ vi.mock("openclaw/plugin-sdk/process-runtime", async (importOriginal) => ({
1111
}));
1212

1313
import {
14+
cleanupOpenClawOwnedAcpxPendingLease,
1415
cleanupOpenClawOwnedAcpxProcessTree,
1516
isOpenClawLeaseAwareAcpxProcessCommand,
1617
reapStaleOpenClawOwnedAcpxOrphans,
@@ -194,6 +195,118 @@ describe("process reaper", () => {
194195
expect(killed).toStrictEqual([]);
195196
});
196197

198+
it("recovers a pending lease only from its exact wrapper and gateway identity", async () => {
199+
const { deps, killed } = cleanupDeps([
200+
{ pid: 120, ppid: 1, command: CODEX_WRAPPER_COMMAND_WITH_LEASE },
201+
{
202+
pid: 121,
203+
ppid: 1,
204+
command: `${CODEX_WRAPPER_COMMAND} ${OPENCLAW_ACPX_LEASE_ID_ARG} lease-1 ${OPENCLAW_GATEWAY_INSTANCE_ID_ARG} gateway-foreign`,
205+
},
206+
{ pid: 122, ppid: 120, command: "node adapter-child.js" },
207+
]);
208+
209+
const result = await cleanupOpenClawOwnedAcpxPendingLease({
210+
leaseId: "lease-1",
211+
gatewayInstanceId: "gateway-1",
212+
wrapperRoot: WRAPPER_ROOT,
213+
wrapperPath: `${WRAPPER_ROOT}/codex-acp-wrapper.mjs`,
214+
deps,
215+
});
216+
217+
expect(result).toMatchObject({ inspectedPids: [120, 122] });
218+
expect(killed.slice(0, 2)).toEqual([
219+
{ pid: 122, signal: "SIGTERM" },
220+
{ pid: 120, signal: "SIGTERM" },
221+
]);
222+
expect(killed.some((entry) => entry.pid === 121)).toBe(false);
223+
});
224+
225+
it("fails closed when pending lease evidence is ambiguous or unavailable", async () => {
226+
const duplicateCommand = CODEX_WRAPPER_COMMAND_WITH_LEASE;
227+
const { deps, killed } = cleanupDeps([
228+
{ pid: 130, ppid: 1, command: duplicateCommand },
229+
{ pid: 131, ppid: 1, command: duplicateCommand },
230+
]);
231+
232+
await expect(
233+
cleanupOpenClawOwnedAcpxPendingLease({
234+
leaseId: "lease-1",
235+
gatewayInstanceId: "gateway-1",
236+
wrapperRoot: WRAPPER_ROOT,
237+
wrapperPath: `${WRAPPER_ROOT}/codex-acp-wrapper.mjs`,
238+
deps,
239+
}),
240+
).resolves.toEqual({
241+
inspectedPids: [130, 131],
242+
terminatedPids: [],
243+
skippedReason: "ambiguous-root",
244+
});
245+
expect(killed).toEqual([]);
246+
247+
await expect(
248+
cleanupOpenClawOwnedAcpxPendingLease({
249+
leaseId: "lease-1",
250+
gatewayInstanceId: "gateway-1",
251+
wrapperRoot: WRAPPER_ROOT,
252+
wrapperPath: `${WRAPPER_ROOT}/codex-acp-wrapper.mjs`,
253+
deps: {
254+
listProcesses: vi.fn(async () => {
255+
throw new Error("ps unavailable");
256+
}),
257+
},
258+
}),
259+
).resolves.toMatchObject({ skippedReason: "process-list-unavailable" });
260+
});
261+
262+
it("does not claim a pending wrapper leased by another gateway", async () => {
263+
const { deps, killed } = cleanupDeps([
264+
{
265+
pid: 135,
266+
ppid: 1,
267+
command: `${CODEX_WRAPPER_COMMAND} ${OPENCLAW_ACPX_LEASE_ID_ARG} lease-1 ${OPENCLAW_GATEWAY_INSTANCE_ID_ARG} gateway-foreign`,
268+
},
269+
]);
270+
271+
await expect(
272+
cleanupOpenClawOwnedAcpxPendingLease({
273+
leaseId: "lease-1",
274+
gatewayInstanceId: "gateway-1",
275+
wrapperRoot: WRAPPER_ROOT,
276+
wrapperPath: `${WRAPPER_ROOT}/codex-acp-wrapper.mjs`,
277+
deps,
278+
}),
279+
).resolves.toEqual({
280+
inspectedPids: [],
281+
terminatedPids: [],
282+
skippedReason: "missing-root",
283+
});
284+
expect(killed).toEqual([]);
285+
});
286+
287+
it("keeps pending leases untouched when process evidence is unsupported", async () => {
288+
const listProcesses = vi.fn(async () => [
289+
{ pid: 140, ppid: 1, command: CODEX_WRAPPER_COMMAND_WITH_LEASE },
290+
]);
291+
const killProcess = vi.fn();
292+
293+
await expect(
294+
cleanupOpenClawOwnedAcpxPendingLease({
295+
leaseId: "lease-1",
296+
gatewayInstanceId: "gateway-1",
297+
wrapperRoot: WRAPPER_ROOT,
298+
wrapperPath: `${WRAPPER_ROOT}/codex-acp-wrapper.mjs`,
299+
deps: { platform: "win32", listProcesses, killProcess },
300+
}),
301+
).resolves.toEqual({
302+
inspectedPids: [],
303+
terminatedPids: [],
304+
skippedReason: "unsupported-platform",
305+
});
306+
expect(listProcesses).not.toHaveBeenCalled();
307+
expect(killProcess).not.toHaveBeenCalled();
308+
});
309+
197310
it("skips recorded pid cleanup when process listing is unavailable", async () => {
198311
const killed: Array<{ pid: number; signal: NodeJS.Signals }> = [];
199312
const result = await cleanupOpenClawOwnedAcpxProcessTree({
@@ -284,6 +397,7 @@ describe("process reaper", () => {
284397
{ pid: 404, ppid: 403, command: "node claude-child.js" },
285398
{ pid: 405, ppid: 1, command: PLUGIN_DEPS_CODEX_COMMAND },
286399
{ pid: 406, ppid: 1, command: "node /tmp/other/codex-acp-wrapper.mjs" },
400+
{ pid: 407, ppid: 1, command: CODEX_WRAPPER_COMMAND_WITH_LEASE },
287401
]);
288402

289403
const result = await reapStaleOpenClawOwnedAcpxOrphans({

‎extensions/acpx/src/process-reaper.ts‎

Lines changed: 84 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,11 @@ import { runExec } from "openclaw/plugin-sdk/process-runtime";
88
import { CODEX_ACP_PACKAGE, LEGACY_CODEX_ACP_PACKAGE } from "./codex-adapter.js";
99
import { splitCommandParts } from "./command-line.js";
1010
import { resolveAcpxPluginRoot } from "./config.js";
11-
import { OPENCLAW_ACPX_LEASE_ID_ARG, OPENCLAW_GATEWAY_INSTANCE_ID_ARG } from "./process-lease.js";
11+
import {
12+
OPENCLAW_ACPX_LEASE_ID_ARG,
13+
OPENCLAW_GATEWAY_INSTANCE_ID_ARG,
14+
readAcpxProcessLeaseIdentity,
15+
} from "./process-lease.js";
1216

1317
const requireFromHere = createRequire(import.meta.url);
1418
const GENERATED_WRAPPER_BASENAMES = new Set([
@@ -59,6 +63,7 @@ type AcpxProcessInfo = {
5963
export type AcpxProcessCleanupDeps = {
6064
listProcesses?: () => Promise<AcpxProcessInfo[]>;
6165
killProcess?: (pid: number, signal: NodeJS.Signals) => void;
66+
platform?: NodeJS.Platform;
6267
sleep?: (ms: number) => Promise<void>;
6368
};
6469

@@ -68,8 +73,10 @@ type AcpxProcessCleanupResult = {
6873
terminatedPids: number[];
6974
skippedReason?:
7075
| "missing-root"
76+
| "ambiguous-root"
7177
| "not-openclaw-owned"
7278
| "process-list-unavailable"
79+
| "unsupported-platform"
7380
| "unverified-root";
7481
};
7582

@@ -136,6 +143,20 @@ function commandWrapperBelongsToRoot(command: string, wrapperRoot: string | unde
136143
);
137144
}
138145

146+
function commandContainsExactWrapperPath(command: string, wrapperPath: string): boolean {
147+
const expectedPath = normalizePathLike(wrapperPath);
148+
return splitCommandParts(command).some((part) => normalizePathLike(part) === expectedPath);
149+
}
150+
151+
function wrapperPathBelongsToRoot(wrapperPath: string, wrapperRoot: string): boolean {
152+
const normalizedPath = normalizePathLike(wrapperPath);
153+
const normalizedRoot = normalizePathLike(wrapperRoot).replace(/\/+$/, "");
154+
return (
155+
GENERATED_WRAPPER_BASENAMES.has(path.posix.basename(normalizedPath)) &&
156+
normalizedPath.startsWith(`${normalizedRoot}/`)
157+
);
158+
}
159+
139160
/** Check whether a command references an OpenClaw-generated ACPX wrapper path. */
140161
export function isOpenClawLeaseAwareAcpxProcessCommand(params: {
141162
command: string | undefined;
@@ -342,6 +363,9 @@ export async function cleanupOpenClawOwnedAcpxProcessTree(params: {
342363
if (!rootPid || rootPid <= 0 || rootPid === process.pid) {
343364
return { inspectedPids: [], terminatedPids: [], skippedReason: "missing-root" };
344365
}
366+
if ((params.deps?.platform ?? process.platform) === "win32") {
367+
return { inspectedPids: [], terminatedPids: [], skippedReason: "unsupported-platform" };
368+
}
345369

346370
let processes: AcpxProcessInfo[];
347371
try {
@@ -418,12 +442,66 @@ export async function cleanupOpenClawOwnedAcpxProcessTree(params: {
418442
};
419443
}
420444

445+
/** Recover a pending lease by matching its exact live wrapper identity. */
446+
export async function cleanupOpenClawOwnedAcpxPendingLease(params: {
447+
leaseId: string;
448+
gatewayInstanceId: string;
449+
wrapperRoot: string;
450+
wrapperPath: string;
451+
deps?: AcpxProcessCleanupDeps;
452+
}): Promise<AcpxProcessCleanupResult> {
453+
if ((params.deps?.platform ?? process.platform) === "win32") {
454+
return { inspectedPids: [], terminatedPids: [], skippedReason: "unsupported-platform" };
455+
}
456+
if (!params.wrapperPath || !wrapperPathBelongsToRoot(params.wrapperPath, params.wrapperRoot)) {
457+
return { inspectedPids: [], terminatedPids: [], skippedReason: "unverified-root" };
458+
}
459+
460+
let processes: AcpxProcessInfo[];
461+
try {
462+
processes = await (params.deps?.listProcesses ?? listPlatformProcesses)();
463+
} catch {
464+
return {
465+
inspectedPids: [],
466+
terminatedPids: [],
467+
skippedReason: "process-list-unavailable",
468+
};
469+
}
470+
471+
const matchingRoots = processes.filter(
472+
(processInfo) =>
473+
commandContainsExactWrapperPath(processInfo.command, params.wrapperPath) &&
474+
liveCommandMatchesLeaseIdentity({
475+
command: processInfo.command,
476+
expectedLeaseId: params.leaseId,
477+
expectedGatewayInstanceId: params.gatewayInstanceId,
478+
}),
479+
);
480+
if (matchingRoots.length === 0) {
481+
return { inspectedPids: [], terminatedPids: [], skippedReason: "missing-root" };
482+
}
483+
if (matchingRoots.length > 1) {
484+
return {
485+
inspectedPids: uniquePids(matchingRoots),
486+
terminatedPids: [],
487+
skippedReason: "ambiguous-root",
488+
};
489+
}
490+
491+
const listedTree = collectProcessTree(processes, matchingRoots[0]!.pid);
492+
const pids = uniquePids(listedTree.toReversed());
493+
return {
494+
inspectedPids: uniquePids(listedTree),
495+
terminatedPids: await terminatePids(pids, params.deps),
496+
};
497+
}
498+
421499
/** Reap orphaned OpenClaw-owned ACPX wrapper trees during runtime startup. */
422500
export async function reapStaleOpenClawOwnedAcpxOrphans(params: {
423501
wrapperRoot: string;
424502
deps?: AcpxProcessCleanupDeps;
425503
}): Promise<AcpxStartupReapResult> {
426-
if (process.platform === "win32") {
504+
if ((params.deps?.platform ?? process.platform) === "win32") {
427505
return { inspectedPids: [], terminatedPids: [], skippedReason: "unsupported-platform" };
428506
}
429507

@@ -437,6 +515,10 @@ export async function reapStaleOpenClawOwnedAcpxOrphans(params: {
437515
const orphans = processes.filter(
438516
(processInfo) =>
439517
processInfo.ppid === 1 &&
518+
// Lease-aware wrapper roots are recovered one lease at a time. This
519+
// temporary marker fallback remains only for direct agents and
520+
// reparented descendants that upstream acpx cannot identify yet.
521+
!readAcpxProcessLeaseIdentity(processInfo.command) &&
440522
isOpenClawOwnedAcpxProcessCommand({
441523
command: processInfo.command,
442524
wrapperRoot: params.wrapperRoot,

0 commit comments

Comments
 (0)