Skip to content

Commit 5ad0d4d

Browse files
abnershangsteipete
andauthored
fix: avoid false restart failure during startup migrations (#105544)
* fix: wait for startup migrations on restart * fix: honor restart readiness caller context * fix: preserve restart service identity * fix: refresh readiness context after repair * fix: bound migration restart wait by wall clock Co-authored-by: Abner Shang <[email protected]> --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent b537775 commit 5ad0d4d

11 files changed

Lines changed: 482 additions & 60 deletions

‎src/cli/daemon-cli/lifecycle.test.ts‎

Lines changed: 92 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@ type RestartPostCheckContext = {
2020

2121
type RestartParams = {
2222
opts?: { json?: boolean };
23+
repairLoadedService?: (ctx: {
24+
json: boolean;
25+
stdout: NodeJS.WritableStream;
26+
state: unknown;
27+
issues: unknown[];
28+
}) => Promise<unknown>;
2329
postRestartCheck?: (ctx: RestartPostCheckContext) => Promise<void>;
2430
};
2531

@@ -201,7 +207,12 @@ describe("runDaemonRestart health checks", () => {
201207
});
202208

203209
beforeEach(() => {
204-
envSnapshot = captureEnv(["OPENCLAW_CONTAINER_HINT", "OPENCLAW_PROFILE"]);
210+
envSnapshot = captureEnv([
211+
"OPENCLAW_CONTAINER_HINT",
212+
"OPENCLAW_PROFILE",
213+
"OPENCLAW_STATE_DIR",
214+
"OPENCLAW_SYSTEMD_UNIT",
215+
]);
205216
delete process.env.OPENCLAW_CONTAINER_HINT;
206217
service.readCommand.mockReset();
207218
service.readRuntime.mockReset();
@@ -331,6 +342,72 @@ describe("runDaemonRestart health checks", () => {
331342
expect(requireMockCallArg(runServiceRestart, "runServiceRestart").expectedPort).toBeUndefined();
332343
});
333344

345+
it("uses the installed service environment for managed restart health", async () => {
346+
process.env.OPENCLAW_STATE_DIR = "/tmp/openclaw-caller-state";
347+
process.env.OPENCLAW_SYSTEMD_UNIT = "openclaw-gateway-maintenance.service";
348+
service.readCommand.mockResolvedValue({
349+
programArguments: ["openclaw", "gateway", "--port", "18789"],
350+
environment: {
351+
OPENCLAW_STATE_DIR: "/tmp/openclaw-service-state",
352+
OPENCLAW_SYSTEMD_UNIT: "openclaw-gateway.service",
353+
},
354+
});
355+
356+
await runDaemonRestart({ json: true });
357+
358+
const waitParams = requireMockCallArg(
359+
waitForGatewayHealthyRestart,
360+
"waitForGatewayHealthyRestart",
361+
) as { env?: NodeJS.ProcessEnv };
362+
expect(waitParams.env?.OPENCLAW_STATE_DIR).toBe("/tmp/openclaw-service-state");
363+
expect(waitParams.env?.OPENCLAW_SYSTEMD_UNIT).toBe("openclaw-gateway-maintenance.service");
364+
});
365+
366+
it("re-reads the installed service environment after restart repair", async () => {
367+
service.readCommand
368+
.mockResolvedValueOnce({
369+
programArguments: ["openclaw", "gateway", "--port", "18789"],
370+
environment: { OPENCLAW_STATE_DIR: "/tmp/openclaw-stale-state" },
371+
})
372+
.mockResolvedValue({
373+
programArguments: ["openclaw", "gateway", "--port", "19001"],
374+
environment: { OPENCLAW_STATE_DIR: "/tmp/openclaw-repaired-state" },
375+
});
376+
repairLoadedGatewayServiceForStart.mockResolvedValue({
377+
result: "restarted",
378+
message: "Gateway service definition repaired and restarted.",
379+
loaded: true,
380+
});
381+
runServiceRestart.mockImplementation(async (params: RestartParams) => {
382+
await params.repairLoadedService?.({
383+
json: true,
384+
stdout: process.stdout,
385+
state: {},
386+
issues: [{ code: "version-mismatch", message: "old service" }],
387+
});
388+
await params.postRestartCheck?.({
389+
json: true,
390+
stdout: process.stdout,
391+
warnings: [],
392+
fail: (message: string) => {
393+
throw new Error(message);
394+
},
395+
});
396+
return true;
397+
});
398+
399+
await runDaemonRestart({ json: true });
400+
401+
expect(waitForGatewayHealthyRestart).toHaveBeenCalledWith(
402+
expect.objectContaining({
403+
port: 19_001,
404+
env: expect.objectContaining({
405+
OPENCLAW_STATE_DIR: "/tmp/openclaw-repaired-state",
406+
}),
407+
}),
408+
);
409+
});
410+
334411
it("repairs toward an explicitly configured gateway port", async () => {
335412
loadConfig.mockReturnValue({ gateway: { port: 19_001 } });
336413
resolveGatewayPort.mockReturnValue(19_001);
@@ -488,6 +565,20 @@ describe("runDaemonRestart health checks", () => {
488565
expect(renderRestartDiagnostics).toHaveBeenCalledTimes(1);
489566
});
490567

568+
it("reports the extended migration-aware timeout duration", async () => {
569+
waitForGatewayHealthyRestart.mockResolvedValue({
570+
healthy: false,
571+
staleGatewayPids: [],
572+
runtime: { status: "running", pid: 4242 },
573+
portUsage: { port: 18789, status: "free", listeners: [], hints: [] },
574+
waitOutcome: "timeout",
575+
elapsedMs: 360_000,
576+
});
577+
578+
const error = await expectRestartError(runDaemonRestart({ json: true }));
579+
expect(error.message).toBe("Gateway restart timed out after 360s waiting for health checks.");
580+
});
581+
491582
it("waits longer for Windows gateway restart health", async () => {
492583
vi.spyOn(process, "platform", "get").mockReturnValue("win32");
493584
waitForGatewayHealthyRestart.mockResolvedValue({

‎src/cli/daemon-cli/lifecycle.ts‎

Lines changed: 43 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { normalizeOptionalString } from "@openclaw/normalization-core/string-coe
44
import { theme } from "../../../packages/terminal-core/src/theme.js";
55
import { isRestartEnabled } from "../../config/commands.flags.js";
66
import { readBestEffortConfig, resolveGatewayPort } from "../../config/config.js";
7+
import { mergeGatewayServiceEnv } from "../../daemon/service-env-merge.js";
78
import { resolveGatewayService } from "../../daemon/service.js";
89
import {
910
findInstalledSystemdGatewayScope,
@@ -61,7 +62,7 @@ function postRestartHealthAttempts(): number {
6162
function formatRestartFailure(params: {
6263
health: GatewayRestartSnapshot;
6364
port: number;
64-
timeoutSeconds: number;
65+
defaultTimeoutSeconds: number;
6566
}): { statusLine: string; failMessage: string } {
6667
if (params.health.waitOutcome === "stopped-free") {
6768
const elapsedSeconds = Math.max(1, Math.round((params.health.elapsedMs ?? 0) / 1000));
@@ -71,22 +72,37 @@ function formatRestartFailure(params: {
7172
};
7273
}
7374

75+
const timeoutSeconds = Math.max(
76+
1,
77+
Math.round(
78+
params.health.elapsedMs === undefined
79+
? params.defaultTimeoutSeconds
80+
: params.health.elapsedMs / 1000,
81+
),
82+
);
7483
return {
75-
statusLine: `Timed out after ${params.timeoutSeconds}s waiting for gateway port ${params.port} to become healthy.`,
76-
failMessage: `Gateway restart timed out after ${params.timeoutSeconds}s waiting for health checks.`,
84+
statusLine: `Timed out after ${timeoutSeconds}s waiting for gateway port ${params.port} to become healthy.`,
85+
failMessage: `Gateway restart timed out after ${timeoutSeconds}s waiting for health checks.`,
7786
};
7887
}
7988

80-
async function resolveGatewayLifecyclePort(service = resolveGatewayService()) {
89+
async function resolveGatewayLifecycleContext(service = resolveGatewayService()): Promise<{
90+
port: number;
91+
env: NodeJS.ProcessEnv;
92+
}> {
8193
const command = await service.readCommand(process.env).catch(() => null);
82-
const serviceEnv = command?.environment ?? undefined;
83-
const mergedEnv = {
84-
...(process.env as Record<string, string | undefined>),
85-
...(serviceEnv ?? undefined),
86-
} as NodeJS.ProcessEnv;
94+
const mergedEnv = mergeGatewayServiceEnv(process.env, command);
8795

8896
const portFromArgs = parsePortFromArgs(command?.programArguments);
89-
return portFromArgs ?? resolveGatewayPort(await readBestEffortConfig(), mergedEnv);
97+
const config = await readBestEffortConfig().catch(() => undefined);
98+
return {
99+
port: portFromArgs ?? resolveGatewayPort(config, mergedEnv),
100+
env: mergedEnv,
101+
};
102+
}
103+
104+
async function resolveGatewayLifecyclePort(service = resolveGatewayService()) {
105+
return (await resolveGatewayLifecycleContext(service)).port;
90106
}
91107

92108
function resolveGatewayPortFallback(): Promise<number> {
@@ -347,9 +363,11 @@ export async function runDaemonRestart(opts: DaemonLifecycleOptions = {}): Promi
347363
let restartedWithoutServiceManager = false;
348364
const restartIntent = resolveGatewayRestartIntentOptions(opts);
349365
const configuredPort = await resolveExplicitGatewayConfigPort();
350-
const managedRestartPort =
351-
configuredPort ??
352-
(await resolveGatewayLifecyclePort(service).catch(() => resolveGatewayPortFallback()));
366+
let managedRestartContext = await resolveGatewayLifecycleContext(service).catch(async () => ({
367+
port: await resolveGatewayPortFallback(),
368+
env: process.env,
369+
}));
370+
let managedRestartPort = configuredPort ?? managedRestartContext.port;
353371
// An unmanaged run loop keeps its lock port across in-process restarts, even
354372
// when config changes underneath it. Use that port for both the signal and
355373
// health proof or a valid CLI/env override looks like a failed restart.
@@ -369,8 +387,8 @@ export async function runDaemonRestart(opts: DaemonLifecycleOptions = {}): Promi
369387
},
370388
checkTokenDrift: true,
371389
expectedPort: configuredPort,
372-
repairLoadedService: async ({ json, stdout, warn, state, issues }) =>
373-
await repairLoadedGatewayServiceForStart({
390+
repairLoadedService: async ({ json, stdout, warn, state, issues }) => {
391+
const result = await repairLoadedGatewayServiceForStart({
374392
action: "restart",
375393
service,
376394
port: configuredPort,
@@ -379,7 +397,13 @@ export async function runDaemonRestart(opts: DaemonLifecycleOptions = {}): Promi
379397
warn,
380398
state,
381399
issues,
382-
}),
400+
});
401+
// Repair rewrites the service definition, so the old command environment
402+
// no longer identifies where the restarted gateway publishes readiness.
403+
managedRestartContext = await resolveGatewayLifecycleContext(service);
404+
managedRestartPort = configuredPort ?? managedRestartContext.port;
405+
return result;
406+
},
383407
onNotLoaded: async () => {
384408
if (process.platform === "darwin") {
385409
const recovered = await recoverInstalledLaunchAgent({ result: "restarted" });
@@ -430,6 +454,7 @@ export async function runDaemonRestart(opts: DaemonLifecycleOptions = {}): Promi
430454
port: managedRestartPort,
431455
attempts: restartHealthAttempts,
432456
delayMs: POST_RESTART_HEALTH_DELAY_MS,
457+
env: managedRestartContext.env,
433458
includeUnknownListenersAsStale: process.platform === "win32",
434459
});
435460

@@ -453,6 +478,7 @@ export async function runDaemonRestart(opts: DaemonLifecycleOptions = {}): Promi
453478
port: managedRestartPort,
454479
attempts: restartHealthAttempts,
455480
delayMs: POST_RESTART_HEALTH_DELAY_MS,
481+
env: managedRestartContext.env,
456482
includeUnknownListenersAsStale: process.platform === "win32",
457483
});
458484
}
@@ -465,7 +491,7 @@ export async function runDaemonRestart(opts: DaemonLifecycleOptions = {}): Promi
465491
const failure = formatRestartFailure({
466492
health,
467493
port: managedRestartPort,
468-
timeoutSeconds: restartWaitSeconds,
494+
defaultTimeoutSeconds: restartWaitSeconds,
469495
});
470496
const runningNoPortLine =
471497
health.runtime.status === "running" && health.portUsage.status === "free"

0 commit comments

Comments
 (0)