Skip to content

Commit c003292

Browse files
authored
fix: restore channel recovery after crash-loop suppression (#134165)
Restores configured channel recovery after crash-loop suppression while preserving unavailable-secret isolation and Gateway lifetime fencing. Refs #134134.
1 parent 9323eae commit c003292

12 files changed

Lines changed: 380 additions & 134 deletions

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1781,6 +1781,8 @@ describe("gateway run option collisions", () => {
17811781
});
17821782

17831783
it("re-inspects crash-loop breaker state for each boot iteration", async () => {
1784+
let firstBootRecovery: (() => boolean) | undefined;
1785+
bootLifecycle.record.mockReturnValueOnce("boot-1").mockReturnValueOnce("boot-2");
17841786
runGatewayLoop.mockImplementationOnce(
17851787
async ({
17861788
beginBoot,
@@ -1791,6 +1793,7 @@ describe("gateway run option collisions", () => {
17911793
}) => {
17921794
await beginBoot?.(1000);
17931795
await start({ startupStartedAt: 1000 });
1796+
firstBootRecovery = gatewayStartOptions(0).tryRecoverChannelAutostartSuppression;
17941797
await beginBoot?.(2000);
17951798
await start({ startupStartedAt: 2000 });
17961799
},
@@ -1828,6 +1831,16 @@ describe("gateway run option collisions", () => {
18281831
bootLifecycle.manualChannelStartHint,
18291832
);
18301833
expect(gatewayStartOptions(1).channelAutostartSuppression).toBeUndefined();
1834+
bootLifecycle.decisions.push({
1835+
tripped: false,
1836+
uncleanBoots: 0,
1837+
windowMs: 300_000,
1838+
shouldWriteStabilityBundle: false,
1839+
recovered: true,
1840+
});
1841+
expect(firstBootRecovery?.()).toBe(false);
1842+
expect(bootLifecycle.inspect).toHaveBeenCalledTimes(2);
1843+
expect(bootLifecycle.recover).not.toHaveBeenCalled();
18311844
expect(gatewayLogMessages.some((message) => message.includes("breaker recovered"))).toBe(true);
18321845
});
18331846

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

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1125,23 +1125,8 @@ async function runGatewayCommandOnce(opts: GatewayRunOpts, hooks: GatewayRunRunt
11251125
: "start";
11261126
let crashLoopDecision: GatewayCrashLoopBreakerDecision | undefined;
11271127
let channelAutostartSuppression: { reason: "crash-loop-breaker"; message: string } | undefined;
1128+
let tryRecoverChannelAutostartSuppression: (() => boolean) | undefined;
11281129
let activeBootId: string | undefined;
1129-
const tryRecoverChannelAutostartSuppression = () => {
1130-
const decision = inspectGatewayCrashLoopBreaker(process.env);
1131-
// The current safe-mode boot remains an open row until the full window has
1132-
// drained. Requiring zero prevents a near-expiry history from restoring
1133-
// channels before this process itself has proven stable for the whole window.
1134-
if (!decision.recovered || decision.uncleanBoots !== 0) {
1135-
return false;
1136-
}
1137-
const recoveredBootId = recordGatewayCrashLoopRecovery(activeBootId, process.env);
1138-
if (!recoveredBootId) {
1139-
return false;
1140-
}
1141-
activeBootId = recoveredBootId;
1142-
gatewayLog.info("gateway restart-loop breaker recovered; channel auto-start restored");
1143-
return true;
1144-
};
11451130
const beginBoot = async (startedAtMs: number) => {
11461131
// run-loop calls beginBoot before every startGatewayServer invocation, so
11471132
// in-process restarts re-evaluate breaker state instead of reusing stale mode.
@@ -1157,6 +1142,7 @@ async function runGatewayCommandOnce(opts: GatewayRunOpts, hooks: GatewayRunRunt
11571142
// row exists for Doctor to reconcile after it repairs the schema.
11581143
activeBootId = recordGatewayBootStart(process.env, startedAtMs, bootStartReason);
11591144
channelAutostartSuppression = undefined;
1145+
tryRecoverChannelAutostartSuppression = undefined;
11601146
if (crashLoopDecision.recovered) {
11611147
gatewayLog.info("gateway restart-loop breaker recovered; channel auto-start restored");
11621148
}
@@ -1167,6 +1153,26 @@ async function runGatewayCommandOnce(opts: GatewayRunOpts, hooks: GatewayRunRunt
11671153
`gateway restart-loop breaker tripped: ${crashLoopDecision.uncleanBoots} unclean boot(s) within ${crashLoopDecision.windowMs}ms; ` +
11681154
`suppressing channel/provider account auto-start. Inspect the stability bundle and fix the startup crash before restarting the service. ${formatGatewayCrashLoopManualChannelStartHint()}`;
11691155
channelAutostartSuppression = { reason: "crash-loop-breaker", message };
1156+
const suppressedBootId = activeBootId;
1157+
tryRecoverChannelAutostartSuppression = () => {
1158+
if (!suppressedBootId || activeBootId !== suppressedBootId) {
1159+
return false;
1160+
}
1161+
const decision = inspectGatewayCrashLoopBreaker(process.env);
1162+
// The current safe-mode boot remains an open row until the full window has
1163+
// drained. Requiring zero prevents a near-expiry history from restoring
1164+
// channels before this process itself has proven stable for the whole window.
1165+
if (!decision.recovered || decision.uncleanBoots !== 0) {
1166+
return false;
1167+
}
1168+
const recoveredBootId = recordGatewayCrashLoopRecovery(suppressedBootId, process.env);
1169+
if (!recoveredBootId || activeBootId !== suppressedBootId) {
1170+
return false;
1171+
}
1172+
activeBootId = recoveredBootId;
1173+
gatewayLog.info("gateway restart-loop breaker recovered; channel auto-start restored");
1174+
return true;
1175+
};
11701176
gatewayLog.error(message);
11711177
if (crashLoopDecision.shouldWriteStabilityBundle) {
11721178
await maybeWriteGatewayStartupFailureBundle(

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

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,7 @@ function createManager(options?: {
271271
fillChannelDependencies?: boolean;
272272
ambientAutostartSuppressedChannelIds?: ReadonlySet<string>;
273273
tryRecoverAutostartSuppression?: () => boolean;
274+
isClosing?: () => boolean;
274275
getNativeApprovalRuntime?: () => GatewayNativeApprovalRuntime | undefined;
275276
}) {
276277
const log = createSubsystemLogger("gateway/server-channels-test");
@@ -302,6 +303,7 @@ function createManager(options?: {
302303
...(options?.tryRecoverAutostartSuppression
303304
? { tryRecoverAutostartSuppression: options.tryRecoverAutostartSuppression }
304305
: {}),
306+
...(options?.isClosing ? { isClosing: options.isClosing } : {}),
305307
...(options?.getNativeApprovalRuntime
306308
? { getNativeApprovalRuntime: options.getNativeApprovalRuntime }
307309
: {}),
@@ -2555,6 +2557,32 @@ describe("server-channels auto restart", () => {
25552557
expect(manager.isManuallyStopped("discord", DEFAULT_ACCOUNT_ID)).toBe(true);
25562558
});
25572559

2560+
it("does not start recovered accounts after gateway close begins during handoff", async () => {
2561+
const accountStartReady = createDeferred();
2562+
const startAccount = vi.fn(async () => {});
2563+
let closing = false;
2564+
installTestRegistry(createTestPlugin({ startAccount }));
2565+
const manager = createManager({
2566+
deferStartupAccountStartsUntil: accountStartReady.promise,
2567+
isClosing: () => closing,
2568+
tryRecoverAutostartSuppression: () => true,
2569+
});
2570+
manager.setAutostartSuppression({
2571+
reason: "crash-loop-breaker",
2572+
message: "safe mode",
2573+
});
2574+
2575+
const recovery = manager.recoverAutostartSuppression();
2576+
await flushMicrotasks();
2577+
closing = true;
2578+
accountStartReady.resolve();
2579+
await recovery;
2580+
await flushMicrotasks();
2581+
2582+
expect(manager.getAutostartSuppression()).toBeNull();
2583+
expect(startAccount).not.toHaveBeenCalled();
2584+
});
2585+
25582586
it("keeps suppression when persisted recovery is not proven", async () => {
25592587
const startAccount = vi.fn(async () => {});
25602588
installTestRegistry(createTestPlugin({ startAccount }));

‎src/gateway/server-channels.ts‎

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,7 @@ type ChannelManagerOptions = {
236236
getNativeApprovalRuntime?: () => GatewayNativeApprovalRuntime | undefined;
237237
ambientAutostartSuppressedChannelIds?: ReadonlySet<string>;
238238
tryRecoverAutostartSuppression?: () => boolean;
239+
isClosing?: () => boolean;
239240
};
240241

241242
type StopChannelOptions = {
@@ -823,7 +824,7 @@ export function createChannelManager(opts: ChannelManagerOptions): ChannelManage
823824
} else if (startupTrace) {
824825
await waitForChannelStartupHandoff();
825826
}
826-
if (abort.signal.aborted || manuallyStopped.has(rKey)) {
827+
if (abort.signal.aborted || manuallyStopped.has(rKey) || opts.isClosing?.()) {
827828
return;
828829
}
829830
const gatewayApprovalRuntime = opts.getNativeApprovalRuntime?.();
@@ -855,7 +856,7 @@ export function createChannelManager(opts: ChannelManagerOptions): ChannelManage
855856
}
856857
let startAccountTask: ReturnType<typeof startAccount> | undefined;
857858
await measureStartup(`channels.${channelId}.start-account-handoff`, () => {
858-
if (abort.signal.aborted || manuallyStopped.has(rKey)) {
859+
if (abort.signal.aborted || manuallyStopped.has(rKey) || opts.isClosing?.()) {
859860
return;
860861
}
861862
const runStartAccount = () => {
@@ -917,7 +918,12 @@ export function createChannelManager(opts: ChannelManagerOptions): ChannelManage
917918
// Only the task that still owns the store slot may write lifecycle state.
918919
const trackedPromise = task
919920
.then(() => {
920-
if (abort.signal.aborted || manuallyStopped.has(rKey) || !isCurrentTask()) {
921+
if (
922+
abort.signal.aborted ||
923+
manuallyStopped.has(rKey) ||
924+
opts.isClosing?.() ||
925+
!isCurrentTask()
926+
) {
921927
return;
922928
}
923929
if (getRuntime(channelId, id).terminalDisconnect) {
@@ -930,7 +936,7 @@ export function createChannelManager(opts: ChannelManagerOptions): ChannelManage
930936
log.error?.(`[${id}] ${message}`);
931937
})
932938
.catch((err: unknown) => {
933-
if (!isCurrentTask() || store.stops.has(id)) {
939+
if (!isCurrentTask() || store.stops.has(id) || opts.isClosing?.()) {
934940
return;
935941
}
936942
const message = formatErrorMessage(err);
@@ -948,15 +954,15 @@ export function createChannelManager(opts: ChannelManagerOptions): ChannelManage
948954
await cleanupTaskScopedApprovalRuntime("channel cleanup failed");
949955
// stopChannel owns the failed-teardown snapshot until a later
950956
// successful stop proves replacement is safe.
951-
if (!isCurrentTask() || store.stops.has(id)) {
957+
if (!isCurrentTask() || store.stops.has(id) || opts.isClosing?.()) {
952958
return;
953959
}
954960
setStoppedRuntime(channelId, id, {
955961
lastStopAt: Date.now(),
956962
});
957963
})
958964
.then(async () => {
959-
if (!isCurrentTask() || store.stops.has(id)) {
965+
if (!isCurrentTask() || store.stops.has(id) || opts.isClosing?.()) {
960966
return;
961967
}
962968
if (manuallyStopped.has(rKey)) {
@@ -1052,7 +1058,7 @@ export function createChannelManager(opts: ChannelManagerOptions): ChannelManage
10521058
pendingAutoRestarts.add(rKey);
10531059
try {
10541060
await sleepWithAbort(retry.delayMs, retry.signal);
1055-
if (manuallyStopped.has(rKey)) {
1061+
if (manuallyStopped.has(rKey) || opts.isClosing?.()) {
10561062
return;
10571063
}
10581064
if (store.tasks.get(id) === trackedPromise) {
@@ -1350,7 +1356,12 @@ export function createChannelManager(opts: ChannelManagerOptions): ChannelManage
13501356
const startChannels = async () => await startChannelsWithOptions();
13511357

13521358
const recoverAutostartSuppression = async (): Promise<boolean> => {
1353-
if (!autostartSuppression || !opts.tryRecoverAutostartSuppression?.()) {
1359+
if (
1360+
!autostartSuppression ||
1361+
opts.isClosing?.() ||
1362+
!opts.tryRecoverAutostartSuppression?.() ||
1363+
opts.isClosing?.()
1364+
) {
13541365
return false;
13551366
}
13561367
autostartSuppression = null;

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

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import fs from "node:fs/promises";
22
import { describe, expect, it, vi } from "vitest";
33
import { createDeferred } from "../../test/helpers/promise.js";
4+
import type { ChannelPlugin } from "../channels/plugins/types.public.js";
45
import { flushDiagnosticsTimeline } from "../infra/diagnostics-timeline.js";
56
import { createPluginRecord } from "../plugins/loader-records.js";
67
import { createEmptyPluginRegistry } from "../plugins/registry-empty.js";
@@ -20,6 +21,105 @@ import { createGatewayKernel } from "./server-kernel.js";
2021
import { createSyntheticPluginRuntimeClient } from "./server-plugin-runtime-client.js";
2122

2223
describe("createGatewayKernel", () => {
24+
it("does not start recovered channels after close prelude begins", async () => {
25+
const port = await getFreePort();
26+
const state = await createOpenClawTestState({
27+
label: "gateway-kernel-breaker-recovery-close",
28+
layout: "home",
29+
env: {
30+
OPENCLAW_GATEWAY_PASSWORD: undefined,
31+
OPENCLAW_GATEWAY_TOKEN: undefined,
32+
OPENCLAW_SKIP_BROWSER_CONTROL_SERVER: "1",
33+
OPENCLAW_SKIP_CANVAS_HOST: "1",
34+
OPENCLAW_SKIP_CHANNELS: undefined,
35+
OPENCLAW_SKIP_CRON: "1",
36+
OPENCLAW_SKIP_GMAIL_WATCHER: "1",
37+
OPENCLAW_SKIP_PROVIDERS: undefined,
38+
OPENCLAW_TEST_MINIMAL_GATEWAY: "0",
39+
VITEST: "1",
40+
},
41+
});
42+
const originalPluginRegistry = captureActivePluginRegistrySnapshot();
43+
const startAccount = vi.fn(async () => {});
44+
const channelPlugin: ChannelPlugin = {
45+
...createChannelTestPluginBase({
46+
id: "telegram",
47+
config: {
48+
listAccountIds: (config) => Object.keys(config.channels?.telegram?.accounts ?? {}),
49+
resolveAccount: (config, accountId) =>
50+
config.channels?.telegram?.accounts?.[accountId ?? "default"] ?? {},
51+
isConfigured: (account) =>
52+
typeof (account as { botToken?: unknown }).botToken === "string",
53+
},
54+
}),
55+
gateway: { startAccount },
56+
};
57+
const registry = createTestRegistry([
58+
{
59+
pluginId: channelPlugin.id,
60+
plugin: channelPlugin,
61+
source: "gateway-kernel-test",
62+
},
63+
]);
64+
registry.plugins.push(
65+
createPluginRecord({
66+
id: channelPlugin.id,
67+
source: "gateway-kernel-test",
68+
origin: "bundled",
69+
enabled: true,
70+
configSchema: false,
71+
}),
72+
);
73+
let kernel: Awaited<ReturnType<typeof createGatewayKernel>> | undefined;
74+
try {
75+
stageActivePluginRegistry(registry, null, "default");
76+
const token = "gateway-kernel-breaker-recovery-token";
77+
await state.writeConfig({
78+
gateway: {
79+
auth: { mode: "token", token },
80+
controlUi: { enabled: false },
81+
port,
82+
},
83+
channels: {
84+
telegram: {
85+
accounts: {
86+
default: { botToken: "telegram-breaker-recovery-token" },
87+
},
88+
},
89+
},
90+
});
91+
state.applyEnv();
92+
kernel = await createGatewayKernel(port, {
93+
auth: { mode: "token", token },
94+
bind: "loopback",
95+
channelAutostartSuppression: {
96+
reason: "crash-loop-breaker",
97+
message: "safe mode",
98+
},
99+
controlUiEnabled: false,
100+
sidecarStartup: "defer",
101+
tryRecoverChannelAutostartSuppression: () => true,
102+
});
103+
104+
await expect(kernel.channelManager.recoverAutostartSuppression()).resolves.toBe(true);
105+
expect(startAccount).not.toHaveBeenCalled();
106+
107+
await kernel.beginClosePrelude();
108+
kernel.releaseStartupAccountStarts();
109+
await new Promise<void>((resolve) => setImmediate(resolve));
110+
111+
expect(startAccount).not.toHaveBeenCalled();
112+
expect(kernel.channelManager.isAutoRestartScheduled("telegram", "default")).toBe(false);
113+
} finally {
114+
try {
115+
await kernel?.closeOnStartupFailure();
116+
} finally {
117+
restoreActivePluginRegistrySnapshot(originalPluginRegistry);
118+
await state.cleanup();
119+
}
120+
}
121+
});
122+
23123
it("reports startup and readiness as draining during a direct close", async () => {
24124
const port = 19_789;
25125
const state = await createOpenClawTestState({

‎src/gateway/server-runtime-state-prepare.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,7 @@ export async function prepareGatewayKernelState(params: {
444444
...(opts.tryRecoverChannelAutostartSuppression
445445
? { tryRecoverAutostartSuppression: opts.tryRecoverChannelAutostartSuppression }
446446
: {}),
447+
isClosing: () => lifecycle.closePreludeStarted,
447448
});
448449
channelManager.setAutostartSuppression(opts.channelAutostartSuppression ?? null);
449450
const sidecarStartup = opts.sidecarStartup ?? "start";

‎src/gateway/server-startup-bootstrap.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,6 @@ export async function prepareGatewayServerBootstrap(input: {
221221
const activateRuntimeSecrets = createRuntimeSecretsActivator({
222222
logSecrets,
223223
emitStateEvent: emitSecretsStateEvent,
224-
channelAutostartSuppression: opts.channelAutostartSuppression,
225224
...(startupConfigLoad.pluginMetadataSnapshot
226225
? { pluginMetadataSnapshot: startupConfigLoad.pluginMetadataSnapshot }
227226
: {}),

0 commit comments

Comments
 (0)