Skip to content

Commit 1aa510d

Browse files
committed
fix: harden managed update handoff sentinels
1 parent 1556fc4 commit 1aa510d

7 files changed

Lines changed: 295 additions & 3 deletions

‎src/gateway/server-methods/update-managed-service-handoff.test.ts‎

Lines changed: 173 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,14 +80,20 @@ describe("managed service update handoff", () => {
8080
expect(result.status).toBe("started");
8181
expect(result.command).toBe("openclaw update --yes --timeout 1800");
8282
expect(spawnMock).toHaveBeenCalledTimes(1);
83-
const [execPath, args, options] = spawnMock.mock.calls[0] as [
83+
const [execPath, args, options] = spawnMock.mock.calls[0] as unknown as [
8484
string,
8585
string[],
8686
{ env: NodeJS.ProcessEnv; detached?: boolean; cwd?: string },
8787
];
8888
expect(execPath).toBe("/usr/local/bin/node");
8989
expect(args).toHaveLength(2);
9090
tempDirs.add(path.dirname(args[0] ?? result.logPath));
91+
const helperParams = JSON.parse(await fs.readFile(args[1] ?? "", "utf-8")) as {
92+
metaPath?: string;
93+
sentinelPath?: string;
94+
};
95+
expect(helperParams.metaPath).toMatch(/sentinel-meta\.json$/u);
96+
expect(helperParams.sentinelPath).toMatch(/restart-sentinel\.json$/u);
9197
expect(options.cwd).toBe("/tmp/openclaw");
9298
expect(options.detached).toBe(true);
9399
expect(options.env.KEEP_ME).toBe("1");
@@ -103,6 +109,172 @@ describe("managed service update handoff", () => {
103109
expect(options.env[CONTROL_PLANE_UPDATE_SENTINEL_META_ENV]).toMatch(/sentinel-meta\.json$/u);
104110
});
105111

112+
it("does not overwrite a restart sentinel owned by another startup task", async () => {
113+
const { execFile } =
114+
await vi.importActual<typeof import("node:child_process")>("node:child_process");
115+
const { startManagedServiceUpdateHandoff } =
116+
await import("./update-managed-service-handoff.js");
117+
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-handoff-helper-test-"));
118+
tempDirs.add(tmpDir);
119+
120+
await startManagedServiceUpdateHandoff({
121+
root: tmpDir,
122+
timeoutMs: 1_800_000,
123+
restartDelayMs: 500,
124+
parentPid: process.pid,
125+
execPath: "/usr/local/bin/node",
126+
argv1: "/opt/openclaw/openclaw.mjs",
127+
env: {},
128+
meta: {
129+
sessionKey: "agent:test:webchat:dm:user-123",
130+
continuationMessage: "continue after restart",
131+
},
132+
});
133+
134+
const [, args] = spawnMock.mock.calls.at(-1) as unknown as [
135+
string,
136+
string[],
137+
{ env: NodeJS.ProcessEnv; detached?: boolean; cwd?: string },
138+
];
139+
const helperScriptPath = args[0] ?? "";
140+
tempDirs.add(path.dirname(helperScriptPath));
141+
const helperParams = JSON.parse(await fs.readFile(args[1] ?? "", "utf-8")) as Record<
142+
string,
143+
unknown
144+
>;
145+
const sentinelPath = path.join(tmpDir, "restart-sentinel.json");
146+
const unrelatedSentinel = {
147+
version: 1,
148+
payload: {
149+
kind: "config",
150+
status: "skipped",
151+
message: "preserve this restart task",
152+
stats: { reason: "config-restart-pending" },
153+
},
154+
};
155+
await fs.writeFile(sentinelPath, `${JSON.stringify(unrelatedSentinel, null, 2)}\n`);
156+
const helperParamsPath = path.join(tmpDir, "helper-params.json");
157+
await fs.writeFile(
158+
helperParamsPath,
159+
`${JSON.stringify(
160+
{
161+
...helperParams,
162+
parentPid: process.pid,
163+
parentExitTimeoutMs: 1,
164+
sentinelPath,
165+
logPath: path.join(tmpDir, "handoff.log"),
166+
sensitivePaths: [],
167+
},
168+
null,
169+
2,
170+
)}\n`,
171+
);
172+
173+
const result = await new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(
174+
(resolve) => {
175+
execFile(process.execPath, [helperScriptPath, helperParamsPath], (err) => {
176+
const childError = err as (NodeJS.ErrnoException & { signal?: NodeJS.Signals }) | null;
177+
resolve({
178+
code: typeof childError?.code === "number" ? childError.code : 0,
179+
signal: childError?.signal ?? null,
180+
});
181+
});
182+
},
183+
);
184+
185+
expect(result).toEqual({ code: 1, signal: null });
186+
await expect(fs.readFile(sentinelPath, "utf-8").then(JSON.parse)).resolves.toEqual(
187+
unrelatedSentinel,
188+
);
189+
});
190+
191+
it("does not overwrite a newer pending update handoff sentinel", async () => {
192+
const { execFile } =
193+
await vi.importActual<typeof import("node:child_process")>("node:child_process");
194+
const { startManagedServiceUpdateHandoff } =
195+
await import("./update-managed-service-handoff.js");
196+
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-handoff-helper-test-"));
197+
tempDirs.add(tmpDir);
198+
199+
await startManagedServiceUpdateHandoff({
200+
root: tmpDir,
201+
timeoutMs: 1_800_000,
202+
restartDelayMs: 500,
203+
parentPid: process.pid,
204+
execPath: "/usr/local/bin/node",
205+
argv1: "/opt/openclaw/openclaw.mjs",
206+
handoffId: "old-handoff",
207+
env: {},
208+
meta: {
209+
handoffId: "old-handoff",
210+
sessionKey: "agent:test:webchat:dm:user-123",
211+
continuationMessage: "continue after restart",
212+
},
213+
});
214+
215+
const [, args] = spawnMock.mock.calls.at(-1) as unknown as [
216+
string,
217+
string[],
218+
{ env: NodeJS.ProcessEnv; detached?: boolean; cwd?: string },
219+
];
220+
const helperScriptPath = args[0] ?? "";
221+
tempDirs.add(path.dirname(helperScriptPath));
222+
const helperParams = JSON.parse(await fs.readFile(args[1] ?? "", "utf-8")) as Record<
223+
string,
224+
unknown
225+
>;
226+
const sentinelPath = path.join(tmpDir, "restart-sentinel.json");
227+
const newerSentinel = {
228+
version: 1,
229+
payload: {
230+
kind: "update",
231+
status: "skipped",
232+
message: "new handoff still pending",
233+
stats: {
234+
mode: "npm",
235+
handoffId: "newer-handoff",
236+
reason: "managed-service-handoff-started",
237+
steps: [],
238+
durationMs: 0,
239+
},
240+
},
241+
};
242+
await fs.writeFile(sentinelPath, `${JSON.stringify(newerSentinel, null, 2)}\n`);
243+
const helperParamsPath = path.join(tmpDir, "helper-params.json");
244+
await fs.writeFile(
245+
helperParamsPath,
246+
`${JSON.stringify(
247+
{
248+
...helperParams,
249+
parentPid: process.pid,
250+
parentExitTimeoutMs: 1,
251+
sentinelPath,
252+
logPath: path.join(tmpDir, "handoff.log"),
253+
sensitivePaths: [],
254+
},
255+
null,
256+
2,
257+
)}\n`,
258+
);
259+
260+
const result = await new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(
261+
(resolve) => {
262+
execFile(process.execPath, [helperScriptPath, helperParamsPath], (err) => {
263+
const childError = err as (NodeJS.ErrnoException & { signal?: NodeJS.Signals }) | null;
264+
resolve({
265+
code: typeof childError?.code === "number" ? childError.code : 0,
266+
signal: childError?.signal ?? null,
267+
});
268+
});
269+
},
270+
);
271+
272+
expect(result).toEqual({ code: 1, signal: null });
273+
await expect(fs.readFile(sentinelPath, "utf-8").then(JSON.parse)).resolves.toEqual(
274+
newerSentinel,
275+
);
276+
});
277+
106278
it("sweeps stale handoff temp directories while keeping fresh handoff logs", async () => {
107279
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-handoff-cleanup-test-"));
108280
tempDirs.add(tmpDir);

‎src/gateway/server-methods/update-managed-service-handoff.ts‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { spawn } from "node:child_process";
22
import fs from "node:fs/promises";
33
import os from "node:os";
44
import path from "node:path";
5+
import { resolveRestartSentinelPath } from "../../infra/restart-sentinel.js";
56
import { SUPERVISOR_HINT_ENV_VARS } from "../../infra/supervisor-markers.js";
67
import {
78
CONTROL_PLANE_UPDATE_SENTINEL_META_ENV,
@@ -61,13 +62,105 @@ function cleanupSensitiveFiles() {
6162
}
6263
}
6364
65+
function readJsonFile(filePath) {
66+
try {
67+
return JSON.parse(fs.readFileSync(filePath, "utf-8"));
68+
} catch {
69+
return null;
70+
}
71+
}
72+
73+
function writeJsonFile(filePath, value) {
74+
const dir = path.dirname(filePath);
75+
const tempPath = path.join(
76+
dir,
77+
"." + path.basename(filePath) + "." + process.pid + "." + Date.now() + ".tmp",
78+
);
79+
try {
80+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
81+
fs.writeFileSync(tempPath, JSON.stringify(value, null, 2) + "\n", { mode: 0o600 });
82+
fs.renameSync(tempPath, filePath);
83+
} catch (err) {
84+
appendLog("failed to write update sentinel failure: " + (err && err.stack ? err.stack : String(err)));
85+
try {
86+
fs.rmSync(tempPath, { force: true });
87+
} catch {
88+
// Best effort only.
89+
}
90+
}
91+
}
92+
93+
function isPendingUpdatePayload(payload) {
94+
const reason = payload && payload.stats && payload.stats.reason;
95+
return (
96+
payload &&
97+
payload.kind === "update" &&
98+
payload.status === "skipped" &&
99+
(reason === "managed-service-handoff-started" || reason === "restart-health-pending")
100+
);
101+
}
102+
103+
function buildFallbackFailurePayload(reason) {
104+
const metaFile = params.metaPath ? readJsonFile(params.metaPath) : null;
105+
const meta = metaFile && metaFile.version === 1 && metaFile.meta ? metaFile.meta : {};
106+
const payload = {
107+
kind: "update",
108+
status: "error",
109+
ts: Date.now(),
110+
message: typeof meta.note === "string" ? meta.note : null,
111+
stats: {
112+
mode: "unknown",
113+
...(typeof meta.handoffId === "string" && meta.handoffId.trim()
114+
? { handoffId: meta.handoffId }
115+
: {}),
116+
reason,
117+
steps: [],
118+
durationMs: 0,
119+
},
120+
};
121+
if (typeof meta.sessionKey === "string" && meta.sessionKey.trim()) {
122+
payload.sessionKey = meta.sessionKey;
123+
}
124+
if (meta.deliveryContext && typeof meta.deliveryContext === "object") {
125+
payload.deliveryContext = meta.deliveryContext;
126+
}
127+
if (typeof meta.threadId === "string" && meta.threadId.trim()) {
128+
payload.threadId = meta.threadId;
129+
}
130+
return payload;
131+
}
132+
133+
function markUpdateSentinelFailureIfPending(reason) {
134+
if (!params.sentinelPath) {
135+
return;
136+
}
137+
const current = readJsonFile(params.sentinelPath);
138+
let payload = current && current.version === 1 ? current.payload : null;
139+
if (payload && (payload.kind !== "update" || !isPendingUpdatePayload(payload))) {
140+
return;
141+
}
142+
const handoffId = typeof params.handoffId === "string" ? params.handoffId.trim() : "";
143+
if (payload && handoffId && (!payload.stats || payload.stats.handoffId !== handoffId)) {
144+
return;
145+
}
146+
if (payload) {
147+
payload = { ...payload, status: "error" };
148+
delete payload.continuation;
149+
payload.stats = { ...(payload.stats || {}), reason };
150+
} else {
151+
payload = buildFallbackFailurePayload(reason);
152+
}
153+
writeJsonFile(params.sentinelPath, { version: 1, payload });
154+
}
155+
64156
(async () => {
65157
const deadline = Date.now() + params.parentExitTimeoutMs;
66158
while (isPidAlive(params.parentPid) && Date.now() < deadline) {
67159
await sleep(250);
68160
}
69161
if (isPidAlive(params.parentPid)) {
70162
appendLog("gateway parent pid " + params.parentPid + " did not exit before handoff timeout");
163+
markUpdateSentinelFailureIfPending("managed-service-handoff-parent-timeout");
71164
cleanupSensitiveFiles();
72165
process.exitCode = 1;
73166
return;
@@ -90,6 +183,7 @@ function cleanupSensitiveFiles() {
90183
});
91184
if (exit && exit.error) {
92185
appendLog("managed update command failed to start: " + (exit.error && exit.error.stack ? exit.error.stack : String(exit.error)));
186+
markUpdateSentinelFailureIfPending("managed-service-handoff-spawn-failed");
93187
process.exitCode = 1;
94188
return;
95189
}
@@ -100,8 +194,10 @@ function cleanupSensitiveFiles() {
100194
(exit && exit.signal ? exit.signal : "null"),
101195
);
102196
if (exit && typeof exit.code === "number" && exit.code !== 0) {
197+
markUpdateSentinelFailureIfPending("managed-service-handoff-failed");
103198
process.exitCode = exit.code;
104199
} else if (exit && exit.signal) {
200+
markUpdateSentinelFailureIfPending("managed-service-handoff-failed");
105201
process.exitCode = 1;
106202
}
107203
} finally {
@@ -116,6 +212,7 @@ function cleanupSensitiveFiles() {
116212
}
117213
})().catch((err) => {
118214
appendLog("handoff failed: " + (err && err.stack ? err.stack : String(err)));
215+
markUpdateSentinelFailureIfPending("managed-service-handoff-helper-failed");
119216
cleanupSensitiveFiles();
120217
process.exitCode = 1;
121218
});
@@ -181,6 +278,7 @@ export async function startManagedServiceUpdateHandoff(params: {
181278
timeoutMs?: number;
182279
restartDelayMs?: number;
183280
meta: UpdateRestartSentinelMeta;
281+
handoffId?: string;
184282
env?: NodeJS.ProcessEnv;
185283
execPath?: string;
186284
argv1?: string;
@@ -207,7 +305,10 @@ export async function startManagedServiceUpdateHandoff(params: {
207305
cwd: params.root,
208306
commandArgv,
209307
commandLabel,
308+
handoffId: params.handoffId,
210309
logPath,
310+
metaPath,
311+
sentinelPath: resolveRestartSentinelPath(),
211312
sensitivePaths: [scriptPath, paramsPath, metaPath],
212313
};
213314

‎src/gateway/server-methods/update.test.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
DEFAULT_RESTART_SUCCESS_CONTINUATION_MESSAGE,
44
type RestartSentinelPayload,
55
} from "../../infra/restart-sentinel.js";
6+
import type { RespawnSupervisor } from "../../infra/supervisor-markers.js";
67
import type { UpdateInstallSurface, UpdateRunResult } from "../../infra/update-runner.js";
78

89
// Capture the sentinel payload written during update.run
@@ -19,7 +20,7 @@ const getLatestUpdateRestartSentinelMock = vi.fn<() => RestartSentinelPayload |
1920
const recordLatestUpdateRestartSentinelMock = vi.fn();
2021
const isRestartEnabledMock = vi.fn(() => true);
2122
const readPackageVersionMock = vi.fn(async () => "1.0.0");
22-
const detectRespawnSupervisorMock = vi.fn(() => null);
23+
const detectRespawnSupervisorMock = vi.fn<() => RespawnSupervisor | null>(() => null);
2324
const startManagedServiceUpdateHandoffMock = vi.fn(async () => ({
2425
status: "started" as const,
2526
pid: 12345,
@@ -365,9 +366,17 @@ describe("update.run restart scheduling", () => {
365366
expect(startManagedServiceUpdateHandoffMock).toHaveBeenCalledWith(
366367
expect.objectContaining({
367368
root: "/tmp/openclaw",
368-
meta: expect.any(Object),
369+
handoffId: expect.any(String),
370+
meta: expect.objectContaining({
371+
handoffId: expect.any(String),
372+
}),
369373
}),
370374
);
375+
const [handoffParams] = firstMockCall(
376+
startManagedServiceUpdateHandoffMock,
377+
"managed handoff",
378+
) as [{ handoffId?: string; meta?: { handoffId?: string } }];
379+
expect(handoffParams.meta?.handoffId).toBe(handoffParams.handoffId);
371380
expect(scheduleGatewaySigusr1RestartMock).toHaveBeenCalledTimes(1);
372381
const [restartParams] = firstMockCall(
373382
scheduleGatewaySigusr1RestartMock,
@@ -392,6 +401,7 @@ describe("update.run restart scheduling", () => {
392401
expect(sentinel.status).toBe("skipped");
393402
expect(sentinel.stats).toEqual(
394403
expect.objectContaining({
404+
handoffId: handoffParams.handoffId,
395405
reason: "managed-service-handoff-started",
396406
}),
397407
);

0 commit comments

Comments
 (0)