Skip to content

Commit 07a0b51

Browse files
authored
fix(gateway): enforce shutdown deadline during event-loop stalls (#125863)
Use an off-main-thread watchdog for the process-owning Gateway runner so a CPU-bound shutdown cannot outlive the managed restart deadline. Bound agent-harness disposal so listener teardown can continue. Release note: Managed Gateway restarts now recover when shutdown work stalls the event loop while preserving graceful cleanup first. Closes #125840
1 parent 0c06490 commit 07a0b51

8 files changed

Lines changed: 249 additions & 28 deletions

File tree

‎src/cli/gateway-cli/run-loop.test.ts‎

Lines changed: 45 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,12 @@ const gatewayLog = {
136136
error: vi.fn(),
137137
};
138138
const flushLogger = vi.fn(async () => {});
139+
const cancelShutdownHardExitWatchdog = vi.fn();
140+
const armShutdownHardExitWatchdog = vi.fn(
141+
(_params: { delayMs: number; onError: (error: unknown) => void }) => ({
142+
cancel: cancelShutdownHardExitWatchdog,
143+
}),
144+
);
139145

140146
vi.mock("../../infra/gateway-lock.js", () => ({
141147
acquireGatewayLock: (opts?: { port?: number }) => acquireGatewayLock(opts),
@@ -255,6 +261,11 @@ vi.mock("../../gateway/server-reload-contracts.js", () => ({
255261
abortPendingChannelReloads: () => abortPendingChannelReloads(),
256262
}));
257263

264+
vi.mock("./shutdown-hard-exit.js", () => ({
265+
armShutdownHardExitWatchdog: (params: { delayMs: number; onError: (error: unknown) => void }) =>
266+
armShutdownHardExitWatchdog(params),
267+
}));
268+
258269
const LOOP_SIGNALS = ["SIGTERM", "SIGINT", "SIGUSR1"] as const;
259270
type LoopSignal = (typeof LOOP_SIGNALS)[number];
260271
const originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, "platform");
@@ -383,6 +394,7 @@ function createSignaledStart(close: GatewayCloseFn, startupSettled = Promise.res
383394
async function runLoopWithStart(params: {
384395
start: ReturnType<typeof vi.fn>;
385396
runtime: LoopRuntime;
397+
ownsProcessLifecycle?: boolean;
386398
lockPort?: number;
387399
healthHost?: string;
388400
waitForHealthyChild?: (port: number, pid?: number, host?: string) => Promise<boolean>;
@@ -392,6 +404,7 @@ async function runLoopWithStart(params: {
392404
const loopPromise = runGatewayLoop({
393405
start: params.start as unknown as Parameters<typeof runGatewayLoop>[0]["start"],
394406
runtime: params.runtime,
407+
ownsProcessLifecycle: params.ownsProcessLifecycle,
395408
lockPort: params.lockPort,
396409
healthHost: params.healthHost,
397410
waitForHealthyChild: params.waitForHealthyChild,
@@ -628,6 +641,7 @@ describe("runGatewayLoop", () => {
628641
});
629642
expect(runtime.exit).toHaveBeenCalledWith(0);
630643
expect(flushLogger).toHaveBeenCalledOnce();
644+
expect(armShutdownHardExitWatchdog).not.toHaveBeenCalled();
631645
});
632646
});
633647

@@ -2411,32 +2425,41 @@ describe("runGatewayLoop", () => {
24112425
await withIsolatedSignals(async ({ captureSignal }) => {
24122426
const { start, started } = createSignaledStart(close);
24132427
const { runtime, exited } = createRuntimeWithExitSignal();
2414-
await runLoopWithStart({ start, runtime });
2428+
await runLoopWithStart({ start, runtime, ownsProcessLifecycle: true });
24152429
await waitForStart(started);
24162430
const sigusr1 = captureSignal("SIGUSR1");
24172431

2418-
sigusr1();
2419-
await waitForLoopCondition(
2420-
() => close.mock.calls.length === 1,
2421-
"restart close did not start",
2422-
);
2423-
sigusr1();
2424-
await waitForLoopCondition(
2425-
() =>
2426-
gatewayLog.info.mock.calls.some(([message]) =>
2427-
String(message).includes("upgrading to update.auto"),
2428-
),
2429-
"accepted restart was not upgraded",
2430-
);
2432+
try {
2433+
sigusr1();
2434+
await waitForLoopCondition(
2435+
() => close.mock.calls.length === 1,
2436+
"restart close did not start",
2437+
);
2438+
expect(armShutdownHardExitWatchdog).toHaveBeenCalledTimes(1);
2439+
sigusr1();
2440+
await waitForLoopCondition(
2441+
() =>
2442+
gatewayLog.info.mock.calls.some(([message]) =>
2443+
String(message).includes("upgrading to update.auto"),
2444+
),
2445+
"accepted restart was not upgraded",
2446+
);
2447+
expect(cancelShutdownHardExitWatchdog).toHaveBeenCalledTimes(1);
2448+
expect(armShutdownHardExitWatchdog).toHaveBeenCalledTimes(2);
24312449

2432-
releaseClose();
2433-
await expect(exited).resolves.toBe(0);
2434-
expect(respawnGatewayProcessForUpdate).toHaveBeenCalledTimes(1);
2435-
expectRestartHandoffCall({
2436-
restartKind: "update-process",
2437-
reason: "update.auto",
2438-
supervisorMode: "external",
2439-
});
2450+
releaseClose();
2451+
await expect(exited).resolves.toBe(0);
2452+
expect(cancelShutdownHardExitWatchdog).toHaveBeenCalledTimes(2);
2453+
expect(respawnGatewayProcessForUpdate).toHaveBeenCalledTimes(1);
2454+
expectRestartHandoffCall({
2455+
restartKind: "update-process",
2456+
reason: "update.auto",
2457+
supervisorMode: "external",
2458+
});
2459+
} finally {
2460+
releaseClose();
2461+
await exited;
2462+
}
24402463
});
24412464
} finally {
24422465
if (originalPlatformDescriptor) {

‎src/cli/gateway-cli/run-loop.ts‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@ import {
2828
GATEWAY_AGENT_MEDIA_MIGRATION_REQUIRED_REASON,
2929
} from "../../state/openclaw-agent-db-migration-required.js";
3030
import { formatActiveTaskRestartBlocker } from "../../tasks/task-restart-blocker.js";
31+
import {
32+
armShutdownHardExitWatchdog,
33+
type ShutdownHardExitWatchdog,
34+
} from "./shutdown-hard-exit.js";
3135
const gatewayLog = createSubsystemLogger("gateway");
3236
const LAUNCHD_SUPERVISED_RESTART_EXIT_DELAY_MS = 1500;
3337
const DEFAULT_RESTART_DRAIN_TIMEOUT_MS = 300_000;
@@ -36,6 +40,7 @@ const RESTART_CLOSE_REPLY_DRAIN_SHUTDOWN_RESERVE_MS = 10_000;
3640
const UPDATE_RESPAWN_HEALTH_TIMEOUT_MS = 10_000;
3741
const UPDATE_RESPAWN_HEALTH_POLL_MS = 200;
3842
const LOG_FLUSH_EXIT_TIMEOUT_MS = 4_000;
43+
const HARD_EXIT_WATCHDOG_GRACE_MS = 2_000;
3944

4045
type GatewayRunSignalAction = "stop" | "restart";
4146
type RestartDrainTimeoutMs = number | undefined;
@@ -109,6 +114,8 @@ export async function runGatewayLoop(params: {
109114
requestHotReloadRecovery?: GatewayRestartEmitter;
110115
}) => Promise<Awaited<ReturnType<typeof startGatewayServer>>>;
111116
runtime: RuntimeEnv;
117+
/** Grants this run-loop authority to hard-kill the process it exclusively owns. */
118+
ownsProcessLifecycle?: boolean;
112119
lockPort?: number;
113120
healthHost?: string;
114121
waitForHealthyChild?: (port: number, pid?: number, host?: string) => Promise<boolean>;
@@ -502,6 +509,7 @@ export async function runGatewayLoop(params: {
502509
activeRestartRequest = acceptedRequest;
503510
}
504511
let forceExitTimer: ReturnType<typeof setTimeout> | null = null;
512+
let hardExitWatchdog: ShutdownHardExitWatchdog | null = null;
505513
const armForceExitTimer = (forceExitMs: number) => {
506514
if (forceExitTimer) {
507515
return;
@@ -524,13 +532,24 @@ export async function runGatewayLoop(params: {
524532
}
525533
})();
526534
}, forceExitMs);
535+
if (params.ownsProcessLifecycle === true) {
536+
hardExitWatchdog = armShutdownHardExitWatchdog({
537+
delayMs: forceExitMs + HARD_EXIT_WATCHDOG_GRACE_MS,
538+
onError: (error) => {
539+
gatewayLog.warn(
540+
`hard-exit watchdog failed; retaining main-thread shutdown timer: ${formatErrorMessage(error)}`,
541+
);
542+
},
543+
});
544+
}
527545
};
528546
const clearForceExitTimer = () => {
529-
if (!forceExitTimer) {
530-
return;
547+
if (forceExitTimer) {
548+
clearTimeout(forceExitTimer);
549+
forceExitTimer = null;
531550
}
532-
clearTimeout(forceExitTimer);
533-
forceExitTimer = null;
551+
hardExitWatchdog?.cancel();
552+
hardExitWatchdog = null;
534553
};
535554
if (isRestart) {
536555
forceActiveRestartExit = () => {

‎src/cli/gateway-cli/run.option-collisions.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ type GatewayLoopStart = (params?: { startupStartedAt?: number }) => Promise<unkn
4545
type GatewayLoopParams = {
4646
start: GatewayLoopStart;
4747
completeBoot?: (completion: unknown) => void;
48+
ownsProcessLifecycle?: boolean;
49+
runtime?: unknown;
4850
};
4951
const runGatewayLoop = vi.fn(async ({ start }: GatewayLoopParams) => {
5052
await start();
@@ -506,6 +508,9 @@ describe("gateway run option collisions", () => {
506508

507509
expect(beforeRun).toHaveBeenCalledOnce();
508510
expect(callOrder).toEqual(["bootstrap", "normalize", "normalize", "start"]);
511+
expect(runGatewayLoop).toHaveBeenCalledWith(
512+
expect.objectContaining({ ownsProcessLifecycle: true, runtime: defaultRuntime }),
513+
);
509514
});
510515

511516
it("rejects invalid gateway ports before startup", async () => {

‎src/cli/gateway-cli/run.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1182,6 +1182,7 @@ async function runGatewayCommandOnce(opts: GatewayRunOpts, hooks: GatewayRunRunt
11821182
const startLoop = async () =>
11831183
await runGatewayLoop({
11841184
runtime: defaultRuntime,
1185+
ownsProcessLifecycle: true,
11851186
lockPort: port,
11861187
healthHost,
11871188
beginBoot,
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// Process-boundary proof that the hard-exit watchdog survives main-thread starvation.
2+
import { spawnSync } from "node:child_process";
3+
import path from "node:path";
4+
import { pathToFileURL } from "node:url";
5+
import { describe, expect, it } from "vitest";
6+
7+
const WATCHDOG_DELAY_MS = 100;
8+
const CHILD_TIMEOUT_MS = 3_000;
9+
const watchdogModuleUrl = pathToFileURL(
10+
path.resolve("src/cli/gateway-cli/shutdown-hard-exit.ts"),
11+
).href;
12+
13+
function runWatchdogChild(source: string) {
14+
const script = `
15+
import { armShutdownHardExitWatchdog } from ${JSON.stringify(watchdogModuleUrl)};
16+
${source}
17+
`;
18+
const startedAt = Date.now();
19+
const result = spawnSync(
20+
process.execPath,
21+
["--import", "tsx", "--input-type=module", "--eval", script],
22+
{
23+
cwd: path.resolve("."),
24+
encoding: "utf8",
25+
env: { ...process.env, VITEST: undefined },
26+
killSignal: "SIGKILL",
27+
timeout: CHILD_TIMEOUT_MS,
28+
},
29+
);
30+
return { elapsedMs: Date.now() - startedAt, result };
31+
}
32+
33+
describe("shutdown hard-exit watchdog", () => {
34+
it("kills a process whose main thread is synchronously blocked", () => {
35+
const { elapsedMs, result } = runWatchdogChild(`
36+
armShutdownHardExitWatchdog({
37+
delayMs: ${WATCHDOG_DELAY_MS},
38+
onError: (error) => console.error(error),
39+
});
40+
while (true) {}
41+
`);
42+
43+
expect(result.error).toBeUndefined();
44+
expect(result.signal).toBe("SIGKILL");
45+
expect(elapsedMs).toBeLessThan(CHILD_TIMEOUT_MS);
46+
});
47+
48+
it("lets a cancelled process survive beyond the deadline and exit cleanly", () => {
49+
const { elapsedMs, result } = runWatchdogChild(`
50+
const watchdog = armShutdownHardExitWatchdog({
51+
delayMs: ${WATCHDOG_DELAY_MS},
52+
onError: (error) => {
53+
console.error(error);
54+
process.exitCode = 2;
55+
},
56+
});
57+
watchdog?.cancel();
58+
await new Promise((resolve) => setTimeout(resolve, ${WATCHDOG_DELAY_MS * 2}));
59+
`);
60+
61+
expect(result.error).toBeUndefined();
62+
expect(result.status).toBe(0);
63+
expect(result.signal).toBeNull();
64+
expect(elapsedMs).toBeGreaterThanOrEqual(WATCHDOG_DELAY_MS * 2);
65+
expect(elapsedMs).toBeLessThan(CHILD_TIMEOUT_MS);
66+
});
67+
});
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import { Worker } from "node:worker_threads";
2+
3+
export type ShutdownHardExitWatchdog = {
4+
cancel: () => void;
5+
};
6+
7+
export function armShutdownHardExitWatchdog(params: {
8+
delayMs: number;
9+
onError: (error: unknown) => void;
10+
}): ShutdownHardExitWatchdog | null {
11+
const reportError = (error: unknown) => {
12+
try {
13+
params.onError(error);
14+
} catch {
15+
// Shutdown must retain the main-thread fallback even if warning delivery fails.
16+
}
17+
};
18+
let worker: Worker;
19+
try {
20+
worker = new Worker(
21+
`const { parentPort, workerData } = require("node:worker_threads");
22+
const timer = setTimeout(() => process.kill(process.pid, "SIGKILL"), workerData.delayMs);
23+
parentPort.once("message", () => {
24+
clearTimeout(timer);
25+
parentPort.close();
26+
});`,
27+
{
28+
eval: true,
29+
execArgv: [],
30+
workerData: { delayMs: Math.max(0, Math.floor(params.delayMs)) },
31+
},
32+
);
33+
} catch (error) {
34+
reportError(error);
35+
return null;
36+
}
37+
38+
let active = true;
39+
worker.once("error", (error) => {
40+
if (active) {
41+
active = false;
42+
reportError(error);
43+
}
44+
});
45+
46+
return {
47+
cancel: () => {
48+
active = false;
49+
try {
50+
worker.postMessage("cancel", []);
51+
} catch (error) {
52+
reportError(error);
53+
}
54+
},
55+
};
56+
}

‎src/gateway/server-close.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ const HTTP_CLOSE_GRACE_MS = 1_000;
3939
const HTTP_CLOSE_FORCE_WAIT_MS = 5_000;
4040
const GATEWAY_SHUTDOWN_HOOK_TIMEOUT_MS = 5_000;
4141
const GATEWAY_PRE_RESTART_HOOK_TIMEOUT_MS = 10_000;
42+
const AGENT_HARNESS_CLOSE_GRACE_MS = 5_000;
4243

4344
vi.mock("../channels/plugins/index.js", async () => ({
4445
...(await vi.importActual<typeof import("../channels/plugins/index.js")>(
@@ -1688,6 +1689,44 @@ describe("createGatewayCloseHandler", () => {
16881689
]);
16891690
});
16901691

1692+
it("continues listener teardown when agent harness disposal never settles", async () => {
1693+
vi.useFakeTimers();
1694+
let releaseHarnessDisposal: (() => void) | undefined;
1695+
const harnessDisposal = new Promise<undefined>((resolve) => {
1696+
releaseHarnessDisposal = () => resolve(undefined);
1697+
});
1698+
mocks.disposeAgentHarnesses.mockReturnValue(harnessDisposal);
1699+
const httpClose = vi.fn((callback: (err?: Error | null) => void) => callback(null));
1700+
const close = createGatewayCloseHandler(
1701+
createGatewayCloseTestDeps({
1702+
httpServer: {
1703+
close: httpClose,
1704+
closeIdleConnections: vi.fn(),
1705+
} as never,
1706+
}),
1707+
);
1708+
const closePromise = close({ reason: "test shutdown" });
1709+
1710+
try {
1711+
await vi.waitFor(() => expect(mocks.disposeAgentHarnesses).toHaveBeenCalledOnce());
1712+
expect(httpClose).not.toHaveBeenCalled();
1713+
1714+
await vi.advanceTimersByTimeAsync(AGENT_HARNESS_CLOSE_GRACE_MS);
1715+
const result = await closePromise;
1716+
1717+
expect(result.warnings).toContain("agent-harnesses");
1718+
expect(httpClose).toHaveBeenCalledOnce();
1719+
expect(
1720+
mocks.logWarn.mock.calls.some(([message]) =>
1721+
String(message).includes("agent-harnesses runtime disposal exceeded 5000ms"),
1722+
),
1723+
).toBe(true);
1724+
} finally {
1725+
releaseHarnessDisposal?.();
1726+
await closePromise;
1727+
}
1728+
});
1729+
16911730
it("starts bundle MCP and LSP runtime disposal concurrently", async () => {
16921731
const disposalOrder: string[] = [];
16931732
let releaseMcp: (() => void) | undefined;

0 commit comments

Comments
 (0)