Skip to content

Commit 3483c89

Browse files
authored
fix(gateway): preserve native runtime selection across reloads (#133195)
1 parent 3306b62 commit 3483c89

5 files changed

Lines changed: 227 additions & 12 deletions

File tree

‎docs/gateway/configuration.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -563,6 +563,11 @@ By default, changing `agents.defaults.mediaMaxMb` restarts channel runtimes so t
563563
attachment limits take effect together. Automatic reloads preserve manually
564564
stopped accounts; use an explicit channel start to resume those accounts.
565565

566+
Model runtime selection keeps your authored settings separate from catalog defaults.
567+
Hot reload and secrets reload preserve that distinction: catalog compatibility
568+
metadata does not become a custom request override that switches a native runtime
569+
back to OpenClaw.
570+
566571
| Category | Fields | Gateway restart needed? |
567572
| ------------------- | ----------------------------------------------------------------------- | ---------------------------- |
568573
| Channels | `channels.*`, `web` (WhatsApp) - all built-in and plugin channels | No (restarts that channel) |
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
import { afterEach, describe, expect, it, vi } from "vitest";
2+
import { resolveModelProviderRouteOverridePresence } from "../config/model-provider-config.js";
3+
import {
4+
getRuntimeConfigSnapshot,
5+
getRuntimeConfigSourceSnapshot,
6+
} from "../config/runtime-snapshot.js";
7+
import { projectConfigOntoRuntimeSourceSnapshot } from "../config/runtime-source-projection.js";
8+
import type { OpenClawConfig } from "../config/types.openclaw.js";
9+
import {
10+
activateSecretsRuntimeSnapshot,
11+
activateSecretsRuntimeSnapshotWithSource,
12+
clearSecretsRuntimeSnapshot,
13+
getActiveSecretsRuntimeSnapshotRevision,
14+
prepareSecretsRuntimeSnapshot,
15+
} from "../secrets/runtime.js";
16+
import { buildGatewayReloadPlan } from "./config-reload-plan.js";
17+
import type { GatewayConfigReloadTransactionOwnership } from "./config-reload.js";
18+
import type { ManagedGatewayConfigReloaderParams } from "./server-reload-contracts.js";
19+
import { createManagedReloadSecretHandlers } from "./server-reload-managed-secrets.js";
20+
import { createRuntimeSecretsActivator } from "./server-startup-config.js";
21+
22+
vi.mock("../agents/context.js", () => ({ refreshContextWindowCache: vi.fn() }));
23+
24+
afterEach(() => {
25+
clearSecretsRuntimeSnapshot();
26+
vi.restoreAllMocks();
27+
});
28+
29+
function configPair(runtime: "openclaw" | "codex") {
30+
const source = {
31+
agents: { defaults: { models: { "openai/gpt-5.6-luna": { agentRuntime: { id: runtime } } } } },
32+
models: {
33+
providers: {
34+
openai: {
35+
api: "openai-responses",
36+
baseUrl: "https://api.openai.com/v1",
37+
models: [
38+
{
39+
id: "gpt-5.6-luna",
40+
name: "Luna",
41+
reasoning: true,
42+
input: ["text", "image"],
43+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
44+
maxTokens: 4096,
45+
},
46+
],
47+
},
48+
},
49+
},
50+
} satisfies OpenClawConfig;
51+
const config: OpenClawConfig = structuredClone(source);
52+
// The loader may seed catalog compatibility; this is not authored request policy.
53+
config.models!.providers!.openai!.models[0]!.compat = { supportsStore: false };
54+
return { source, config };
55+
}
56+
57+
const prepare = (config: OpenClawConfig) =>
58+
prepareSecretsRuntimeSnapshot({
59+
config,
60+
includeAuthStoreRefs: false,
61+
env: {},
62+
});
63+
64+
function expectAuthoredSource(source: OpenClawConfig) {
65+
const config = getRuntimeConfigSnapshot();
66+
expect(config).not.toBeNull();
67+
expect(getRuntimeConfigSourceSnapshot()).toEqual(source);
68+
expect(
69+
resolveModelProviderRouteOverridePresence({
70+
provider: "openai",
71+
modelId: "gpt-5.6-luna",
72+
authoredConfig: projectConfigOntoRuntimeSourceSnapshot(config!),
73+
}),
74+
).toBe("none");
75+
}
76+
77+
async function createReload(canonicalActivator: boolean, commit: () => Promise<void>) {
78+
const initial = configPair("openclaw");
79+
activateSecretsRuntimeSnapshotWithSource(await prepare(initial.config), initial.source);
80+
expectAuthoredSource(initial.source);
81+
const activator = createRuntimeSecretsActivator({
82+
logSecrets: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
83+
emitStateEvent: vi.fn(),
84+
prepareRuntimeSecretsSnapshot: ({ config }) => prepare(config),
85+
activateRuntimeSecretsSnapshot: activateSecretsRuntimeSnapshot,
86+
});
87+
const activateRuntimeSecrets: ManagedGatewayConfigReloaderParams["activateRuntimeSecrets"] =
88+
canonicalActivator ? activator : (config, options) => activator(config, options);
89+
// Only secret publication is exercised here; the service tail is injected at its existing seam.
90+
const params = {
91+
activateRuntimeSecrets,
92+
resolveSharedGatewaySessionGenerationForConfig: () => undefined,
93+
sharedGatewaySessionGenerationState: { current: undefined, required: null },
94+
clients: [],
95+
reconcileTerminalSessions: vi.fn(),
96+
};
97+
const { onHotReload } = createManagedReloadSecretHandlers({
98+
params,
99+
prepareRuntimeCandidate: (config) => config,
100+
tryPrepareRuntimeSecrets: async (config) => ({
101+
snapshot: await prepare(config),
102+
expectedRevision: getActiveSecretsRuntimeSnapshotRevision(),
103+
}),
104+
applyHotReload: async (_plan, _config, publication) => {
105+
let committed = false;
106+
await publication!.publish(
107+
async () => {
108+
await commit();
109+
committed = true;
110+
},
111+
() => committed,
112+
);
113+
return "applied";
114+
},
115+
});
116+
const ownership: GatewayConfigReloadTransactionOwnership = {
117+
isCurrent: () => true,
118+
markRuntimeCommitted: vi.fn(),
119+
commitRuntimeEnv: vi.fn(),
120+
publishRuntimeEnv: vi.fn(),
121+
rollbackRuntimeEnv: vi.fn(),
122+
reapplyRuntimeOverlays: (config) => config,
123+
};
124+
const next = configPair("codex");
125+
const plan = buildGatewayReloadPlan(
126+
["agents.defaults.models.openai/gpt-5.6-luna.agentRuntime.id"],
127+
{ candidateConfig: next.config },
128+
);
129+
return { initial, next, run: () => onHotReload(plan, next.config, ownership, next.source) };
130+
}
131+
132+
describe.each([true, false])(
133+
"managed reload authored source (canonical activator: %s)",
134+
(canonical) => {
135+
it("preserves generated model metadata across a successful hot reload", async () => {
136+
const { next, run } = await createReload(canonical, async () => {});
137+
await expect(run()).resolves.toBe("applied");
138+
expect(
139+
getRuntimeConfigSnapshot()?.agents?.defaults?.models?.["openai/gpt-5.6-luna"]?.agentRuntime
140+
?.id,
141+
).toBe("codex");
142+
expectAuthoredSource(next.source);
143+
});
144+
145+
it("restores the predecessor's authored source when runtime commit fails", async () => {
146+
const { initial, run } = await createReload(canonical, async () => {
147+
throw new Error("commit failed");
148+
});
149+
await expect(run()).rejects.toThrow("commit failed");
150+
expectAuthoredSource(initial.source);
151+
});
152+
153+
it("does not roll back a newer publication's authored source", async () => {
154+
const newer = configPair("codex");
155+
newer.source.models.providers.openai.models[0]!.name = "Newer model";
156+
newer.config.models!.providers!.openai!.models[0]!.name = "Newer model";
157+
const { run } = await createReload(canonical, async () => {
158+
activateSecretsRuntimeSnapshotWithSource(await prepare(newer.config), newer.source);
159+
throw new Error("superseded commit failed");
160+
});
161+
await expect(run()).rejects.toThrow("superseded commit failed");
162+
expectAuthoredSource(newer.source);
163+
});
164+
},
165+
);

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

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,14 @@ type EffectiveConfigUnchangedHandler = NonNullable<
114114
type HotReloadHandler = NonNullable<ManagedReloadOptions["onHotReload"]>;
115115

116116
export function createManagedReloadSecretHandlers(options: {
117-
params: ManagedGatewayConfigReloaderParams;
117+
params: Pick<
118+
ManagedGatewayConfigReloaderParams,
119+
| "activateRuntimeSecrets"
120+
| "clients"
121+
| "reconcileTerminalSessions"
122+
| "resolveSharedGatewaySessionGenerationForConfig"
123+
| "sharedGatewaySessionGenerationState"
124+
>;
118125
prepareRuntimeCandidate: PrepareRuntimeCandidate;
119126
tryPrepareRuntimeSecrets: TryPrepareRuntimeSecrets;
120127
applyHotReload: ReturnType<typeof createGatewayReloadHandlers>["applyHotReload"];
@@ -293,6 +300,8 @@ export function createManagedReloadSecretHandlers(options: {
293300
throw new GatewayConfigReloadSupersededError();
294301
}
295302
const previousSnapshot = getActiveSecretsRuntimeSnapshotState();
303+
// Prepared secrets carry effective defaults; commit and rollback must retain authored provenance.
304+
const previousRuntimeSourceConfig = getRuntimeConfigSourceSnapshot() ?? undefined;
296305
const previousSnapshotRevision = getActiveSecretsRuntimeSnapshotRevisionState();
297306
const previousGenerationOwnership = captureSharedGatewaySessionGenerationOwnership(
298307
params.sharedGatewaySessionGenerationState,
@@ -433,6 +442,7 @@ export function createManagedReloadSecretHandlers(options: {
433442
publishedSnapshotRevision ?? -1,
434443
prepared,
435444
{
445+
runtimeSourceConfig: previousRuntimeSourceConfig,
436446
onActivated: () => {
437447
generationRestored = restoreOwnedCurrentSharedGatewaySessionGeneration(
438448
params.sharedGatewaySessionGenerationState,
@@ -486,6 +496,7 @@ export function createManagedReloadSecretHandlers(options: {
486496
{
487497
reason: "reload",
488498
activate: true,
499+
runtimeSourceConfig: sourceConfig,
489500
},
490501
publishRuntime,
491502
() =>
@@ -511,6 +522,7 @@ export function createManagedReloadSecretHandlers(options: {
511522
previousGenerationOwnership,
512523
),
513524
onActivated: claimGenerationOwnership,
525+
runtimeSourceConfig: sourceConfig,
514526
},
515527
))
516528
) {
@@ -557,6 +569,7 @@ export function createManagedReloadSecretHandlers(options: {
557569
publishedSnapshotRevision,
558570
prepared,
559571
{
572+
runtimeSourceConfig: previousRuntimeSourceConfig,
560573
onActivated: () => {
561574
generationRestored = restoreOwnedCurrentSharedGatewaySessionGeneration(
562575
params.sharedGatewaySessionGenerationState,

‎src/gateway/server-secrets-reload.model-runtime.test.ts‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,13 @@ import {
99
} from "../agents/prepared-model-runtime.js";
1010
import { resetPreparedModelRuntimeSnapshotsForTest } from "../agents/prepared-model-runtime.test-support.js";
1111
import { writeConfigFile } from "../config/config.js";
12-
import { getRuntimeConfigSnapshot } from "../config/runtime-snapshot.js";
12+
import {
13+
getRuntimeConfigSnapshot,
14+
getRuntimeConfigSourceSnapshot,
15+
} from "../config/runtime-snapshot.js";
1316
import type { OpenClawConfig } from "../config/types.openclaw.js";
1417
import {
15-
activateSecretsRuntimeSnapshot,
18+
activateSecretsRuntimeSnapshotWithSource,
1619
clearSecretsRuntimeSnapshot,
1720
prepareSecretsRuntimeSnapshot,
1821
} from "../secrets/runtime.js";
@@ -92,8 +95,10 @@ afterEach(async () => {
9295
async function coldRuntime(clients: SharedGatewayAuthClient[] = []) {
9396
const config = sourceConfig();
9497
await state.writeConfig(config);
98+
const runtimeConfig: OpenClawConfig = structuredClone(config);
99+
runtimeConfig.models!.providers!["healthy-fixture"]!.models[0]!.compat = { supportsStore: false };
95100
const initial = await prepareSecretsRuntimeSnapshot({
96-
config,
101+
config: runtimeConfig,
97102
allowUnavailableSecretOwners: true,
98103
});
99104
expect(initial.degradedOwners).toEqual(
@@ -105,7 +110,7 @@ async function coldRuntime(clients: SharedGatewayAuthClient[] = []) {
105110
}),
106111
]),
107112
);
108-
activateSecretsRuntimeSnapshot(initial);
113+
activateSecretsRuntimeSnapshotWithSource(initial, config);
109114
await refreshPreparedModelRuntimeSnapshots(requireRuntimeConfig(), {
110115
catalogMode: "static",
111116
gatewayLifecycle: true,
@@ -143,11 +148,12 @@ async function coldRuntime(clients: SharedGatewayAuthClient[] = []) {
143148

144149
describe("secret reload model-runtime publication", () => {
145150
it("publishes recovered config refs to the model owner without an auth-profile mutation", async () => {
146-
const { reload } = await coldRuntime();
151+
const { config, reload } = await coldRuntime();
147152
const authRevision = getRuntimeAuthProfileStoreCredentialsRevision();
148153

149154
await reload();
150155

156+
expect(getRuntimeConfigSourceSnapshot()).toEqual(config);
151157
expect(getRuntimeAuthProfileStoreCredentialsRevision()).toBe(authRevision);
152158
expect(requireRuntimeConfig().models?.providers?.["recoverable-fixture"]?.apiKey).toBe(
153159
"recovered-fixture-key",
@@ -162,13 +168,14 @@ describe("secret reload model-runtime publication", () => {
162168
});
163169

164170
it("restores the authoritative runtime model config after a publication failure", async () => {
165-
const { reload } = await coldRuntime();
171+
const { config, reload } = await coldRuntime();
166172
vi.spyOn(providerCatalog, "prepareImplicitProviderStaticCatalog").mockRejectedValueOnce(
167173
new Error("catalog build failed"),
168174
);
169175

170176
await expect(reload()).rejects.toThrow("catalog build failed");
171177

178+
expect(getRuntimeConfigSourceSnapshot()).toEqual(config);
172179
const current = requireRuntimeConfig();
173180
const published = await prepareModelRuntimeSnapshot({
174181
config: current,
@@ -287,6 +294,7 @@ describe("secret reload model-runtime publication", () => {
287294
await nextPublication;
288295
expect((await reader).config).toBe(current);
289296
expect(requireRuntimeConfig()).toBe(current);
297+
expect(getRuntimeConfigSourceSnapshot()?.models).toEqual(next.models);
290298
expect(generationState).toEqual({ current: "newer", required: null });
291299
} finally {
292300
release.resolve();

0 commit comments

Comments
 (0)