Skip to content

Commit 9c8393f

Browse files
steipeteampagent
andauthored
fix(cron): bind task recovery to exact receipt (#127003)
Preserve receipt-less legacy matching, but fail closed when an active receipt has only an ambiguous pre-upgrade task identity. Amp-Thread-ID: https://ampcode.com/threads/T-01a0220e-6236-745d-8b14-759d26595b12 Co-authored-by: Amp <[email protected]>
1 parent 9b3445d commit 9c8393f

6 files changed

Lines changed: 203 additions & 39 deletions

File tree

‎src/cron/service/ops-run-preparation.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -509,7 +509,8 @@ export async function activatePreparedManualRun(
509509
state,
510510
job: activatedJob,
511511
startedAt,
512-
publicRunId: prepared.runId ?? activation.runReceipt.receiptId,
512+
runReceipt: activation.runReceipt,
513+
publicRunId: prepared.runId,
513514
});
514515
const taskRunId = taskRun?.runId;
515516
const activeJobMarker = markManualCronJobActive(state, job);

‎src/cron/service/ops.test.ts‎

Lines changed: 75 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1065,10 +1065,14 @@ describe("cron service ops seam coverage", () => {
10651065
});
10661066

10671067
it.each([
1068-
{ identity: "canonical", reservationOffsetMs: undefined },
1069-
{ identity: "shipped reservation-keyed", reservationOffsetMs: 250 },
1068+
{ outcome: "restores", identity: "canonical receipt-keyed", reservationOffsetMs: undefined },
1069+
{
1070+
outcome: "fails closed for",
1071+
identity: "pre-upgrade reservation-keyed",
1072+
reservationOffsetMs: 250,
1073+
},
10701074
])(
1071-
"preserves a finalized $identity task run when startup finds its stale marker",
1075+
"$outcome a finalized $identity task run when startup finds its stale marker",
10721076
async ({ reservationOffsetMs }) => {
10731077
const { storePath } = await makeStorePath();
10741078
const now = Date.parse("2026-03-23T12:00:00.000Z");
@@ -1109,7 +1113,8 @@ describe("cron service ops seam coverage", () => {
11091113
});
11101114
const taskRunId =
11111115
reservationOffsetMs === undefined
1112-
? taskRuns.tryCreateCronTaskRunHandle({ state, job, startedAt })?.runId
1116+
? taskRuns.tryCreateCronTaskRunHandle({ state, job, startedAt, runReceipt: receipt })
1117+
?.runId
11131118
: taskExecutor.createRunningTaskRunCore({
11141119
runtime: "cron",
11151120
sourceId: job.id,
@@ -1164,6 +1169,37 @@ describe("cron service ops seam coverage", () => {
11641169
},
11651170
});
11661171
const persisted = await loadCronStore(storePath);
1172+
const receiptRow = runOpenClawStateWriteTransaction(({ db }) =>
1173+
db
1174+
.prepare(
1175+
"SELECT status, finished_at_ms AS finishedAtMs, error_text AS error FROM cron_run_receipts WHERE receipt_id = ?",
1176+
)
1177+
.get(receipt.receiptId),
1178+
) as { status: string; finishedAtMs: number; error: string | null };
1179+
if (reservationOffsetMs !== undefined) {
1180+
expect(persisted.jobs[0]?.state).toMatchObject({
1181+
lastRunAtMs: startedAt,
1182+
lastRunStatus: "error",
1183+
lastStatus: "error",
1184+
lastError: "cron: job interrupted by gateway restart",
1185+
triggerState: { cursor: "old" },
1186+
});
1187+
expect(persisted.jobs[0]?.state.runningAtMs).toBeUndefined();
1188+
expect(receiptRow).toEqual({
1189+
status: "interrupted",
1190+
finishedAtMs: now,
1191+
error: "cron: job interrupted by owner process exit",
1192+
});
1193+
expect(events.filter((event) => event.action === "finished")).toEqual([
1194+
expect.objectContaining({
1195+
jobId: job.id,
1196+
status: "error",
1197+
error: "cron: job interrupted by gateway restart",
1198+
}),
1199+
]);
1200+
stop(state);
1201+
return;
1202+
}
11671203
expect(persisted.jobs[0]).toMatchObject({
11681204
enabled: false,
11691205
state: {
@@ -1181,13 +1217,6 @@ describe("cron service ops seam coverage", () => {
11811217
expect(persisted.jobs[0]?.state.runningAtMs).toBeUndefined();
11821218
expect(persisted.jobs[0]?.state.lastError).toBeUndefined();
11831219
expect(persisted.jobs[0]?.state.nextRunAtMs).toBeUndefined();
1184-
const receiptRow = runOpenClawStateWriteTransaction(({ db }) =>
1185-
db
1186-
.prepare(
1187-
"SELECT status, finished_at_ms AS finishedAtMs, error_text AS error FROM cron_run_receipts WHERE receipt_id = ?",
1188-
)
1189-
.get(receipt.receiptId),
1190-
) as { status: string; finishedAtMs: number; error: string | null };
11911220
expect(receiptRow).toEqual({ status: "ok", finishedAtMs: endedAt, error: null });
11921221
expect(events.filter((event) => event.action === "finished")).toEqual([]);
11931222
stop(state);
@@ -1227,7 +1256,12 @@ describe("cron service ops seam coverage", () => {
12271256
requestHeartbeat: vi.fn(),
12281257
runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" as const })),
12291258
});
1230-
const taskRunId = taskRuns.tryCreateCronTaskRunHandle({ state, job, startedAt })?.runId;
1259+
const taskRunId = taskRuns.tryCreateCronTaskRunHandle({
1260+
state,
1261+
job,
1262+
startedAt,
1263+
runReceipt: receipt,
1264+
})?.runId;
12311265
if (!taskRunId) {
12321266
throw new Error("expected invalid finalized cron task run");
12331267
}
@@ -1599,8 +1633,14 @@ describe("cron service ops seam coverage", () => {
15991633
ran: true,
16001634
});
16011635

1636+
const receipt = openOpenClawStateDatabase()
1637+
.db.prepare(
1638+
"SELECT receipt_id AS receiptId FROM cron_run_receipts WHERE store_key = ? AND job_id = ? ORDER BY started_at_ms DESC, receipt_id DESC LIMIT 1",
1639+
)
1640+
.get(cronStoreKey(storePath), "isolated-timeout") as { receiptId: string };
1641+
const taskRunId = `cron:isolated-timeout:${now}:${receipt.receiptId}:${manualRunId}`;
16021642
expectTaskRun({
1603-
runId: `cron:isolated-timeout:${now}:${manualRunId}`,
1643+
runId: taskRunId,
16041644
runtime: "cron",
16051645
status: "succeeded",
16061646
sourceId: "isolated-timeout",
@@ -1763,20 +1803,32 @@ describe("cron service ops seam coverage", () => {
17631803
jobs: [createDueIsolatedJob(now)],
17641804
});
17651805

1806+
const createTaskRecord = taskExecutor.createRunningTaskRunCore;
17661807
const createTaskRecordSpy = vi
17671808
.spyOn(taskExecutor, "createRunningTaskRunCore")
1768-
.mockImplementation(() => {
1809+
.mockImplementationOnce(() => {
17691810
throw new Error("disk full");
1770-
});
1771-
1772-
await expectDueIsolatedManualRunProgresses(storePath, now);
1773-
expectWarnedJob({
1774-
field: "jobId",
1775-
value: "isolated-timeout",
1776-
message: "cron: failed to create task ledger record",
1777-
});
1811+
})
1812+
.mockImplementation((params) => createTaskRecord(params));
17781813

1779-
createTaskRecordSpy.mockRestore();
1814+
try {
1815+
await expectDueIsolatedManualRunProgresses(storePath, now);
1816+
expectWarnedJob({
1817+
field: "jobId",
1818+
value: "isolated-timeout",
1819+
message: "cron: failed to create task ledger record",
1820+
});
1821+
const receipt = openOpenClawStateDatabase()
1822+
.db.prepare(
1823+
"SELECT receipt_id AS receiptId FROM cron_run_receipts WHERE store_key = ? AND job_id = ? ORDER BY started_at_ms DESC, receipt_id DESC LIMIT 1",
1824+
)
1825+
.get(cronStoreKey(storePath), "isolated-timeout") as { receiptId: string };
1826+
expect(findTaskByRunId(`cron:isolated-timeout:${now}:${receipt.receiptId}`)).toMatchObject({
1827+
status: "succeeded",
1828+
});
1829+
} finally {
1830+
createTaskRecordSpy.mockRestore();
1831+
}
17801832
});
17811833

17821834
it("keeps manual cron cleanup progressing when task ledger updates fail", async () => {

‎src/cron/service/run-admission.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -576,7 +576,7 @@ export async function executeQueuedCronRun(params: {
576576
state,
577577
job: executionJob,
578578
startedAt: started.startedAt,
579-
publicRunId: started.runReceipt.receiptId,
579+
runReceipt: started.runReceipt,
580580
});
581581
const taskRunId = taskRun?.runId;
582582
const activeJobMarker = markCronJobActive(executionJob.id, {

‎src/cron/service/run-recovery.test.ts‎

Lines changed: 84 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,11 @@ import type { CronJob } from "../types.js";
1515
import { proposeCronRunRecovery, recoverCronRunProposal } from "./run-recovery.js";
1616
import { createCronServiceState } from "./state.js";
1717
import { runPostPersistCronNotifications } from "./store.js";
18-
import { tryCreateCronTaskRunHandle, tryFinishCronTaskRunWithoutHistory } from "./task-runs.js";
18+
import {
19+
tryCreateCronTaskRunHandle,
20+
tryFinishCronTaskRun,
21+
tryFinishCronTaskRunWithoutHistory,
22+
} from "./task-runs.js";
1923

2024
function tryCreateCronTaskRun(
2125
params: Parameters<typeof tryCreateCronTaskRunHandle>[0],
@@ -262,7 +266,7 @@ describe("atomic cron run recovery", () => {
262266
state,
263267
job,
264268
startedAt: startedAtMs,
265-
publicRunId: receipt.receiptId,
269+
runReceipt: receipt,
266270
});
267271
tryFinishCronTaskRunWithoutHistory(state, {
268272
taskRunId,
@@ -285,6 +289,84 @@ describe("atomic cron run recovery", () => {
285289
expect(receiptRow.status).toBe("skipped");
286290
});
287291

292+
it("does not restore a prior same-millisecond task for a different receipt", async () => {
293+
const { storePath } = await makeStorePath();
294+
const startedAtMs = Date.parse("2026-08-13T10:50:00.000Z");
295+
const job = makeJob("same-millisecond-task-recovery", startedAtMs);
296+
await writeCronStoreSnapshot({ storePath, jobs: [job] });
297+
const state = makeState(storePath, startedAtMs + 30_000);
298+
const priorReceipt = claimReceipt(storePath, job, startedAtMs);
299+
const priorTaskRunId = tryCreateCronTaskRun({
300+
state,
301+
job,
302+
startedAt: startedAtMs,
303+
runReceipt: priorReceipt,
304+
});
305+
tryFinishCronTaskRun(state, {
306+
taskRunId: priorTaskRunId,
307+
job,
308+
event: {
309+
jobId: job.id,
310+
action: "finished",
311+
job,
312+
status: "ok",
313+
summary: "prior receipt completed",
314+
runAtMs: startedAtMs,
315+
durationMs: 1,
316+
},
317+
});
318+
finishCronRunReceipt({
319+
handle: priorReceipt,
320+
status: "ok",
321+
finishedAtMs: startedAtMs + 1,
322+
});
323+
const receipt = claimReceipt(storePath, job, startedAtMs);
324+
const proposal = proposeCronRunRecovery(state, job.id, undefined, startedAtMs);
325+
releaseLocalCronRunReceiptOwnership(receipt);
326+
327+
expect(recoverCronRunProposal(state, proposal)).toMatchObject({ kind: "repaired" });
328+
expect((await loadCronStore(storePath)).jobs[0]?.state).toMatchObject({
329+
lastRunStatus: "error",
330+
lastError: expect.stringContaining("interrupted by gateway restart"),
331+
});
332+
});
333+
334+
it("fails closed for a legacy caller-ID task without exact receipt identity", async () => {
335+
const { storePath } = await makeStorePath();
336+
const startedAtMs = Date.parse("2026-08-13T10:55:00.000Z");
337+
const job = makeJob("legacy-manual-task-recovery", startedAtMs);
338+
await writeCronStoreSnapshot({ storePath, jobs: [job] });
339+
const state = makeState(storePath, startedAtMs + 30_000);
340+
const receipt = claimReceipt(storePath, job, startedAtMs);
341+
const taskRunId = tryCreateCronTaskRun({
342+
state,
343+
job,
344+
startedAt: startedAtMs,
345+
publicRunId: "manual:legacy-manual-task-recovery:1",
346+
});
347+
tryFinishCronTaskRun(state, {
348+
taskRunId,
349+
job,
350+
event: {
351+
jobId: job.id,
352+
action: "finished",
353+
job,
354+
status: "ok",
355+
runId: "manual:legacy-manual-task-recovery:1",
356+
runAtMs: startedAtMs,
357+
durationMs: 1,
358+
},
359+
});
360+
const proposal = proposeCronRunRecovery(state, job.id, undefined, startedAtMs);
361+
releaseLocalCronRunReceiptOwnership(receipt);
362+
363+
expect(recoverCronRunProposal(state, proposal)).toMatchObject({ kind: "repaired" });
364+
expect((await loadCronStore(storePath)).jobs[0]?.state).toMatchObject({
365+
lastRunStatus: "error",
366+
lastError: expect.stringContaining("interrupted by gateway restart"),
367+
});
368+
});
369+
288370
it("retires a dead owner receipt after timeout state already finalized", async () => {
289371
const { storePath } = await makeStorePath();
290372
const startedAtMs = Date.parse("2026-08-13T11:00:00.000Z");

‎src/cron/service/run-recovery.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@ function repairInDatabase(params: {
143143
jobId: proposal.jobId,
144144
startedAt: proposal.runningAtMs,
145145
storeKey,
146+
receiptId: proposal.receipt?.receiptId,
146147
});
147148
const finalized = task.finalized;
148149
const restored = finalized

‎src/cron/service/task-runs.ts‎

Lines changed: 40 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -140,37 +140,63 @@ export function tryCreateCronTaskRunHandle(params: {
140140
state: CronServiceState;
141141
job: CronJob;
142142
startedAt: number;
143+
runReceipt?: CronRunReceiptHandle;
143144
publicRunId?: string;
144-
}): { runId: string; taskId: string; flowId?: string } | undefined {
145-
const runId = createCronTaskRunId(params.job.id, params.startedAt, params.publicRunId);
146-
return tryCreateCronTaskRunRecord({
147-
state: params.state,
148-
job: params.job,
149-
jobId: params.job.id,
150-
startedAt: params.startedAt,
151-
runId,
152-
});
145+
}): { runId: string; taskId?: string; flowId?: string } {
146+
const runId = createCronTaskRunId(
147+
params.job.id,
148+
params.startedAt,
149+
params.runReceipt?.receiptId,
150+
params.publicRunId,
151+
);
152+
return (
153+
tryCreateCronTaskRunRecord({
154+
state: params.state,
155+
job: params.job,
156+
jobId: params.job.id,
157+
startedAt: params.startedAt,
158+
runId,
159+
}) ?? { runId }
160+
);
153161
}
154162

155-
function createCronTaskRunId(jobId: string, startedAt: number, publicRunId?: string): string {
156-
const discriminator = publicRunId?.trim() || randomUUID();
157-
return `${createCronExecutionId(jobId, startedAt)}:${discriminator}`;
163+
function createCronTaskRunId(
164+
jobId: string,
165+
startedAt: number,
166+
receiptId?: string,
167+
publicRunId?: string,
168+
): string {
169+
const receipt = receiptId?.trim();
170+
const publicId = publicRunId?.trim();
171+
const discriminator = receipt || publicId || randomUUID();
172+
const publicSuffix = publicId && publicId !== discriminator ? `:${publicId}` : "";
173+
return `${createCronExecutionId(jobId, startedAt)}:${discriminator}${publicSuffix}`;
158174
}
159175

160176
function findLatestCronTaskRunForRecoveryFromRecords(
161177
records: readonly TaskRecord[],
162178
jobId: string,
163179
startedAt: number,
164180
storeKey: string,
181+
receiptId?: string,
165182
): TaskRecord | undefined {
166183
const executionRunId = createCronExecutionId(jobId, startedAt);
167184
const prefix = `${executionRunId}:`;
185+
const receiptRunId = receiptId ? `${prefix}${receiptId}` : undefined;
168186
return records
169187
.filter((task) => {
170188
if (task.runtime !== "cron" || task.sourceId !== jobId) {
171189
return false;
172190
}
173191
const taskStoreKey = cronTaskRecordStoreKey(task);
192+
if (receiptRunId) {
193+
// Receipt recovery accepts only its owner-native identity; legacy rows
194+
// without that receipt prefix are ambiguous when runs share a millisecond.
195+
return (
196+
taskStoreKey === storeKey &&
197+
(task.runId === receiptRunId || task.runId?.startsWith(`${receiptRunId}:`))
198+
);
199+
}
174200
if (taskStoreKey === undefined) {
175201
// Exact match covers detail-less pre-discriminator rows from older releases.
176202
return task.runId === executionRunId;
@@ -240,12 +266,14 @@ export function findCronTaskRunRecoveryInDatabase(params: {
240266
jobId: string;
241267
startedAt: number;
242268
storeKey: string;
269+
receiptId?: string;
243270
}): { taskRunId?: string; finalized?: FinalizedCronTaskRun } {
244271
const task = findLatestCronTaskRunForRecoveryFromRecords(
245272
listTaskRecordsByRuntimeSourceIdInDatabase(params.database, "cron", params.jobId),
246273
params.jobId,
247274
params.startedAt,
248275
params.storeKey,
276+
params.receiptId,
249277
);
250278
const finalized = finalizedCronTaskRun(task, params.jobId);
251279
return {

0 commit comments

Comments
 (0)