Skip to content

Commit be0bcb3

Browse files
authored
fix(gateway): clear stale credential warnings after channel plugin removal (#127503)
* fix(gateway): retire removed channel credential owners Retire stale account diagnostics only after successful channel plugin removal. Preserve independently owned credential diagnostics across snapshot replacement and rollback. * test(gateway): cover plugin-disable owner pruning
1 parent a7a68cf commit be0bcb3

7 files changed

Lines changed: 88 additions & 6 deletions

‎src/agents/mcp-connection-resolver.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,7 @@ describe("mcp connection resolver helpers", () => {
340340
};
341341
const reloadLog = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
342342
const requestRecoveryRestart = vi.fn(() => ({ status: "failed" as const }));
343+
const pruneInactiveChannelAccountState = vi.fn();
343344
const nextConfig: OpenClawConfig = {
344345
plugins: {
345346
entries: {
@@ -365,6 +366,7 @@ describe("mcp connection resolver helpers", () => {
365366
},
366367
async startChannel() {},
367368
async stopChannel() {},
369+
pruneInactiveChannelAccountState,
368370
async reloadPlugins({ beforeReplace, commitRuntime }) {
369371
await beforeReplace(new Set());
370372
await commitRuntime();
@@ -392,6 +394,7 @@ describe("mcp connection resolver helpers", () => {
392394
});
393395
expect(refreshContextWindowCache).toHaveBeenCalledWith(nextConfig);
394396
expect(requestRecoveryRestart).not.toHaveBeenCalled();
397+
expect(pruneInactiveChannelAccountState).toHaveBeenCalledExactlyOnceWith(new Set());
395398
expect(isPluginRegistryRetired(previous.registry)).toBe(true);
396399
expect(peekSessionMcpRuntime({ sessionId })).toBeUndefined();
397400

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

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3087,6 +3087,44 @@ describe("server-channels auto restart", () => {
30873087
]);
30883088
});
30893089

3090+
it("prunes only credential owners and account state for inactive channel plugins", async () => {
3091+
installTestRegistry(
3092+
...(["discord", "slack"] as const).map((channelId) =>
3093+
createTestPlugin({
3094+
id: channelId,
3095+
listAccountIds: () => ["Ops Team"],
3096+
startAccount: async () => {},
3097+
resolveAccount: (_cfg, accountId) => ({
3098+
enabled: true,
3099+
configured: true,
3100+
credentialDiagnostics: [
3101+
{
3102+
code: "CREDENTIAL_FILE_UNAVAILABLE" as const,
3103+
path: `channels.${channelId}.accounts.${accountId}.tokenFile`,
3104+
reason: "not-found",
3105+
},
3106+
],
3107+
}),
3108+
}),
3109+
),
3110+
);
3111+
const manager = createManager({ channelIds: ["discord", "slack"] });
3112+
3113+
await manager.startChannels();
3114+
expect(listActiveDegradedSecretOwners().map((owner) => owner.ownerId)).toEqual([
3115+
"discord:ops-team",
3116+
"slack:ops-team",
3117+
]);
3118+
3119+
manager.pruneInactiveChannelAccountState(new Set(["slack"]));
3120+
3121+
expect(listActiveDegradedSecretOwners().map((owner) => owner.ownerId)).toEqual([
3122+
"slack:ops-team",
3123+
]);
3124+
expect(manager.resolveRuntimeAccountId("discord", "ops-team")).toBeUndefined();
3125+
expect(manager.resolveRuntimeAccountId("slack", "ops-team")).toBe("Ops Team");
3126+
});
3127+
30903128
it("resolves only an unambiguous authoritative runtime account for a normalized owner", async () => {
30913129
let accountIds = ["Ops Team"];
30923130
installTestRegistry(

‎src/gateway/server-channels.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,7 @@ export type ChannelManager = {
284284

285285
// Channel docking: lifecycle hooks (`plugin.gateway`) flow through this manager.
286286
export function createChannelManager(opts: ChannelManagerOptions): ChannelManager & {
287+
pruneInactiveChannelAccountState: (activeChannelIds: ReadonlySet<ChannelId>) => void;
287288
resolveRuntimeAccountId: (channelId: ChannelId, accountId: string) => string | undefined;
288289
} {
289290
const {
@@ -500,6 +501,14 @@ export function createChannelManager(opts: ChannelManagerOptions): ChannelManage
500501
}
501502
};
502503

504+
const pruneInactiveChannelAccountState = (activeChannelIds: ReadonlySet<ChannelId>): void => {
505+
for (const [channelId, store] of channelStores) {
506+
if (!activeChannelIds.has(channelId)) {
507+
evictStaleChannelAccountState(channelId, store, []);
508+
}
509+
}
510+
};
511+
503512
const startChannelProcessOwned = async (
504513
channelId: ChannelId,
505514
accountId?: string,
@@ -1420,6 +1429,7 @@ export function createChannelManager(opts: ChannelManagerOptions): ChannelManage
14201429
startChannels,
14211430
startChannel,
14221431
stopChannel,
1432+
pruneInactiveChannelAccountState,
14231433
setAutostartSuppression: (suppression) => {
14241434
autostartSuppression = suppression;
14251435
},

‎src/gateway/server-reload-contracts.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,7 @@ export type GatewayReloadHandlerParams = {
151151
getPluginMetadataSnapshot?: () => PluginMetadataSnapshot | undefined;
152152
startChannel: GatewayChannelManager["startChannel"];
153153
stopChannel: GatewayChannelManager["stopChannel"];
154+
pruneInactiveChannelAccountState: (activeChannelIds: ReadonlySet<ChannelKind>) => void;
154155
getChannelAutostartSuppression?: GatewayChannelManager["getAutostartSuppression"];
155156
stopPostReadySidecars?: () => Promise<void> | void;
156157
reloadPlugins: (params: {
@@ -187,7 +188,7 @@ export type GatewayReloadHandlerParams = {
187188

188189
export type ManagedGatewayConfigReloaderParams = Omit<
189190
GatewayReloadHandlerParams,
190-
"assertRestartReady" | "createHealthMonitor" | "logReload"
191+
"assertRestartReady" | "createHealthMonitor" | "logReload" | "pruneInactiveChannelAccountState"
191192
> & {
192193
configRevisionProjector: import("./config-revision-token.js").GatewayConfigRevisionProjector;
193194
minimalTestGateway: boolean;
@@ -204,7 +205,9 @@ export type ManagedGatewayConfigReloaderParams = Omit<
204205
promoteSnapshot: typeof import("../config/config.js").promoteConfigSnapshotToLastKnownGood;
205206
subscribeToWrites: typeof import("../config/config.js").registerConfigWriteListener;
206207
logReload: GatewayReloadLog & { error: (msg: string) => void };
207-
channelManager: GatewayChannelManager;
208+
channelManager: GatewayChannelManager & {
209+
pruneInactiveChannelAccountState: GatewayReloadHandlerParams["pruneInactiveChannelAccountState"];
210+
};
208211
activateRuntimeSecrets: ActivateRuntimeSecrets;
209212
/** Applies one immutable effective config/compare snapshot before reload planning. */
210213
prepareConfigCandidate?: (params: {

‎src/gateway/server-reload-handlers.test.ts‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,7 @@ function createGatewayReloadHandlers(
133133
setState: vi.fn(),
134134
startChannel: vi.fn(async () => {}),
135135
stopChannel: vi.fn(async () => {}),
136+
pruneInactiveChannelAccountState: vi.fn(),
136137
stopPostReadySidecars: vi.fn(),
137138
reloadPlugins: vi.fn(async () => makePluginReloadResult()),
138139
logHooks: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
@@ -196,7 +197,7 @@ function startManagedGatewayConfigReloader(params: ManagedReloaderTestParams) {
196197
logChannels: { info: vi.fn(), error: vi.fn() },
197198
logCron: { error: vi.fn() },
198199
logReload: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
199-
channelManager: {} as never,
200+
channelManager: { pruneInactiveChannelAccountState: vi.fn() } as never,
200201
activateRuntimeSecrets: vi.fn(async (config: OpenClawConfig) =>
201202
makePreparedSecretsSnapshot(config),
202203
) as never,
@@ -611,6 +612,7 @@ function createReloadHandlersForTest(
611612
channels?: {
612613
start: ReloadHandlerParams["startChannel"];
613614
stop: ReloadHandlerParams["stopChannel"];
615+
pruneInactiveChannelAccountState?: ReloadHandlerParams["pruneInactiveChannelAccountState"];
614616
},
615617
reloadPlugins?: Parameters<typeof createGatewayReloadHandlers>[0]["reloadPlugins"],
616618
stopPostReadySidecars = vi.fn(),
@@ -648,6 +650,9 @@ function createReloadHandlersForTest(
648650
setState,
649651
startChannel: channels?.start ?? vi.fn(async () => {}),
650652
stopChannel: channels?.stop ?? vi.fn(async () => {}),
653+
...(channels?.pruneInactiveChannelAccountState
654+
? { pruneInactiveChannelAccountState: channels.pruneInactiveChannelAccountState }
655+
: {}),
651656
...(reloadPlugins ? { reloadPlugins } : {}),
652657
getChannelAutostartSuppression: options?.getChannelAutostartSuppression,
653658
stopPostReadySidecars,
@@ -5583,6 +5588,7 @@ describe("gateway plugin hot reload handlers", () => {
55835588

55845589
it("restarts pre-stopped channel targets when runtime publication fails", async () => {
55855590
const events: string[] = [];
5591+
const pruneInactiveChannelAccountState = vi.fn();
55865592
const publish = vi.fn(async () => {
55875593
throw new Error("publication failed");
55885594
});
@@ -5611,6 +5617,7 @@ describe("gateway plugin hot reload handlers", () => {
56115617
start: vi.fn(async (channel, accountId) => {
56125618
events.push(`start:${channel}:${accountId ?? "all"}`);
56135619
}),
5620+
pruneInactiveChannelAccountState,
56145621
},
56155622
reloadPlugins,
56165623
);
@@ -5629,11 +5636,13 @@ describe("gateway plugin hot reload handlers", () => {
56295636
"start:slack:catalog-account",
56305637
"start:discord:all",
56315638
]);
5639+
expect(pruneInactiveChannelAccountState).not.toHaveBeenCalled();
56325640
expect(handlers.setState).not.toHaveBeenCalled();
56335641
});
56345642

56355643
it("restarts pre-stopped account targets when plugin replacement is cancelled", async () => {
56365644
const events: string[] = [];
5645+
const pruneInactiveChannelAccountState = vi.fn();
56375646
const reloadPlugins = vi.fn(
56385647
async (params: {
56395648
beforeReplace: (
@@ -5656,6 +5665,7 @@ describe("gateway plugin hot reload handlers", () => {
56565665
start: vi.fn(async (channel, accountId) => {
56575666
events.push(`start:${channel}:${accountId ?? "all"}`);
56585667
}),
5668+
pruneInactiveChannelAccountState,
56595669
},
56605670
reloadPlugins,
56615671
);
@@ -5665,6 +5675,7 @@ describe("gateway plugin hot reload handlers", () => {
56655675
).rejects.toThrow("config hot reload cancelled by config supersession or in-process restart");
56665676

56675677
expect(events).toEqual(["stop:discord:catalog-account", "start:discord:catalog-account"]);
5678+
expect(pruneInactiveChannelAccountState).not.toHaveBeenCalled();
56685679
expect(handlers.setState).not.toHaveBeenCalled();
56695680
});
56705681

@@ -5675,6 +5686,7 @@ describe("gateway plugin hot reload handlers", () => {
56755686
const logChannels = { info: vi.fn(), error: vi.fn() };
56765687
const events: string[] = [];
56775688
const startRootCounts: number[] = [];
5689+
const pruneInactiveChannelAccountState = vi.fn();
56785690
const startChannel = vi.fn(async (channel: ChannelKind) => {
56795691
events.push(`start:${channel}`);
56805692
startRootCounts.push(getActiveGatewayRootWorkCount({ excludeCurrent: true }));
@@ -5700,6 +5712,7 @@ describe("gateway plugin hot reload handlers", () => {
57005712
setState,
57015713
startChannel,
57025714
stopChannel,
5715+
pruneInactiveChannelAccountState,
57035716
reloadPlugins,
57045717
logChannels,
57055718
});
@@ -5734,6 +5747,7 @@ describe("gateway plugin hot reload handlers", () => {
57345747
expect(startChannel).toHaveBeenCalledWith("telegram");
57355748
expect(startChannel).toHaveBeenCalledWith("discord");
57365749
expect(startRootCounts).toEqual([1, 1]);
5750+
expect(pruneInactiveChannelAccountState).not.toHaveBeenCalled();
57375751
expect(setState).not.toHaveBeenCalled();
57385752
});
57395753

@@ -5743,6 +5757,10 @@ describe("gateway plugin hot reload handlers", () => {
57435757
const setState = vi.fn();
57445758
const startChannel = vi.fn(async () => {});
57455759
const events: string[] = [];
5760+
const activeChannels = new Set<ChannelKind>(["slack"]);
5761+
const pruneInactiveChannelAccountState = vi.fn(() => {
5762+
events.push("prune");
5763+
});
57465764
const stopChannel = vi.fn(async () => {
57475765
events.push("stop");
57485766
});
@@ -5753,14 +5771,15 @@ describe("gateway plugin hot reload handlers", () => {
57535771
events.push("reload:start");
57545772
await params.beforeReplace(new Set(["discord"]));
57555773
events.push("registry:replace");
5756-
return makePluginReloadResult();
5774+
return makePluginReloadResult({ activeChannels });
57575775
},
57585776
);
57595777
const { applyHotReload } = createGatewayReloadHandlers({
57605778
getState: () => gatewayState,
57615779
setState,
57625780
startChannel,
57635781
stopChannel,
5782+
pruneInactiveChannelAccountState,
57645783
reloadPlugins,
57655784
});
57665785
const sourceConfig: OpenClawConfig = {
@@ -5798,7 +5817,8 @@ describe("gateway plugin hot reload handlers", () => {
57985817
expect(reloadParamsRecord?.changedPaths).toEqual(["plugins.enabled"]);
57995818
expect(stopChannel).toHaveBeenCalledWith("discord", undefined, { manual: false });
58005819
expect(startChannel).not.toHaveBeenCalled();
5801-
expect(events).toEqual(["reload:start", "stop", "registry:replace"]);
5820+
expect(pruneInactiveChannelAccountState).toHaveBeenCalledExactlyOnceWith(activeChannels);
5821+
expect(events).toEqual(["reload:start", "stop", "registry:replace", "prune"]);
58025822
expect(setState).toHaveBeenCalledTimes(1);
58035823
});
58045824

@@ -6163,6 +6183,7 @@ describe("deferred channel reload abort generation", () => {
61636183
start: vi.fn(async () => {}),
61646184
stop: vi.fn(async () => {}),
61656185
};
6186+
const pruneInactiveChannelAccountState = vi.fn();
61666187
let receivedIsAborted = false;
61676188
let reloadWasCancelled = false;
61686189
const reloadPlugins = vi.fn(
@@ -6185,6 +6206,7 @@ describe("deferred channel reload abort generation", () => {
61856206
const { applyHotReload } = createGatewayReloadHandlers({
61866207
startChannel: channels.start,
61876208
stopChannel: channels.stop,
6209+
pruneInactiveChannelAccountState,
61886210
reloadPlugins,
61896211
logChannels,
61906212
});
@@ -6217,6 +6239,7 @@ describe("deferred channel reload abort generation", () => {
62176239
// No channel should be started — cancelledByRestart = pluginReloadAborted = true
62186240
expect(channels.start).not.toHaveBeenCalled();
62196241
expect(channels.stop).not.toHaveBeenCalled();
6242+
expect(pruneInactiveChannelAccountState).not.toHaveBeenCalled();
62206243
} finally {
62216244
vi.useRealTimers();
62226245
hoisted.activeTaskBlockers.length = 0;

‎src/gateway/server-reload-hot.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -550,12 +550,16 @@ export function createGatewayReloadHandlers(params: GatewayReloadHandlerParams)
550550
}
551551
// beforeReplace may have set pluginReloadAborted inside reloadPlugins;
552552
// skip metadata/runtime updates when the reload was cancelled mid-flight.
553-
if (!pluginReloadAborted) {
553+
if (!pluginReloadAborted && !isLifecycleReloadAborted()) {
554554
for (const channel of pluginReloadResult.restartChannels) {
555555
channelsToRestart.add(channel);
556556
}
557557
activePluginChannelsAfterReload = pluginReloadResult.activeChannels;
558+
// Only a successfully published replacement can authoritatively retire channel owners.
559+
params.pruneInactiveChannelAccountState(activePluginChannelsAfterReload);
558560
resetPreparedModelRuntimeStateForHotReload();
561+
} else {
562+
pluginReloadAborted = true;
559563
}
560564
}
561565
}

‎src/gateway/server-reload-managed.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@ export function startManagedGatewayConfigReloader(
142142
getPluginMetadataSnapshot: params.getPluginMetadataSnapshot,
143143
startChannel: params.startChannel,
144144
stopChannel: params.stopChannel,
145+
pruneInactiveChannelAccountState: params.channelManager.pruneInactiveChannelAccountState,
145146
getChannelAutostartSuppression: params.getChannelAutostartSuppression,
146147
stopPostReadySidecars: params.stopPostReadySidecars,
147148
reloadPlugins: params.reloadPlugins,

0 commit comments

Comments
 (0)