Skip to content

Commit cc3dfc9

Browse files
authored
fix: preserve unmanaged gateway restart truth (#105241)
1 parent 1592d42 commit cc3dfc9

4 files changed

Lines changed: 68 additions & 12 deletions

File tree

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

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ const probeGateway = vi.fn<
5353
const callGatewayCli = vi.fn();
5454
const isRestartEnabled = vi.fn<(config?: { commands?: unknown }) => boolean>(() => true);
5555
const loadConfig = vi.hoisted(() => vi.fn(() => ({})));
56+
const readActiveGatewayLockPort = vi.hoisted(() => vi.fn<() => Promise<number | undefined>>());
5657
const recoverInstalledLaunchAgent = vi.hoisted(() => vi.fn());
5758
const repairLoadedGatewayServiceForStart = vi.hoisted(() => vi.fn());
5859
const findInstalledSystemdGatewayScope = vi.hoisted(() =>
@@ -103,6 +104,10 @@ vi.mock("../../infra/gateway-processes.js", () => ({
103104
formatGatewayPidList: (pids: number[]) => formatGatewayPidList(pids),
104105
}));
105106

107+
vi.mock("../../infra/gateway-lock.js", () => ({
108+
readActiveGatewayLockPort: () => readActiveGatewayLockPort(),
109+
}));
110+
106111
vi.mock("../../gateway/probe.js", () => ({
107112
probeGateway: (opts: {
108113
url: string;
@@ -214,6 +219,7 @@ describe("runDaemonRestart health checks", () => {
214219
callGatewayCli.mockReset();
215220
isRestartEnabled.mockReset();
216221
loadConfig.mockReset();
222+
readActiveGatewayLockPort.mockReset();
217223
recoverInstalledLaunchAgent.mockReset();
218224
repairLoadedGatewayServiceForStart.mockReset();
219225

@@ -224,6 +230,7 @@ describe("runDaemonRestart health checks", () => {
224230
service.restart.mockResolvedValue({ outcome: "completed" });
225231
runServiceStart.mockResolvedValue(undefined);
226232
recoverInstalledLaunchAgent.mockResolvedValue(null);
233+
readActiveGatewayLockPort.mockResolvedValue(undefined);
227234
findInstalledSystemdGatewayScope.mockReset();
228235
findInstalledSystemdGatewayScope.mockResolvedValue(null);
229236
restartSystemdService.mockReset();
@@ -575,6 +582,26 @@ describe("runDaemonRestart health checks", () => {
575582
expect(service.restart).not.toHaveBeenCalled();
576583
});
577584

585+
it("signals and verifies the active unmanaged port despite a config edit", async () => {
586+
loadConfig.mockReturnValue({ gateway: { port: 19_001 } });
587+
readActiveGatewayLockPort.mockResolvedValue(18_789);
588+
findVerifiedGatewayListenerPidsOnPortSync.mockImplementation((port) =>
589+
port === 18_789 ? [4200] : [],
590+
);
591+
mockUnmanagedRestart({ runPostRestartCheck: true });
592+
593+
await runDaemonRestart({ json: true });
594+
595+
expect(findVerifiedGatewayListenerPidsOnPortSync).toHaveBeenCalledWith(18_789);
596+
expect(probeGateway).toHaveBeenCalledWith(
597+
expect.objectContaining({ url: "ws://127.0.0.1:18789" }),
598+
);
599+
expect(signalVerifiedGatewayPidSync).toHaveBeenCalledWith(4200, "SIGUSR1");
600+
expect(waitForGatewayHealthyListener).toHaveBeenCalledWith(
601+
expect.objectContaining({ port: 18_789 }),
602+
);
603+
});
604+
578605
it("prefers launchd repair over unmanaged restart when an installed LaunchAgent is unloaded", async () => {
579606
vi.spyOn(process, "platform", "get").mockReturnValue("darwin");
580607
recoverInstalledLaunchAgent.mockResolvedValue({

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

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
} from "../../daemon/systemd.js";
1313
import { callGatewayCli } from "../../gateway/call.js";
1414
import { probeGateway } from "../../gateway/probe.js";
15+
import { readActiveGatewayLockPort } from "../../infra/gateway-lock.js";
1516
import {
1617
findVerifiedGatewayListenerPidsOnPortSync,
1718
formatGatewayPidList,
@@ -334,9 +335,14 @@ export async function runDaemonRestart(opts: DaemonLifecycleOptions = {}): Promi
334335
let restartedWithoutServiceManager = false;
335336
const restartIntent = resolveGatewayRestartIntentOptions(opts);
336337
const configuredPort = await resolveExplicitGatewayConfigPort();
337-
const restartPort =
338+
const managedRestartPort =
338339
configuredPort ??
339340
(await resolveGatewayLifecyclePort(service).catch(() => resolveGatewayPortFallback()));
341+
// An unmanaged run loop keeps its lock port across in-process restarts, even
342+
// when config changes underneath it. Use that port for both the signal and
343+
// health proof or a valid CLI/env override looks like a failed restart.
344+
const unmanagedPort =
345+
(await readActiveGatewayLockPort().catch(() => undefined)) ?? managedRestartPort;
340346
const restartHealthAttempts = postRestartHealthAttempts();
341347
const restartWaitMs = restartHealthAttempts * POST_RESTART_HEALTH_DELAY_MS;
342348
const restartWaitSeconds = Math.round(restartWaitMs / 1000);
@@ -369,7 +375,7 @@ export async function runDaemonRestart(opts: DaemonLifecycleOptions = {}): Promi
369375
return recovered;
370376
}
371377
}
372-
const handled = await restartGatewayWithoutServiceManager(restartPort, restartIntent);
378+
const handled = await restartGatewayWithoutServiceManager(unmanagedPort, restartIntent);
373379
if (handled) {
374380
restartedWithoutServiceManager = true;
375381
return handled;
@@ -380,7 +386,7 @@ export async function runDaemonRestart(opts: DaemonLifecycleOptions = {}): Promi
380386
if (restartedWithoutServiceManager) {
381387
// SIGUSR1 restarts have no service-manager state to watch; use listener health only.
382388
const health = await waitForGatewayHealthyListener({
383-
port: restartPort,
389+
port: unmanagedPort,
384390
attempts: restartHealthAttempts,
385391
delayMs: POST_RESTART_HEALTH_DELAY_MS,
386392
});
@@ -389,7 +395,7 @@ export async function runDaemonRestart(opts: DaemonLifecycleOptions = {}): Promi
389395
}
390396

391397
const diagnostics = renderGatewayPortHealthDiagnostics(health);
392-
const timeoutLine = `Timed out after ${restartWaitSeconds}s waiting for gateway port ${restartPort} to become healthy.`;
398+
const timeoutLine = `Timed out after ${restartWaitSeconds}s waiting for gateway port ${unmanagedPort} to become healthy.`;
393399
if (!jsonOutput) {
394400
defaultRuntime.log(theme.warn(timeoutLine));
395401
for (const line of diagnostics) {
@@ -409,7 +415,7 @@ export async function runDaemonRestart(opts: DaemonLifecycleOptions = {}): Promi
409415

410416
let health = await waitForGatewayHealthyRestart({
411417
service,
412-
port: restartPort,
418+
port: managedRestartPort,
413419
attempts: restartHealthAttempts,
414420
delayMs: POST_RESTART_HEALTH_DELAY_MS,
415421
includeUnknownListenersAsStale: process.platform === "win32",
@@ -432,7 +438,7 @@ export async function runDaemonRestart(opts: DaemonLifecycleOptions = {}): Promi
432438
}
433439
health = await waitForGatewayHealthyRestart({
434440
service,
435-
port: restartPort,
441+
port: managedRestartPort,
436442
attempts: restartHealthAttempts,
437443
delayMs: POST_RESTART_HEALTH_DELAY_MS,
438444
includeUnknownListenersAsStale: process.platform === "win32",
@@ -446,12 +452,12 @@ export async function runDaemonRestart(opts: DaemonLifecycleOptions = {}): Promi
446452
const diagnostics = renderRestartDiagnostics(health);
447453
const failure = formatRestartFailure({
448454
health,
449-
port: restartPort,
455+
port: managedRestartPort,
450456
timeoutSeconds: restartWaitSeconds,
451457
});
452458
const runningNoPortLine =
453459
health.runtime.status === "running" && health.portUsage.status === "free"
454-
? `Gateway process is running but port ${restartPort} is still free (startup hang/crash loop or very slow VM startup).`
460+
? `Gateway process is running but port ${managedRestartPort} is still free (startup hang/crash loop or very slow VM startup).`
455461
: null;
456462
if (!jsonOutput) {
457463
defaultRuntime.log(theme.warn(failure.statusLine));

‎src/crestodian/operations.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,24 @@ describe("parseCrestodianOperation", () => {
559559
expect(runGatewayRestart).not.toHaveBeenCalled();
560560
});
561561

562+
it("does not report or audit a gateway restart that returned false", async () => {
563+
const tempDir = opTempDirs.make("crestodian-restart-failed-");
564+
setTestEnvValue("OPENCLAW_STATE_DIR", tempDir);
565+
const { runtime, lines } = createCrestodianTestRuntime();
566+
const runGatewayRestart = vi.fn(async () => false);
567+
568+
await expect(
569+
executeCrestodianOperation({ kind: "gateway-restart" }, runtime, {
570+
approved: true,
571+
deps: { runGatewayRestart },
572+
}),
573+
).rejects.toThrow("Gateway restart did not complete");
574+
575+
expect(lines.join("\n")).toContain("[crestodian] running: gateway.restart");
576+
expect(lines.join("\n")).not.toContain("[crestodian] done: gateway.restart");
577+
await expect(fs.access(path.join(tempDir, "audit", "crestodian.jsonl"))).rejects.toThrow();
578+
});
579+
562580
it("validates missing config without exiting the process", async () => {
563581
mockConfig.missing("/tmp/openclaw.json");
564582
const { runtime, lines } = createCrestodianTestRuntime();

‎src/crestodian/operations.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ export type CrestodianCommandDeps = {
114114
cliOptions: ConfigSetOptions;
115115
}) => Promise<void>;
116116
runDoctor?: (runtime: RuntimeEnv, options: DoctorOptions) => Promise<void>;
117-
runGatewayRestart?: () => Promise<void>;
117+
runGatewayRestart?: () => Promise<void | boolean>;
118118
runGatewayStart?: () => Promise<void>;
119119
runGatewayStop?: () => Promise<void>;
120120
runPluginInstall?: (spec: string, runtime: RuntimeEnv) => Promise<void>;
@@ -560,7 +560,9 @@ function formatGatewayStatusLine(overview: CrestodianOverview): string {
560560
.join("\n");
561561
}
562562

563-
async function runGatewayLifecycle(operation: "start" | "stop" | "restart"): Promise<void> {
563+
async function runGatewayLifecycle(
564+
operation: "start" | "stop" | "restart",
565+
): Promise<void | boolean> {
564566
const lifecycle = await import("../cli/daemon-cli/lifecycle.js");
565567
if (operation === "start") {
566568
await lifecycle.runDaemonStart();
@@ -570,7 +572,7 @@ async function runGatewayLifecycle(operation: "start" | "stop" | "restart"): Pro
570572
await lifecycle.runDaemonStop();
571573
return;
572574
}
573-
await lifecycle.runDaemonRestart();
575+
return await lifecycle.runDaemonRestart();
574576
}
575577

576578
async function readConfigFileSnapshotLazy(): Promise<ConfigFileSnapshot> {
@@ -1493,7 +1495,10 @@ export async function executeCrestodianOperation(
14931495
run: async (ctx) => {
14941496
const runGatewayRestart =
14951497
ctx.deps?.runGatewayRestart ?? (() => runGatewayLifecycle("restart"));
1496-
await ctx.commit(runGatewayRestart);
1498+
const restarted = await ctx.commit(runGatewayRestart);
1499+
if (restarted === false) {
1500+
throw new Error("Gateway restart did not complete");
1501+
}
14971502
return { summary: "Restarted Gateway" };
14981503
},
14991504
});

0 commit comments

Comments
 (0)