From 2cf0d1af00ffdb7f8a3c4a0bbeccac5e87401fd1 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Thu, 8 Oct 2026 12:12:28 -0700 Subject: [PATCH] Preserve accepted plugin writes during idle preparation Keep worker-to-host writes admitted until the worker confirms its accepted handlers have drained. Release only the matching preparation and log session callback failures. Verified with 13 idle RPC tests, adjacent worker tests, and server typecheck. Co-Authored-By: Paperclip --- packages/plugins/sdk/src/worker-rpc-host.ts | 7 ++++- .../__tests__/fixtures/plugin-worker-idle.cjs | 7 ++++- .../src/__tests__/plugin-idle-manager.test.ts | 27 ++++++++++++++++++- server/src/__tests__/plugin-idle-rpc.test.ts | 22 +++++++++++++++ server/src/services/plugin-worker-manager.ts | 23 +++++++++++----- 5 files changed, 76 insertions(+), 10 deletions(-) diff --git a/packages/plugins/sdk/src/worker-rpc-host.ts b/packages/plugins/sdk/src/worker-rpc-host.ts index a4544f3c518..d6781c1b6db 100644 --- a/packages/plugins/sdk/src/worker-rpc-host.ts +++ b/packages/plugins/sdk/src/worker-rpc-host.ts @@ -2322,7 +2322,12 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost } else if (notif.method === "agents.sessions.event" && notif.params) { const event = notif.params as AgentSessionEvent; const cb = sessionEventCallbacks.get(event.sessionId); - if (cb) void runNotification(() => cb(event)).catch(() => undefined); + if (cb) void runNotification(() => cb(event)).catch((err) => { + notifyHost("log", { + level: "error", + message: `Failed to handle session event notification: ${err instanceof Error ? err.message : String(err)}`, + }); + }); } else if (notif.method === "onEvent" && notif.params) { // Plugin event bus notifications — dispatch to registered event handlers Promise.resolve(runNotification(() => handleOnEvent(notif.params as OnEventParams))).catch((err) => { diff --git a/server/src/__tests__/fixtures/plugin-worker-idle.cjs b/server/src/__tests__/fixtures/plugin-worker-idle.cjs index c17c40610f6..4b989b447ea 100644 --- a/server/src/__tests__/fixtures/plugin-worker-idle.cjs +++ b/server/src/__tests__/fixtures/plugin-worker-idle.cjs @@ -5,7 +5,12 @@ void Promise.all([ ]).then(([{ definePlugin }, { startWorkerRpcHost }]) => { let context; startWorkerRpcHost({ plugin: definePlugin({ - async setup(ctx) { context = ctx; }, + async setup(ctx) { + context = ctx; + ctx.events.on("fixture.write", async () => { + await ctx.state.set({ scopeKind: "instance", stateKey: "event" }, { value: 1 }); + }); + }, async onIdleDrain() { return "none"; }, async onHealth() { if (process.env.IDLE_TEST_WRITE === "1") { diff --git a/server/src/__tests__/plugin-idle-manager.test.ts b/server/src/__tests__/plugin-idle-manager.test.ts index e8bbb7ee019..1ea93bc172b 100644 --- a/server/src/__tests__/plugin-idle-manager.test.ts +++ b/server/src/__tests__/plugin-idle-manager.test.ts @@ -12,7 +12,8 @@ function worker(write = false, hostHandler = async () => undefined) { entrypointPath: fileURLToPath(new URL("./fixtures/plugin-worker-idle.cjs", import.meta.url)), execArgv: ["--import", createRequire(import.meta.url).resolve("tsx")], manifest, config: {}, instanceInfo: { instanceId: "fixture", hostVersion: "1.0.0" }, apiVersion: 1, - env: { IDLE_TEST_WRITE: write ? "1" : "0" }, hostHandlers: { "state.set": hostHandler }, + env: { IDLE_TEST_WRITE: write ? "1" : "0" }, + hostHandlers: { "state.set": hostHandler, "events.subscribe": async () => ({}) }, }); } function hold() { @@ -55,6 +56,30 @@ describe("plugin manager idle receipts", () => { } finally { stopTaskDrain(); await handle.stop(); } }); + it("lets a queued notification finish its write while idle preparation is in flight", async () => { + let finish!: () => void; + let writes = 0; + const handle = worker(false, () => new Promise((resolve) => { + writes++; + finish = resolve; + })); + await handle.start(); + try { + // Finish setup and its subscription receipt before queuing the event. + await handle.call("health", {}); + handle.notify("onEvent", { event: { eventType: "fixture.write" } }); + // No await: the host has set its hold before it can read the event's + // worker-to-host write. The worker must still be allowed to complete it. + const lease = hold(); + const preparation = handle.prepareIdleSleep!(lease); + expect(await preparation).not.toBe("none"); + await expect.poll(() => writes).toBe(1); + expect(await handle.prepareIdleSleep!(lease)).toBe("present"); + finish(); + await expect.poll(() => handle.prepareIdleSleep!(lease)).toBe("none"); + } finally { finish?.(); stopTaskDrain(); await handle.stop(); } + }); + it("resumes crash recovery after an idle hold without discarding the restart", async () => { const handle = worker(); await handle.start(); diff --git a/server/src/__tests__/plugin-idle-rpc.test.ts b/server/src/__tests__/plugin-idle-rpc.test.ts index cc23e56d473..c1e626c1b88 100644 --- a/server/src/__tests__/plugin-idle-rpc.test.ts +++ b/server/src/__tests__/plugin-idle-rpc.test.ts @@ -64,4 +64,26 @@ describe("plugin idle RPC", () => { expect((await f.call("prepareIdleSleep", hold())).result.backgroundWork).toBe("none"); } finally { f.close(); } }); + + it.each([false, true])("logs session callback failures (async: %s)", async (asynchronous) => { + let subscribe!: () => Promise; + const f = fixture({ async setup(ctx) { + subscribe = () => ctx.agents.sessions.sendMessage("fixture-session", "fixture-company", { + prompt: "fixture", + onEvent: asynchronous + ? async () => { throw new Error("fixture callback failure"); } + : () => { throw new Error("fixture callback failure"); }, + }); + } }); + try { + await f.initialize(); + const subscription = subscribe(); + const request = f.messages.find((message) => message.method === "agents.sessions.sendMessage"); + f.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: request.id, result: {} }) + "\n"); + await subscription; + f.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "agents.sessions.event", params: { sessionId: "fixture-session" } }) + "\n"); + await expect.poll(() => f.messages.find((message) => message.method === "log" && + message.params.level === "error" && message.params.message.includes("fixture callback failure"))).toBeDefined(); + } finally { f.close(); } + }); }); diff --git a/server/src/services/plugin-worker-manager.ts b/server/src/services/plugin-worker-manager.ts index d4ac6e919af..2d3f961d530 100644 --- a/server/src/services/plugin-worker-manager.ts +++ b/server/src/services/plugin-worker-manager.ts @@ -899,7 +899,7 @@ export function createPluginWorkerHandle( // completion receipt. A worker crash cannot manufacture one. const unsettledCalls = new Map void>(); let activeHostHandlers = 0; - let idleHold: { ownerId: string; expiresAt: number } | null = null; + let idleHold: { ownerId: string; expiresAt: number; ready: boolean } | null = null; function releaseIdleSleep(): void { const prior = idleHold; @@ -2733,7 +2733,10 @@ export function createPluginWorkerHandle( const done = beginIdleTrackedWork(); activeHostHandlers++; try { - if (idleSleepHeld()) { + // A queued notification may already be running in the worker while its + // prepare request is in flight. Let its writes finish until that worker + // has positively acknowledged that all accepted handlers have drained. + if (idleSleepHeld() && idleHold?.ready) { try { sendMessage(createErrorResponse(request.id, PLUGIN_RPC_ERROR_CODES.WORKER_UNAVAILABLE, "Plugin is held for idle sleep")); } catch { /* Worker may have exited after sending its request. */ } @@ -3470,16 +3473,22 @@ export function createPluginWorkerHandle( if (unsettledCalls.size || activeHostHandlers || loginPtyRoutesByHostRouteId.size || liveDuplexRoutes.size || openingDuplexRoutes.size || terminalDuplexRoutes.size) return "present"; if (idleHold && (idleHold.ownerId !== hold.ownerId || idleHold.expiresAt !== hold.expiresAt)) return "unknown"; - idleHold = hold; + const candidate = idleHold ??= { ...hold, ready: false }; try { const result = await callInternal("prepareIdleSleep", hold, Math.min(5_000, hold.expiresAt - Date.now())); - if (!idleSleepHeld() || status !== "running" || unsettledCalls.size || activeHostHandlers || - result.ownerId !== hold.ownerId || result.expiresAt !== hold.expiresAt) return "unknown"; - if (result.backgroundWork === "none") return "none"; + if (!idleSleepHeld() || idleHold !== candidate || status !== "running" || unsettledCalls.size || activeHostHandlers || + result.ownerId !== hold.ownerId || result.expiresAt !== hold.expiresAt) { + if (idleHold === candidate) releaseIdleSleep(); + return "unknown"; + } + if (result.backgroundWork === "none") { + candidate.ready = true; + return "none"; + } releaseIdleSleep(); return result.backgroundWork === "present" ? "present" : "unknown"; } catch { - releaseIdleSleep(); + if (idleHold === candidate) releaseIdleSleep(); return "unknown"; } },