Skip to content

Commit 5b0e4ec

Browse files
committed
fix: restore breaker channel recovery
1 parent 87dba63 commit 5b0e4ec

11 files changed

Lines changed: 248 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-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
: {}),

‎src/gateway/server-startup-config.breaker-secrets.integration.test.ts‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/** Integration coverage for breaker-suppressed startup SecretRef projection. */
1+
/** Integration coverage for breaker-safe startup SecretRef activation. */
22
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
33
import "../secrets/runtime-telegram.test-support.ts";
44
import type { ConfigFileSnapshot, OpenClawConfig } from "../config/types.js";
@@ -52,7 +52,7 @@ describe("gateway breaker SecretRef integration", () => {
5252
});
5353

5454
it(
55-
"preserves suppressed channel source for full reload projection",
55+
"keeps unavailable channel owners isolated in the active startup config",
5656
async () => {
5757
await withEnvAsync(
5858
{
@@ -111,10 +111,6 @@ describe("gateway breaker SecretRef integration", () => {
111111
emitStateEvent: vi.fn(),
112112
prepareRuntimeSecretsSnapshot,
113113
activateRuntimeSecretsSnapshot: activateSecretsRuntimeSnapshot,
114-
channelAutostartSuppression: {
115-
reason: "crash-loop-breaker",
116-
message: "breaker tripped: 20 unclean boots",
117-
},
118114
});
119115

120116
const startup = await prepareGatewayStartupConfig({
@@ -123,14 +119,22 @@ describe("gateway breaker SecretRef integration", () => {
123119
});
124120

125121
expect(startup.cfg.gateway?.auth?.token).toBe("resolved-gateway-token");
126-
expect(startup.cfg.channels).toBeUndefined();
122+
expect(startup.cfg.channels?.telegram?.botToken).toEqual(channelTokenRef);
127123
const activeStartup = getActiveSecretsRuntimeSnapshot();
128124
if (!activeStartup) {
129125
throw new Error("Expected an active startup secrets snapshot");
130126
}
131127
expect(activeStartup.sourceConfig.gateway?.auth?.token).toEqual(gatewayTokenRef);
132128
expect(activeStartup.sourceConfig.channels?.telegram?.botToken).toEqual(channelTokenRef);
133-
expect(activeStartup.config.channels).toBeUndefined();
129+
expect(activeStartup.config.channels?.telegram?.botToken).toEqual(channelTokenRef);
130+
expect(activeStartup.degradedOwners).toMatchObject([
131+
{
132+
ownerKind: "account",
133+
ownerId: "telegram:default",
134+
state: "unavailable",
135+
paths: ["channels.telegram.botToken"],
136+
},
137+
]);
134138

135139
process.env[CHANNEL_TOKEN_ENV] = "restored-channel-token";
136140
const reloaded = await activateRuntimeSecrets(activeStartup.sourceConfig, {

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

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@ import {
3737
} from "../secrets/runtime-state.js";
3838
import { logRuntimeSecretWarnings } from "../secrets/runtime-warning-log.js";
3939
import { createLazyPromise } from "../shared/lazy-runtime.js";
40-
import type { ChannelAutostartSuppression } from "./server-channels.js";
4140
import {
4241
applyGatewayAuthOverridesForStartupPreflight,
4342
assertRuntimeGatewayAuthNotKnownWeak,
@@ -51,10 +50,7 @@ import {
5150
logPreparedSecretDegradations,
5251
logThrownSecretDegradations,
5352
} from "./server-startup-secret-diagnostics.js";
54-
import {
55-
resolveGatewayStartupSecretProjection,
56-
resolveGatewayStartupSourceConfig,
57-
} from "./server-startup-secret-surfaces.js";
53+
import { resolveGatewayStartupSourceConfig } from "./server-startup-secret-surfaces.js";
5854
import { ensureGatewayStartupAuth } from "./startup-auth.js";
5955
export {
6056
loadGatewayStartupConfigSnapshot,
@@ -139,7 +135,6 @@ export function createRuntimeSecretsActivator(params: {
139135
activateRuntimeSecretsSnapshot?: ActivateRuntimeSecretsSnapshot;
140136
manifestRegistry?: Pick<PluginManifestRegistry, "plugins">;
141137
pluginMetadataSnapshot?: Pick<PluginMetadataSnapshot, "plugins" | "manifestRegistry">;
142-
channelAutostartSuppression?: ChannelAutostartSuppression | null;
143138
}): ActivateRuntimeSecrets {
144139
let secretsDegraded = false;
145140
let degradationGeneration = 0;
@@ -358,21 +353,18 @@ export function createRuntimeSecretsActivator(params: {
358353
await runWithSecretsActivationLock(async () => {
359354
let activationSourceConfig = config;
360355
try {
361-
const { sourceConfig, assignmentConfig } = resolveGatewayStartupSecretProjection({
356+
const sourceConfig = resolveGatewayStartupSourceConfig(
362357
config,
363-
reason: activationParams.reason,
364-
channelAutostartSuppression: params.channelAutostartSuppression,
365-
...(activationParams.env ? { env: activationParams.env } : {}),
366-
});
358+
activationParams.env ?? process.env,
359+
);
367360
activationSourceConfig = sourceConfig;
368361
const startupPreflight =
369362
activationParams.reason === "startup" || activationParams.reason === "restart-check";
370363
if (
371364
activationParams.reason === "startup" &&
372365
activationParams.activate &&
373366
!params.prepareRuntimeSecretsSnapshot &&
374-
!params.activateRuntimeSecretsSnapshot &&
375-
assignmentConfig === undefined
367+
!params.activateRuntimeSecretsSnapshot
376368
) {
377369
const startupEnv = activationParams.env ?? process.env;
378370
const fastPath = hasLegacyAuthProfileSourcesForStartup({
@@ -423,7 +415,6 @@ export function createRuntimeSecretsActivator(params: {
423415
() =>
424416
prepareRuntimeSecretsSnapshot({
425417
config: sourceConfig,
426-
...(assignmentConfig !== undefined ? { assignmentConfig } : {}),
427418
allowUnavailableSecretOwners,
428419
...(activationParams.env ? { env: activationParams.env } : {}),
429420
includeAuthStoreRefs: activationParams.includeAuthStoreRefs,

0 commit comments

Comments
 (0)