Skip to content

Commit ec7e5dd

Browse files
steipetePeter Steinberger
andauthored
fix(gateway): recover channel autostart after crash loops (#118311)
* fix(gateway): recover channel autostart after crash loops * docs(gateway): clarify crash-loop recovery steps * test(gateway): type crash-loop recovery context * test(gateway): correct recovery mock context * test(gateway): keep recovery monitor coverage compact * chore: leave crash-loop note to release flow --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 899be35 commit ec7e5dd

13 files changed

Lines changed: 322 additions & 22 deletions

‎docs/channels/troubleshooting.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -161,8 +161,9 @@ If the gateway process is healthy but a channel stays stopped after repeated
161161
unclean boots, the [crash-loop breaker](/gateway/restart-recovery#safety-valves-and-observability)
162162
may be suppressing channel auto-start. Use
163163
`openclaw gateway call channels.start --params '{"channel":"<id>"}'` to
164-
override, or wait for the unclean-boot window to drain and then restart the
165-
gateway.
164+
override immediately, or leave the healthy gateway running. After the full
165+
unclean-boot window drains, the same process rechecks the breaker and resumes
166+
deferred channel auto-start.
166167

167168
## Related
168169

‎docs/gateway/restart-recovery.md‎

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -182,14 +182,15 @@ restart handling continues.
182182

183183
- **Crash-loop breaker:** 3 unclean boots within 5 minutes trip a breaker that
184184
suppresses auto-start side services on the next boot, so a crashing gateway
185-
does not amplify itself. A later boot recovers once the unclean-boot window
186-
drains.
185+
does not amplify itself. A continuously stable safe-mode gateway rechecks the
186+
breaker after the full unclean-boot window drains and then resumes deferred
187+
channel auto-start without requiring another gateway restart.
187188

188189
When the breaker is tripped, the **control plane still starts**, but channel
189-
plugins (and other auto-started side services) stay down for the current boot
190-
unless an operator manually overrides the suppression. Automatic startup
191-
resumes on a later boot after the unclean-boot window drains. Gateway logs
192-
look like:
190+
plugins (and other auto-started side services) stay down until an operator
191+
manually overrides the suppression or the full window drains with no unclean
192+
boots. Recovery preserves channels that an operator manually stopped and any
193+
separate development-mode suppression. Gateway logs look like:
193194
`channel autostart suppressed by crash-loop breaker; refusing automatic
194195
start for <channel>… Start a channel manually with: openclaw gateway call
195196
channels.start --params '{"channel":"<id>"}'`
@@ -214,8 +215,12 @@ channels.start --params '{"channel":"<id>"}'`
214215
`channels.start` is a **manual** override; it does not disable the
215216
breaker for other channels.
216217

217-
5. Or wait for the unclean-boot window to drain, then restart the gateway.
218-
The next boot logs whether channel auto-start is restored.
218+
5. Or leave the healthy gateway running until the full unclean-boot window
219+
drains. The same process logs that the restart-loop breaker recovered and
220+
starts the deferred configured channels.
221+
If that message does not appear after the window plus one health-monitor
222+
interval, inspect the gateway logs and run `openclaw doctor` before
223+
restarting.
219224

220225
See also [Gateway](/gateway) (safe mode paragraph) for the same control-plane
221226
vs channel-autostart split.

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

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,10 @@ const bootLifecycle = vi.hoisted(() => ({
123123
record: vi.fn(
124124
(_env?: NodeJS.ProcessEnv, _nowMs?: number, _reason?: string): string | undefined => "boot-id",
125125
),
126+
recover: vi.fn(
127+
(_bootId?: string, _env?: NodeJS.ProcessEnv, _nowMs?: number): string | undefined =>
128+
"recovered-boot-id",
129+
),
126130
complete: vi.fn(),
127131
}));
128132
const netState = vi.hoisted(() => ({
@@ -317,6 +321,8 @@ vi.mock("../../infra/gateway-boot-lifecycle.js", () => ({
317321
bootLifecycle.inspect(env, nowMs),
318322
recordGatewayBootStart: (env?: NodeJS.ProcessEnv, nowMs?: number, reason?: string) =>
319323
bootLifecycle.record(env, nowMs, reason),
324+
recordGatewayCrashLoopRecovery: (bootId?: string, env?: NodeJS.ProcessEnv, nowMs?: number) =>
325+
bootLifecycle.recover(bootId, env, nowMs),
320326
completeGatewayBootLifecycle: (bootId: string | undefined, completion: unknown) =>
321327
bootLifecycle.complete(bootId, completion),
322328
}));
@@ -409,6 +415,7 @@ describe("gateway run option collisions", () => {
409415
bootLifecycle.decisions.length = 0;
410416
bootLifecycle.inspect.mockClear();
411417
bootLifecycle.record.mockClear();
418+
bootLifecycle.recover.mockClear();
412419
bootLifecycle.complete.mockClear();
413420
startGatewayServer.mockClear();
414421
setGatewayWsLogStyle.mockClear();
@@ -467,6 +474,7 @@ describe("gateway run option collisions", () => {
467474
auth?: { mode?: string; token?: string; password?: string };
468475
bind?: string;
469476
channelAutostartSuppression?: { reason?: string; message?: string };
477+
tryRecoverChannelAutostartSuppression?: () => boolean;
470478
ambientEnvTriggers?: "allow" | "suppress";
471479
startupConfigSnapshotRead?: { snapshot?: Record<string, unknown> };
472480
startupStartedAt?: number;
@@ -1594,6 +1602,55 @@ describe("gateway run option collisions", () => {
15941602
expect(gatewayLogMessages.some((message) => message.includes("breaker recovered"))).toBe(true);
15951603
});
15961604

1605+
it("recovers channel autostart only after the full breaker window drains", async () => {
1606+
runGatewayLoop.mockImplementationOnce(
1607+
async ({
1608+
beginBoot,
1609+
start,
1610+
}: {
1611+
beginBoot?: (startedAtMs: number) => Promise<void> | void;
1612+
start: GatewayLoopStart;
1613+
}) => {
1614+
await beginBoot?.(1000);
1615+
await start({ startupStartedAt: 1000 });
1616+
},
1617+
);
1618+
bootLifecycle.decisions.push({
1619+
tripped: true,
1620+
uncleanBoots: 3,
1621+
windowMs: 300_000,
1622+
shouldWriteStabilityBundle: false,
1623+
recovered: false,
1624+
});
1625+
1626+
await runGatewayCli(["gateway", "run", "--allow-unconfigured"]);
1627+
1628+
const recover = gatewayStartOptions().tryRecoverChannelAutostartSuppression;
1629+
expect(recover).toBeTypeOf("function");
1630+
bootLifecycle.decisions.push(
1631+
{
1632+
tripped: false,
1633+
uncleanBoots: 1,
1634+
windowMs: 300_000,
1635+
shouldWriteStabilityBundle: false,
1636+
recovered: true,
1637+
},
1638+
{
1639+
tripped: false,
1640+
uncleanBoots: 0,
1641+
windowMs: 300_000,
1642+
shouldWriteStabilityBundle: false,
1643+
recovered: true,
1644+
},
1645+
);
1646+
1647+
expect(recover?.()).toBe(false);
1648+
expect(bootLifecycle.recover).not.toHaveBeenCalled();
1649+
expect(recover?.()).toBe(true);
1650+
expect(bootLifecycle.recover).toHaveBeenCalledWith("boot-id", process.env, undefined);
1651+
expect(gatewayLogMessages.some((message) => message.includes("breaker recovered"))).toBe(true);
1652+
});
1653+
15971654
it("skips failure bundles but exits nonzero for unconfirmed gateway lock conflicts", async () => {
15981655
const port = await getFreePort();
15991656
configState.snapshot = {

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ import {
4343
GATEWAY_CRASH_LOOP_RECOVERED_REASON,
4444
inspectGatewayCrashLoopBreaker,
4545
recordGatewayBootStart,
46+
recordGatewayCrashLoopRecovery,
4647
type GatewayCrashLoopBreakerDecision,
4748
type GatewayBootLifecycleCompletion,
4849
} from "../../infra/gateway-boot-lifecycle.js";
@@ -1136,6 +1137,22 @@ async function runGatewayCommandOnce(opts: GatewayRunOpts, hooks: GatewayRunRunt
11361137
let crashLoopDecision: GatewayCrashLoopBreakerDecision | undefined;
11371138
let channelAutostartSuppression: { reason: "crash-loop-breaker"; message: string } | undefined;
11381139
let activeBootId: string | undefined;
1140+
const tryRecoverChannelAutostartSuppression = () => {
1141+
const decision = inspectGatewayCrashLoopBreaker(process.env);
1142+
// The current safe-mode boot remains an open row until the full window has
1143+
// drained. Requiring zero prevents a near-expiry history from restoring
1144+
// channels before this process itself has proven stable for the whole window.
1145+
if (!decision.recovered || decision.uncleanBoots !== 0) {
1146+
return false;
1147+
}
1148+
const recoveredBootId = recordGatewayCrashLoopRecovery(activeBootId, process.env);
1149+
if (!recoveredBootId) {
1150+
return false;
1151+
}
1152+
activeBootId = recoveredBootId;
1153+
gatewayLog.info("gateway restart-loop breaker recovered; channel auto-start restored");
1154+
return true;
1155+
};
11391156
const beginBoot = async (startedAtMs: number) => {
11401157
// run-loop calls beginBoot before every startGatewayServer invocation, so
11411158
// in-process restarts re-evaluate breaker state instead of reusing stale mode.
@@ -1194,6 +1211,7 @@ async function runGatewayCommandOnce(opts: GatewayRunOpts, hooks: GatewayRunRunt
11941211
: {}),
11951212
...(envSidecarStartupMode !== "start" ? { sidecarStartup: envSidecarStartupMode } : {}),
11961213
...(channelAutostartSuppression ? { channelAutostartSuppression } : {}),
1214+
...(channelAutostartSuppression ? { tryRecoverChannelAutostartSuppression } : {}),
11971215
...(devMode
11981216
? {
11991217
ambientEnvTriggers: devAmbientEnvTriggers,

‎src/gateway/channel-health-monitor.test.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ function createMockChannelManager(overrides?: Partial<ChannelManager>): ChannelM
1717
stopChannel: vi.fn(async () => {}),
1818
setAutostartSuppression: vi.fn(),
1919
getAutostartSuppression: vi.fn(() => null),
20+
recoverAutostartSuppression: vi.fn(async () => false),
2021
setAmbientAutostartSuppressedChannelIds: vi.fn(),
2122
isAmbientAutostartSuppressed: vi.fn(() => false),
2223
markChannelLoggedOut: vi.fn(),
@@ -283,7 +284,12 @@ describe("channel-health-monitor", () => {
283284

284285
it("treats crash-loop suppressed accounts as expected stopped", async () => {
285286
let suppressed = true;
287+
let allowRecovery = false;
286288
const suppression = { reason: "crash-loop-breaker" as const, message: "safe mode" };
289+
const recoverAutostartSuppression = vi.fn(async () => {
290+
suppressed = !allowRecovery;
291+
return allowRecovery;
292+
});
287293
const manager = createSnapshotManager(
288294
{
289295
discord: {
@@ -292,6 +298,7 @@ describe("channel-health-monitor", () => {
292298
},
293299
{
294300
getAutostartSuppression: vi.fn(() => (suppressed ? suppression : null)),
301+
recoverAutostartSuppression,
295302
},
296303
);
297304
const monitor = startDefaultMonitor(manager, {
@@ -305,9 +312,10 @@ describe("channel-health-monitor", () => {
305312
expect(manager.resetRestartAttempts).not.toHaveBeenCalled();
306313
expect(manager.startChannel).not.toHaveBeenCalled();
307314

308-
suppressed = false;
315+
allowRecovery = true;
309316
await vi.advanceTimersByTimeAsync(101);
310317

318+
expect(recoverAutostartSuppression).toHaveBeenCalled();
311319
expect(manager.resetRestartAttempts).toHaveBeenCalledWith("discord", "default");
312320
expect(manager.startChannel).toHaveBeenCalledWith("discord", "default");
313321
monitor.stop();

‎src/gateway/channel-health-monitor.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,9 @@ export function startChannelHealthMonitor(deps: ChannelHealthMonitorDeps): Chann
100100
return;
101101
}
102102

103+
if (channelManager.getAutostartSuppression() !== null) {
104+
await channelManager.recoverAutostartSuppression();
105+
}
103106
const snapshot = channelManager.getRuntimeSnapshot();
104107
const globalAutostartSuppression = channelManager.getAutostartSuppression();
105108

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

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,7 @@ function createManager(options?: {
253253
deferStartupAccountStartsUntil?: Promise<void>;
254254
fillChannelDependencies?: boolean;
255255
ambientAutostartSuppressedChannelIds?: ReadonlySet<string>;
256+
tryRecoverAutostartSuppression?: () => boolean;
256257
getNativeApprovalRuntime?: () => GatewayNativeApprovalRuntime | undefined;
257258
}) {
258259
const log = createSubsystemLogger("gateway/server-channels-test");
@@ -281,6 +282,9 @@ function createManager(options?: {
281282
...(options?.ambientAutostartSuppressedChannelIds
282283
? { ambientAutostartSuppressedChannelIds: options.ambientAutostartSuppressedChannelIds }
283284
: {}),
285+
...(options?.tryRecoverAutostartSuppression
286+
? { tryRecoverAutostartSuppression: options.tryRecoverAutostartSuppression }
287+
: {}),
284288
...(options?.getNativeApprovalRuntime
285289
? { getNativeApprovalRuntime: options.getNativeApprovalRuntime }
286290
: {}),
@@ -1731,6 +1735,83 @@ describe("server-channels auto restart", () => {
17311735
expect(manager.getAutostartSuppression()?.reason).toBe("crash-loop-breaker");
17321736
});
17331737

1738+
it("recovers suppressed autostart without undoing manual stops", async () => {
1739+
const startAccount = vi.fn(
1740+
async ({ abortSignal }: ChannelGatewayContext<TestAccount>) =>
1741+
await new Promise<void>((resolve) => {
1742+
abortSignal.addEventListener("abort", () => resolve(), { once: true });
1743+
}),
1744+
);
1745+
installTestRegistry(
1746+
createTestPlugin({
1747+
startAccount,
1748+
listAccountIds: () => [DEFAULT_ACCOUNT_ID, "work"],
1749+
}),
1750+
);
1751+
const tryRecover = vi.fn(() => true);
1752+
const manager = createManager({
1753+
tryRecoverAutostartSuppression: tryRecover,
1754+
getRuntimeConfig: () => ({
1755+
channels: { discord: { healthMonitor: { enabled: false } } },
1756+
}),
1757+
});
1758+
manager.setAutostartSuppression({
1759+
reason: "crash-loop-breaker",
1760+
message: "safe mode",
1761+
});
1762+
1763+
await manager.startChannels();
1764+
await manager.startChannel("discord", DEFAULT_ACCOUNT_ID, { manual: true });
1765+
await manager.stopChannel("discord", DEFAULT_ACCOUNT_ID);
1766+
await manager.recoverAutostartSuppression();
1767+
await flushMicrotasks();
1768+
1769+
expect(tryRecover).toHaveBeenCalledOnce();
1770+
expect(manager.getAutostartSuppression()).toBeNull();
1771+
expect(startAccount.mock.calls.map(([ctx]) => ctx.accountId)).toEqual([
1772+
DEFAULT_ACCOUNT_ID,
1773+
"work",
1774+
]);
1775+
expect(manager.isHealthMonitorEnabled("discord", "work")).toBe(false);
1776+
expect(manager.isManuallyStopped("discord", DEFAULT_ACCOUNT_ID)).toBe(true);
1777+
});
1778+
1779+
it("keeps suppression when persisted recovery is not proven", async () => {
1780+
const startAccount = vi.fn(async () => {});
1781+
installTestRegistry(createTestPlugin({ startAccount }));
1782+
const manager = createManager({ tryRecoverAutostartSuppression: () => false });
1783+
manager.setAutostartSuppression({
1784+
reason: "crash-loop-breaker",
1785+
message: "safe mode",
1786+
});
1787+
1788+
await expect(manager.recoverAutostartSuppression()).resolves.toBe(false);
1789+
1790+
expect(manager.getAutostartSuppression()?.reason).toBe("crash-loop-breaker");
1791+
expect(startAccount).not.toHaveBeenCalled();
1792+
});
1793+
1794+
it("keeps ambient channel suppression after crash-loop recovery", async () => {
1795+
const startAccount = vi.fn(async () => {});
1796+
installTestRegistry(createTestPlugin({ startAccount }));
1797+
const manager = createManager({
1798+
ambientAutostartSuppressedChannelIds: new Set(["discord"]),
1799+
tryRecoverAutostartSuppression: () => true,
1800+
});
1801+
manager.setAutostartSuppression({
1802+
reason: "crash-loop-breaker",
1803+
message: "safe mode",
1804+
});
1805+
1806+
await expect(manager.recoverAutostartSuppression()).resolves.toBe(true);
1807+
1808+
expect(manager.getAutostartSuppression()).toBeNull();
1809+
expect(startAccount).not.toHaveBeenCalled();
1810+
expect(manager.getRuntimeSnapshot().channelAccounts.discord?.default?.lastError).toBe(
1811+
"ambient channel credentials suppressed for dev gateway",
1812+
);
1813+
});
1814+
17341815
it("suppresses ambient dev channel autostart while allowing manual starts", async () => {
17351816
const startAccount = vi.fn(async (_ctx: ChannelGatewayContext<TestAccount>) => {});
17361817
installTestRegistry(createTestPlugin({ startAccount }));

0 commit comments

Comments
 (0)