Skip to content

Commit 2cf8a1b

Browse files
author
Peter Steinberger
committed
fix(gateway): hot-reload automatic compaction settings
1 parent 0ac3368 commit 2cf8a1b

4 files changed

Lines changed: 320 additions & 0 deletions

File tree

‎src/gateway/config-reload-plan.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ const BASE_RELOAD_RULES: ReloadRule[] = [
9595
kind: "hot",
9696
actions: ["restart-heartbeat"],
9797
},
98+
{ prefix: "agents.defaults.compaction", kind: "hot" },
9899
{
99100
prefix: "agents.defaults.models",
100101
kind: "hot",

‎src/gateway/config-reload.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,30 @@ describe("buildGatewayReloadPlan", () => {
358358
});
359359
});
360360

361+
it.each([
362+
"agents.defaults.compaction",
363+
"agents.defaults.compaction.model",
364+
"agents.defaults.compaction.maxActiveTranscriptBytes",
365+
"agents.defaults.compaction.memoryFlush.model",
366+
])("refreshes compaction config without restarting subsystems: %s", (path) => {
367+
const plan = buildGatewayReloadPlan([path]);
368+
369+
expect(plan).toMatchObject({
370+
restartGateway: false,
371+
restartReasons: [],
372+
hotReasons: [path],
373+
noopPaths: [],
374+
restartHeartbeat: false,
375+
restartCron: false,
376+
reloadHooks: false,
377+
reloadPlugins: false,
378+
disposeMcpRuntimes: false,
379+
restartChannels: new Set(),
380+
restartChannelAccounts: new Map(),
381+
});
382+
expect(resolveConfigReloadMetadata(path).kind).toBe("hot");
383+
});
384+
361385
it.each(["gateway.remote.url", "secrets.providers.default.path", "tui.footer.showRemoteHost"])(
362386
"keeps runtime-irrelevant path as a no-op: %s",
363387
(path) => {

‎src/gateway/gateway.test.ts‎

Lines changed: 259 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Gateway server integration tests cover startup, auth, device pairing, session
22
// routing, OpenAI-compatible paths, and environment isolation for local servers.
33
import fs from "node:fs/promises";
4+
import { createServer } from "node:http";
45
import os from "node:os";
56
import path from "node:path";
67
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
@@ -11,6 +12,13 @@ import {
1112
writeConfigFile,
1213
} from "../config/config.js";
1314
import { resetConfigOverrides, setConfigOverride } from "../config/runtime-overrides.js";
15+
import { resolveStorePath } from "../config/sessions/paths.js";
16+
import {
17+
appendTranscriptMessage,
18+
loadSessionEntry,
19+
loadTranscriptEventsSync,
20+
upsertSessionEntry,
21+
} from "../config/sessions/session-accessor.js";
1422
import { clearSessionStoreCacheForTest } from "../config/sessions/store-writer-state.js";
1523
import type { GatewayAuthConfig, GatewayTailscaleConfig } from "../config/types.gateway.js";
1624
import type { OpenClawConfig } from "../config/types.openclaw.js";
@@ -543,6 +551,257 @@ describe("gateway e2e", () => {
543551
}
544552
});
545553

554+
it(
555+
"applies a hot-reloaded compaction model to automatic chat preflight without restarting",
556+
{ timeout: GATEWAY_E2E_TIMEOUT_MS },
557+
async () => {
558+
const { envSnapshot, tempHome, workspaceDir } = await setupGatewayTempHome({
559+
prefix: "openclaw-gw-compaction-hot-reload-",
560+
});
561+
const token = nextGatewayId("compaction-hot-reload-token");
562+
setTestEnvValue("OPENCLAW_GATEWAY_TOKEN", token);
563+
564+
const providerRequests: Array<{ model: string }> = [];
565+
const summaryByModel = new Map<string, string>();
566+
const providerServer = createServer((request, response) => {
567+
void (async () => {
568+
const chunks: Buffer[] = [];
569+
for await (const chunk of request) {
570+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
571+
}
572+
if (request.method !== "POST" || request.url !== "/v1/responses") {
573+
response.writeHead(404).end();
574+
return;
575+
}
576+
const body = JSON.parse(Buffer.concat(chunks).toString("utf8")) as { model?: string };
577+
const model = body.model ?? "";
578+
providerRequests.push({ model });
579+
const text = summaryByModel.get(model) ?? "Primary assistant answer.";
580+
const message = {
581+
type: "message",
582+
id: nextGatewayId("provider-message"),
583+
role: "assistant",
584+
status: "completed",
585+
content: [{ type: "output_text", text, annotations: [] }],
586+
};
587+
const events = [
588+
{
589+
type: "response.output_item.added",
590+
item: { ...message, status: "in_progress", content: [] },
591+
},
592+
{ type: "response.output_item.done", item: message },
593+
{
594+
type: "response.completed",
595+
response: {
596+
status: "completed",
597+
usage: { input_tokens: 10, output_tokens: 10, total_tokens: 20 },
598+
},
599+
},
600+
];
601+
response.writeHead(200, { "content-type": "text/event-stream" });
602+
for (const event of events) {
603+
response.write(`data: ${JSON.stringify(event)}\n\n`);
604+
}
605+
response.end("data: [DONE]\n\n");
606+
})().catch((error: unknown) => {
607+
response.writeHead(500).end(error instanceof Error ? error.message : String(error));
608+
});
609+
});
610+
611+
let gateway: Awaited<ReturnType<typeof startGatewayWithClient>> | undefined;
612+
try {
613+
await new Promise<void>((resolve, reject) => {
614+
providerServer.once("error", reject);
615+
providerServer.listen(0, "127.0.0.1", resolve);
616+
});
617+
const providerAddress = providerServer.address();
618+
if (!providerAddress || typeof providerAddress === "string") {
619+
throw new Error("mock OpenAI Responses server did not bind a loopback port");
620+
}
621+
const baseUrl = `http://127.0.0.1:${providerAddress.port}/v1`;
622+
const primaryModel = buildMockOpenAiResponsesProvider(baseUrl, "gpt-primary");
623+
const oldCompactionModel = buildMockOpenAiResponsesProvider(baseUrl, "gpt-old-summary");
624+
const newCompactionModel = buildMockOpenAiResponsesProvider(baseUrl, "gpt-new-summary");
625+
const newSummary = "HOT_RELOAD_COMPACTION_SUMMARY";
626+
summaryByModel.set(oldCompactionModel.modelId, "STALE_COMPACTION_SUMMARY");
627+
summaryByModel.set(newCompactionModel.modelId, newSummary);
628+
629+
const initialConfig = {
630+
agents: {
631+
defaults: {
632+
workspace: workspaceDir,
633+
skipBootstrap: true,
634+
model: { primary: primaryModel.modelRef },
635+
models: {
636+
[primaryModel.modelRef]: { params: { transport: "sse", openaiWsWarmup: false } },
637+
[oldCompactionModel.modelRef]: {
638+
params: { transport: "sse", openaiWsWarmup: false },
639+
},
640+
[newCompactionModel.modelRef]: {
641+
params: { transport: "sse", openaiWsWarmup: false },
642+
},
643+
},
644+
compaction: {
645+
model: oldCompactionModel.modelRef,
646+
maxActiveTranscriptBytes: "1mb",
647+
keepRecentTokens: 1,
648+
recentTurnsPreserve: 1,
649+
qualityGuard: { enabled: false },
650+
memoryFlush: { enabled: false },
651+
},
652+
},
653+
entries: { dev: { default: true } },
654+
},
655+
models: {
656+
mode: "replace",
657+
providers: {
658+
[primaryModel.providerId]: {
659+
...primaryModel.config,
660+
models: [primaryModel, oldCompactionModel, newCompactionModel].map(({ config }) => ({
661+
...config.models[0],
662+
input: [...config.models[0].input],
663+
})),
664+
},
665+
},
666+
},
667+
gateway: { auth: { mode: "token", token } },
668+
} satisfies OpenClawConfig;
669+
670+
const configPath = await createGatewayConfigPath(tempHome);
671+
gateway = await startGatewayWithClient({
672+
cfg: initialConfig,
673+
configPath,
674+
token,
675+
clientDisplayName: "vitest-compaction-hot-reload",
676+
});
677+
const gatewayClient = gateway.client;
678+
const sessionKey = "agent:dev:main";
679+
const sessionId = nextGatewayId("existing-compaction-session");
680+
const scope = {
681+
agentId: "dev",
682+
sessionId,
683+
sessionKey,
684+
storePath: resolveStorePath(undefined, { agentId: "dev" }),
685+
};
686+
await upsertSessionEntry(scope, {
687+
sessionId,
688+
updatedAt: Date.now(),
689+
compactionCount: 0,
690+
modelProvider: primaryModel.providerId,
691+
model: primaryModel.modelId,
692+
totalTokens: 20,
693+
totalTokensFresh: true,
694+
});
695+
for (let turn = 0; turn < 6; turn += 1) {
696+
const timestamp = Date.now() + turn;
697+
await appendTranscriptMessage(scope, {
698+
message: {
699+
role: "user",
700+
content: `Historical request ${turn}: ${"persisted conversation ".repeat(24)}`,
701+
timestamp,
702+
},
703+
now: timestamp,
704+
});
705+
await appendTranscriptMessage(scope, {
706+
message: {
707+
role: "assistant",
708+
content: [
709+
{
710+
type: "text",
711+
text: `Historical answer ${turn}: ${"durable model context ".repeat(24)}`,
712+
},
713+
],
714+
api: "openai-responses",
715+
provider: primaryModel.providerId,
716+
model: primaryModel.modelId,
717+
usage: {
718+
input: 10,
719+
output: 10,
720+
cacheRead: 0,
721+
cacheWrite: 0,
722+
totalTokens: 20,
723+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
724+
},
725+
stopReason: "stop",
726+
timestamp,
727+
},
728+
now: timestamp,
729+
});
730+
}
731+
expect(loadTranscriptEventsSync(scope).length).toBeGreaterThan(10);
732+
733+
const sendChatAndWait = async (message: string) => {
734+
const started = await gatewayClient.request<{ runId: string; status: string }>(
735+
"chat.send",
736+
{ sessionKey, message, idempotencyKey: nextGatewayId("compaction-chat") },
737+
);
738+
expect(started.status).toBe("started");
739+
const completed = await gatewayClient.request<{ status: string }>(
740+
"agent.wait",
741+
{ runId: started.runId, timeoutMs: 30_000 },
742+
{ timeoutMs: 35_000 },
743+
);
744+
expect(completed.status).toBe("ok");
745+
};
746+
747+
await sendChatAndWait("Warm the existing prepared model runtime.");
748+
expect(providerRequests.map(({ model }) => model)).toContain(primaryModel.modelId);
749+
expect(loadSessionEntry(scope)?.compactionCount ?? 0).toBe(0);
750+
751+
await writeConfigFile({
752+
...initialConfig,
753+
agents: {
754+
...initialConfig.agents,
755+
defaults: {
756+
...initialConfig.agents.defaults,
757+
compaction: {
758+
...initialConfig.agents.defaults.compaction,
759+
model: newCompactionModel.modelRef,
760+
maxActiveTranscriptBytes: "10b",
761+
},
762+
},
763+
},
764+
});
765+
await expect
766+
.poll(() => getRuntimeConfig().agents?.defaults?.compaction?.model, {
767+
timeout: 5_000,
768+
interval: 50,
769+
})
770+
.toBe(newCompactionModel.modelRef);
771+
await expect
772+
.poll(() => getRuntimeConfig().agents?.defaults?.compaction?.maxActiveTranscriptBytes, {
773+
timeout: 5_000,
774+
interval: 50,
775+
})
776+
.toBe("10b");
777+
778+
const requestsBeforeCompaction = providerRequests.length;
779+
await sendChatAndWait("Compact the existing conversation before answering.");
780+
781+
const newRequests = providerRequests.slice(requestsBeforeCompaction);
782+
expect(newRequests.map(({ model }) => model)).toContain(newCompactionModel.modelId);
783+
expect(newRequests.map(({ model }) => model)).not.toContain(oldCompactionModel.modelId);
784+
expect(loadSessionEntry(scope)?.compactionCount).toBe(1);
785+
expect(loadTranscriptEventsSync(scope)).toContainEqual(
786+
expect.objectContaining({
787+
type: "compaction",
788+
summary: expect.stringContaining(newSummary),
789+
}),
790+
);
791+
await expect(gatewayClient.request("health", {})).resolves.toEqual(expect.any(Object));
792+
} finally {
793+
if (gateway) {
794+
await disconnectGatewayClient(gateway.client);
795+
await gateway.server.close({ reason: "compaction hot reload integration test complete" });
796+
}
797+
providerServer.closeAllConnections();
798+
await new Promise<void>((resolve) => providerServer.close(() => resolve()));
799+
await removeGatewayTempHome(tempHome);
800+
envSnapshot.restore();
801+
}
802+
},
803+
);
804+
546805
it(
547806
"accepts a gateway agent request over ws and returns a run id",
548807
{ timeout: GATEWAY_E2E_TIMEOUT_MS },

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

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1093,6 +1093,42 @@ describe("provider auth hot reload path ownership", () => {
10931093
});
10941094

10951095
describe("gateway hot reload model state", () => {
1096+
it.each([
1097+
"agents.defaults.compaction.model",
1098+
"agents.defaults.compaction.maxActiveTranscriptBytes",
1099+
])("refreshes prepared model runtime without restarting subsystems: %s", async (changedPath) => {
1100+
const logReload = { info: vi.fn(), warn: vi.fn() };
1101+
const channels = { start: vi.fn(async () => {}), stop: vi.fn(async () => {}) };
1102+
const { applyHotReload, heartbeatRunner, cron } = createReloadHandlersForTest(
1103+
logReload,
1104+
channels,
1105+
);
1106+
const nextConfig = {
1107+
agents: {
1108+
defaults: {
1109+
compaction: {
1110+
model: "mock-openai/gpt-5.6-luna-new",
1111+
maxActiveTranscriptBytes: "10b",
1112+
},
1113+
},
1114+
},
1115+
} satisfies OpenClawConfig;
1116+
1117+
await applyHotReload(buildGatewayReloadPlan([changedPath]), nextConfig);
1118+
1119+
expect(hoisted.markPreparedModelRuntimeSnapshotsStale).toHaveBeenCalledOnce();
1120+
expect(hoisted.refreshPreparedModelRuntimeSnapshots).toHaveBeenCalledWith(nextConfig, {
1121+
allowGatewaySubagentBinding: true,
1122+
catalogMode: "static",
1123+
});
1124+
expect(heartbeatRunner.updateConfig).not.toHaveBeenCalled();
1125+
expect(cron.stop).not.toHaveBeenCalled();
1126+
expect(channels.start).not.toHaveBeenCalled();
1127+
expect(channels.stop).not.toHaveBeenCalled();
1128+
expect(hoisted.disposeAllSessionMcpRuntimes).not.toHaveBeenCalled();
1129+
expect(logReload.info).toHaveBeenCalledWith(`config hot reload applied (${changedPath})`);
1130+
});
1131+
10961132
it("stops old cron exit watchers and reconciles rebuilt ones after cron restart", async () => {
10971133
const order: string[] = [];
10981134
const newCron = {

0 commit comments

Comments
 (0)