Skip to content

Commit 616f24f

Browse files
authored
refactor(gateway): consolidate lifecycle lazy boundary (#74105)
* refactor(gateway): consolidate lifecycle lazy boundary * test(gateway): cover quoted lifecycle imports
1 parent 53e0874 commit 616f24f

5 files changed

Lines changed: 97 additions & 69 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ Docs: https://docs.openclaw.ai
2121

2222
### Fixes
2323

24+
- Build/Gateway: route restart, shutdown, respawn, diagnostics, command-queue cleanup, and runtime cleanup through one stable gateway lifecycle runtime entry so rebuilt packages do not strand long-running gateways on stale hashed chunks. Carries forward #73964. Thanks @pashpashpash.
2425
- Agents/errors: suppress malformed streaming tool-call JSON fragments before they reach chat surfaces while preserving provider request-validation diagnostics. Fixes #59076; keeps #59080 as duplicate coverage. (#59118) Thanks @singleGanghood.
2526
- CLI/models: restore provider-filtered `models list --all --provider <id>` rows for providers without manifest/static catalog coverage, including Anthropic and Amazon Bedrock, while keeping the compatibility fallback off expensive availability and resolver paths. Thanks @shakkernerd.
2627
- CLI/models: move the OpenAI listable catalog into the plugin manifest so `models list --all --provider openai` uses the manifest fast path instead of loading provider runtime normalization hooks. Thanks @shakkernerd.
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
export {
2+
abortEmbeddedPiRun,
3+
getActiveEmbeddedRunCount,
4+
waitForActiveEmbeddedRuns,
5+
} from "../../agents/pi-embedded-runner/runs.js";
6+
export { getRuntimeConfig } from "../../config/config.js";
7+
export {
8+
respawnGatewayProcessForUpdate,
9+
restartGatewayProcessWithFreshPid,
10+
} from "../../infra/process-respawn.js";
11+
export {
12+
resolveGatewayRestartDeferralTimeoutMs,
13+
consumeGatewayRestartIntentSync,
14+
consumeGatewaySigusr1RestartAuthorization,
15+
isGatewaySigusr1RestartExternallyAllowed,
16+
markGatewaySigusr1RestartHandled,
17+
peekGatewaySigusr1RestartReason,
18+
resetGatewayRestartStateForInProcessRestart,
19+
scheduleGatewaySigusr1Restart,
20+
} from "../../infra/restart.js";
21+
export { markUpdateRestartSentinelFailure } from "../../infra/restart-sentinel.js";
22+
export { detectRespawnSupervisor } from "../../infra/supervisor-markers.js";
23+
export { writeDiagnosticStabilityBundleForFailureSync } from "../../logging/diagnostic-stability-bundle.js";
24+
export {
25+
getActiveBundledRuntimeDepsInstallCount,
26+
waitForBundledRuntimeDepsInstallIdle,
27+
} from "../../plugins/bundled-runtime-deps-activity.js";
28+
export {
29+
getActiveTaskCount,
30+
markGatewayDraining,
31+
resetAllLanes,
32+
waitForActiveTasks,
33+
} from "../../process/command-queue.js";
34+
export { reloadTaskRegistryFromStore } from "../../tasks/runtime-internal.js";

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

Lines changed: 30 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -15,48 +15,12 @@ const UPDATE_RESPAWN_HEALTH_POLL_MS = 200;
1515
type GatewayRunSignalAction = "stop" | "restart";
1616
type RestartDrainTimeoutMs = number | undefined;
1717

18-
type EmbeddedRunsModule = typeof import("../../agents/pi-embedded-runner/runs.js");
19-
type RuntimeConfigModule = typeof import("../../config/config.js");
20-
type ProcessRespawnModule = typeof import("../../infra/process-respawn.js");
21-
type RestartSentinelModule = typeof import("../../infra/restart-sentinel.js");
22-
type RestartModule = typeof import("../../infra/restart.js");
23-
type SupervisorMarkersModule = typeof import("../../infra/supervisor-markers.js");
24-
type DiagnosticStabilityBundleModule =
25-
typeof import("../../logging/diagnostic-stability-bundle.js");
26-
type BundledRuntimeDepsActivityModule =
27-
typeof import("../../plugins/bundled-runtime-deps-activity.js");
28-
type CommandQueueModule = typeof import("../../process/command-queue.js");
29-
type RuntimeInternalModule = typeof import("../../tasks/runtime-internal.js");
18+
type GatewayLifecycleRuntimeModule = typeof import("./lifecycle.runtime.js");
3019

31-
let embeddedRunsModule: Promise<EmbeddedRunsModule> | undefined;
32-
let runtimeConfigModule: Promise<RuntimeConfigModule> | undefined;
33-
let processRespawnModule: Promise<ProcessRespawnModule> | undefined;
34-
let restartSentinelModule: Promise<RestartSentinelModule> | undefined;
35-
let restartModule: Promise<RestartModule> | undefined;
36-
let supervisorMarkersModule: Promise<SupervisorMarkersModule> | undefined;
37-
let diagnosticStabilityBundleModule: Promise<DiagnosticStabilityBundleModule> | undefined;
38-
let bundledRuntimeDepsActivityModule: Promise<BundledRuntimeDepsActivityModule> | undefined;
39-
let commandQueueModule: Promise<CommandQueueModule> | undefined;
40-
let runtimeInternalModule: Promise<RuntimeInternalModule> | undefined;
20+
let gatewayLifecycleRuntimeModule: Promise<GatewayLifecycleRuntimeModule> | undefined;
4121

42-
const loadEmbeddedRunsModule = () =>
43-
(embeddedRunsModule ??= import("../../agents/pi-embedded-runner/runs.js"));
44-
const loadRuntimeConfigModule = () => (runtimeConfigModule ??= import("../../config/config.js"));
45-
const loadProcessRespawnModule = () =>
46-
(processRespawnModule ??= import("../../infra/process-respawn.js"));
47-
const loadRestartSentinelModule = () =>
48-
(restartSentinelModule ??= import("../../infra/restart-sentinel.js"));
49-
const loadRestartModule = () => (restartModule ??= import("../../infra/restart.js"));
50-
const loadSupervisorMarkersModule = () =>
51-
(supervisorMarkersModule ??= import("../../infra/supervisor-markers.js"));
52-
const loadDiagnosticStabilityBundleModule = () =>
53-
(diagnosticStabilityBundleModule ??= import("../../logging/diagnostic-stability-bundle.js"));
54-
const loadBundledRuntimeDepsActivityModule = () =>
55-
(bundledRuntimeDepsActivityModule ??= import("../../plugins/bundled-runtime-deps-activity.js"));
56-
const loadCommandQueueModule = () =>
57-
(commandQueueModule ??= import("../../process/command-queue.js"));
58-
const loadRuntimeInternalModule = () =>
59-
(runtimeInternalModule ??= import("../../tasks/runtime-internal.js"));
22+
const loadGatewayLifecycleRuntimeModule = () =>
23+
(gatewayLifecycleRuntimeModule ??= import("./lifecycle.runtime.js"));
6024

6125
function createRestartIterationHook(onRestart: () => Promise<void> | void): () => Promise<boolean> {
6226
let isFirstIteration = true;
@@ -137,7 +101,7 @@ export async function runGatewayLoop(params: {
137101
};
138102
const writeStabilityBundle = async (reason: string, error?: unknown) => {
139103
const { writeDiagnosticStabilityBundleForFailureSync } =
140-
await loadDiagnosticStabilityBundleModule();
104+
await loadGatewayLifecycleRuntimeModule();
141105
const result = writeDiagnosticStabilityBundleForFailureSync(reason, error);
142106
if ("message" in result) {
143107
gatewayLog.warn(result.message);
@@ -165,10 +129,12 @@ export async function runGatewayLoop(params: {
165129
const handleRestartAfterServerClose = async (restartReason?: string) => {
166130
const hadLock = await releaseLockIfHeld();
167131
const isUpdateRestart = restartReason === "update.run";
168-
const { respawnGatewayProcessForUpdate, restartGatewayProcessWithFreshPid } =
169-
await loadProcessRespawnModule();
170-
const { detectRespawnSupervisor } = await loadSupervisorMarkersModule();
171-
const { markUpdateRestartSentinelFailure } = await loadRestartSentinelModule();
132+
const {
133+
detectRespawnSupervisor,
134+
markUpdateRestartSentinelFailure,
135+
respawnGatewayProcessForUpdate,
136+
restartGatewayProcessWithFreshPid,
137+
} = await loadGatewayLifecycleRuntimeModule();
172138

173139
if (isUpdateRestart) {
174140
const respawn = respawnGatewayProcessForUpdate();
@@ -279,10 +245,8 @@ export async function runGatewayLoop(params: {
279245
const SHUTDOWN_TIMEOUT_MS = SUPERVISOR_STOP_TIMEOUT_MS - 5_000;
280246
const resolveRestartDrainTimeoutMs = async (): Promise<RestartDrainTimeoutMs> => {
281247
try {
282-
const [{ getRuntimeConfig }, { resolveGatewayRestartDeferralTimeoutMs }] = await Promise.all([
283-
loadRuntimeConfigModule(),
284-
loadRestartModule(),
285-
]);
248+
const { getRuntimeConfig, resolveGatewayRestartDeferralTimeoutMs } =
249+
await loadGatewayLifecycleRuntimeModule();
286250
const timeoutMs = getRuntimeConfig().gateway?.reload?.deferralTimeoutMs;
287251
return resolveGatewayRestartDeferralTimeoutMs(timeoutMs);
288252
} catch {
@@ -351,15 +315,16 @@ export async function runGatewayLoop(params: {
351315
// On restart, wait for in-flight agent turns to finish before
352316
// tearing down the server so buffered messages are delivered.
353317
if (isRestart) {
354-
const [
355-
{ abortEmbeddedPiRun, getActiveEmbeddedRunCount, waitForActiveEmbeddedRuns },
356-
{ getActiveBundledRuntimeDepsInstallCount, waitForBundledRuntimeDepsInstallIdle },
357-
{ getActiveTaskCount, markGatewayDraining, waitForActiveTasks },
358-
] = await Promise.all([
359-
loadEmbeddedRunsModule(),
360-
loadBundledRuntimeDepsActivityModule(),
361-
loadCommandQueueModule(),
362-
]);
318+
const {
319+
abortEmbeddedPiRun,
320+
getActiveBundledRuntimeDepsInstallCount,
321+
getActiveEmbeddedRunCount,
322+
getActiveTaskCount,
323+
markGatewayDraining,
324+
waitForActiveEmbeddedRuns,
325+
waitForActiveTasks,
326+
waitForBundledRuntimeDepsInstallIdle,
327+
} = await loadGatewayLifecycleRuntimeModule();
363328
const createStillPendingDrainLogger = () =>
364329
setInterval(() => {
365330
gatewayLog.warn(
@@ -429,7 +394,7 @@ export async function runGatewayLoop(params: {
429394
const onSigterm = () => {
430395
gatewayLog.info("signal SIGTERM received");
431396
void (async () => {
432-
const { consumeGatewayRestartIntentSync } = await loadRestartModule();
397+
const { consumeGatewayRestartIntentSync } = await loadGatewayLifecycleRuntimeModule();
433398
request(consumeGatewayRestartIntentSync() ? "restart" : "stop", "SIGTERM");
434399
})();
435400
};
@@ -446,7 +411,7 @@ export async function runGatewayLoop(params: {
446411
markGatewaySigusr1RestartHandled,
447412
peekGatewaySigusr1RestartReason,
448413
scheduleGatewaySigusr1Restart,
449-
} = await loadRestartModule();
414+
} = await loadGatewayLifecycleRuntimeModule();
450415
const authorized = consumeGatewaySigusr1RestartAuthorization();
451416
if (!authorized) {
452417
if (!isGatewaySigusr1RestartExternallyAllowed()) {
@@ -482,15 +447,11 @@ export async function runGatewayLoop(params: {
482447
// new work from draining. The same boundary also discards stale restart
483448
// deferral timers and reloads the task registry from durable state so
484449
// cancelled/completed work is not kept alive by old in-memory maps.
485-
const [
486-
{ resetAllLanes },
487-
{ resetGatewayRestartStateForInProcessRestart },
488-
{ reloadTaskRegistryFromStore },
489-
] = await Promise.all([
490-
loadCommandQueueModule(),
491-
loadRestartModule(),
492-
loadRuntimeInternalModule(),
493-
]);
450+
const {
451+
reloadTaskRegistryFromStore,
452+
resetAllLanes,
453+
resetGatewayRestartStateForInProcessRestart,
454+
} = await loadGatewayLifecycleRuntimeModule();
494455
resetAllLanes();
495456
resetGatewayRestartStateForInProcessRestart();
496457
reloadTaskRegistryFromStore();

‎src/infra/tsdown-config.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { readFileSync } from "node:fs";
12
import { bundledPluginRoot } from "openclaw/plugin-sdk/test-fixtures";
23
import { describe, expect, it } from "vitest";
34
import tsdownConfig from "../../tsdown.config.ts";
@@ -41,6 +42,13 @@ function entryKeys(config: TsdownConfigEntry): string[] {
4142
return Object.keys(config.entry);
4243
}
4344

45+
function entrySources(config: TsdownConfigEntry): Record<string, string> {
46+
if (!config.entry || Array.isArray(config.entry)) {
47+
return {};
48+
}
49+
return config.entry;
50+
}
51+
4452
function hasBundledPluginRuntimeEntry(config: TsdownConfigEntry): boolean {
4553
const keys = entryKeys(config);
4654
return keys.includes("index") || keys.includes("runtime-api");
@@ -56,6 +64,10 @@ function unifiedDistGraph(): TsdownConfigEntry | undefined {
5664
);
5765
}
5866

67+
function readGatewayRunLoopSource(): string {
68+
return readFileSync(new URL("../cli/gateway-cli/run-loop.ts", import.meta.url), "utf8");
69+
}
70+
5971
describe("tsdown config", () => {
6072
it("keeps core, plugin runtime, plugin-sdk, bundled root plugins, and bundled hooks in one dist graph", () => {
6173
const distGraph = unifiedDistGraph();
@@ -66,6 +78,7 @@ describe("tsdown config", () => {
6678
"agents/auth-profiles.runtime",
6779
"agents/model-catalog.runtime",
6880
"agents/models-config.runtime",
81+
"cli/gateway-lifecycle.runtime",
6982
"plugins/memory-state",
7083
"subagent-registry.runtime",
7184
"task-registry-control.runtime",
@@ -85,6 +98,24 @@ describe("tsdown config", () => {
8598
);
8699
});
87100

101+
it("keeps gateway lifecycle lazy runtime behind one stable dist entry", () => {
102+
const distGraph = unifiedDistGraph();
103+
104+
expect(entrySources(distGraph as TsdownConfigEntry)).toEqual(
105+
expect.objectContaining({
106+
"cli/gateway-lifecycle.runtime": "src/cli/gateway-cli/lifecycle.runtime.ts",
107+
}),
108+
);
109+
});
110+
111+
it("routes gateway run-loop lifecycle imports through the stable runtime boundary", () => {
112+
const importSpecifiers = [
113+
...readGatewayRunLoopSource().matchAll(/import\(["']([^"']+)["']\)/gu),
114+
].map((match) => match[1]);
115+
116+
expect(new Set(importSpecifiers)).toEqual(new Set(["./lifecycle.runtime.js"]));
117+
});
118+
88119
it("emits staged bundled plugins as separate extension graphs", () => {
89120
const stagedGraphs = asConfigArray(tsdownConfig).filter(
90121
(config) => typeof config.outDir === "string" && config.outDir.startsWith("dist/extensions/"),

‎tsdown.config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,7 @@ function buildCoreDistEntries(): Record<string, string> {
212212
"agents/auth-profiles.runtime": "src/agents/auth-profiles.runtime.ts",
213213
"agents/model-catalog.runtime": "src/agents/model-catalog.runtime.ts",
214214
"agents/models-config.runtime": "src/agents/models-config.runtime.ts",
215+
"cli/gateway-lifecycle.runtime": "src/cli/gateway-cli/lifecycle.runtime.ts",
215216
"plugins/memory-state": "src/plugins/memory-state.ts",
216217
"subagent-registry.runtime": "src/agents/subagent-registry.runtime.ts",
217218
"task-registry-control.runtime": "src/tasks/task-registry-control.runtime.ts",

0 commit comments

Comments
 (0)