Skip to content

Commit 3f3e59b

Browse files
fix(cron): defer auto-disable notifications until persistence (#118384)
* fix(cron): defer auto-disable notifications until persistence * fix(cron): emit disable notifications only after durable roster commits --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent f9df87c commit 3f3e59b

7 files changed

Lines changed: 196 additions & 32 deletions

File tree

‎src/cron/service/jobs-scheduling.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -535,6 +535,7 @@ function recomputeJobNextRunAtMs(params: {
535535
job: CronJob;
536536
nowMs: number;
537537
deferredNotifications?: DeferredCronNotifications;
538+
skipScheduleErrorHandling?: boolean;
538539
}) {
539540
let changed = false;
540541
try {
@@ -562,6 +563,9 @@ function recomputeJobNextRunAtMs(params: {
562563
changed = true;
563564
}
564565
} catch (err) {
566+
if (params.skipScheduleErrorHandling) {
567+
return false;
568+
}
565569
if (
566570
recordScheduleComputeError({
567571
state: params.state,
@@ -611,6 +615,7 @@ export function recomputeNextRunsForMaintenance(
611615
repairFutureCronNextRunAtMs?: boolean;
612616
preserveExpiredPacedNextRunJobId?: string;
613617
deferredNotifications?: DeferredCronNotifications;
618+
skipScheduleErrorHandling?: boolean;
614619
},
615620
): boolean {
616621
const recomputeExpired = opts?.recomputeExpired ?? false;
@@ -621,6 +626,7 @@ export function recomputeNextRunsForMaintenance(
621626
job,
622627
nowMs,
623628
deferredNotifications: opts?.deferredNotifications,
629+
skipScheduleErrorHandling: opts?.skipScheduleErrorHandling,
624630
});
625631
return walkSchedulableJobs(
626632
state,

‎src/cron/service/ops-mutations.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -504,13 +504,19 @@ export async function removeAgentJobsTransactional<T>(
504504
state.store.jobs = state.store.jobs.filter(
505505
(job) => resolveEffectiveJobAgentId(job, defaultAgentId) !== id,
506506
);
507-
recomputeNextRunsForMaintenance(state);
507+
const postPersistNotifications: DeferredCronNotifications = [];
508+
recomputeNextRunsForMaintenance(state, { deferredNotifications: postPersistNotifications });
509+
// Cron is durable first, but notifications stay speculative until the roster commits.
508510
await persistOrRestore(state, snapshot);
509511
let result: T;
510512
try {
511513
result = await commit();
512514
} catch (error) {
513515
if (error instanceof AgentDeletionCommitUncertainError) {
516+
// Uncertain roster writes intentionally keep the cron deletion durable.
517+
for (const notify of postPersistNotifications) {
518+
notify();
519+
}
514520
armTimer(state);
515521
for (const job of removedJobs) {
516522
noteActiveCronJobRemoval(job.id);
@@ -534,6 +540,9 @@ export async function removeAgentJobsTransactional<T>(
534540
}
535541
throw error;
536542
}
543+
for (const notify of postPersistNotifications) {
544+
notify();
545+
}
537546
for (const job of removedJobs) {
538547
noteActiveCronJobRemoval(job.id);
539548
try {

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

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,15 @@ async function skipInvalidPersistedManualRun(params: {
207207
armTimer(params.state);
208208
}
209209

210+
function recomputeManualRunPreflight(state: CronServiceState, id: string, mode?: "due" | "force") {
211+
// Preflight is advisory and may be called by read-shaped queue checks. Do not
212+
// let a schedule error turn that check into an auto-disable transition.
213+
return recomputeNextRunsForMaintenance(state, {
214+
...(mode === "force" ? { preserveExpiredPacedNextRunJobId: id } : {}),
215+
skipScheduleErrorHandling: true,
216+
});
217+
}
218+
210219
async function inspectManualRunPreflight(
211220
state: CronServiceState,
212221
id: string,
@@ -228,10 +237,7 @@ async function inspectManualRunPreflight(
228237
// Normalize job tick state (clears stale runningAtMs markers) before
229238
// checking if already running, so a stale marker from a crashed Phase-1
230239
// persist does not block manual triggers for up to STUCK_RUN_MS (#17554).
231-
recomputeNextRunsForMaintenance(
232-
state,
233-
mode === "force" ? { preserveExpiredPacedNextRunJobId: id } : undefined,
234-
);
240+
recomputeManualRunPreflight(state, id, mode);
235241
const job = findJobOrThrow(state, id);
236242
if (!admitsStreamSourceRun(job, streamScheduleKey, streamSourceIdentity)) {
237243
return { ok: true, ran: false, reason: "not-due" } as const;
@@ -308,10 +314,7 @@ export async function prepareManualRun(
308314
// The initial preflight is advisory. A command-lane wait or another cron
309315
// run can change this job before its reservation is persisted.
310316
await ensureLoaded(state, { skipRecompute: true });
311-
recomputeNextRunsForMaintenance(
312-
state,
313-
mode === "force" ? { preserveExpiredPacedNextRunJobId: id } : undefined,
314-
);
317+
recomputeManualRunPreflight(state, id, mode);
315318
const job = findJobOrThrow(state, id);
316319
if (!admitsStreamSourceRun(job, opts?.streamScheduleKey, opts?.streamSourceIdentity)) {
317320
return { ok: true, ran: false, reason: "not-due" as const };

‎src/cron/service/ops-shared.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ import { cronStreamScheduleKey } from "../stream-schedule.js";
55
import type { CronJob } from "../types.js";
66
import { recomputeNextRunsForMaintenance } from "./jobs.js";
77
import { normalizeOptionalAgentId } from "./normalize.js";
8-
import type { CronServiceState } from "./state.js";
9-
import { ensureLoaded, persist } from "./store.js";
8+
import type { CronServiceState, DeferredCronNotifications } from "./state.js";
9+
import { ensureLoaded, persistOrRestore, snapshotStoreForRollback } from "./store.js";
1010
import {
1111
type IsolatedAgentSetupTimeoutSignal,
1212
maybeNotifyIsolatedAgentSetupTimeout,
@@ -74,9 +74,13 @@ export async function ensureLoadedForRead(state: CronServiceState) {
7474
}
7575
// Use the maintenance-only version so that read-only operations never
7676
// advance a past-due nextRunAtMs without executing the job (#16156).
77-
const changed = recomputeNextRunsForMaintenance(state);
77+
const rollbackSnapshot = snapshotStoreForRollback(state);
78+
const postPersistNotifications: DeferredCronNotifications = [];
79+
const changed = recomputeNextRunsForMaintenance(state, {
80+
deferredNotifications: postPersistNotifications,
81+
});
7882
if (changed) {
79-
await persist(state);
83+
await persistOrRestore(state, rollbackSnapshot, { postPersistNotifications });
8084
}
8185
}
8286

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

Lines changed: 116 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import fs from "node:fs/promises";
33
import path from "node:path";
44
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import { AgentDeletionCommitUncertainError } from "../../agents/agent-lifecycle-registry.js";
56
import { runOpenClawStateWriteTransaction } from "../../state/openclaw-state-db.js";
67
import * as taskExecutor from "../../tasks/task-executor.js";
78
import { findTaskByRunId, listTaskRecordsUnsorted } from "../../tasks/task-registry.js";
@@ -16,8 +17,15 @@ import { loadCronJobsStoreWithConfigJobs, loadCronStore } from "../store.js";
1617
import { cronStoreKey } from "../store/key.js";
1718
import type { CronJob } from "../types.js";
1819
import { start, stop } from "./ops-lifecycle.js";
19-
import { add, remove, removeStaleJobFamily, update } from "./ops-mutations.js";
20+
import {
21+
add,
22+
remove,
23+
removeAgentJobsTransactional,
24+
removeStaleJobFamily,
25+
update,
26+
} from "./ops-mutations.js";
2027
import { list } from "./ops-read.js";
28+
import { inspectManualRunDisposition } from "./ops-run-preparation.js";
2129
import { run } from "./ops-run.js";
2230
import { createCronServiceState, type CronEvent } from "./state.js";
2331
import { tryCreateCronTaskRun, tryFinishCronTaskRun } from "./task-runs.js";
@@ -1738,5 +1746,112 @@ describe("cron service ops persist rollback", () => {
17381746
expect(enqueueSystemEvent).toHaveBeenCalledTimes(1);
17391747
expect(requestHeartbeat).toHaveBeenCalledTimes(1);
17401748
});
1749+
1750+
it.each(["failed", "committed", "uncertain"] as const)(
1751+
"publishes agent-removal auto-disable notifications only after a %s roster outcome",
1752+
async (outcome) => {
1753+
const { storePath } = await makeStorePath();
1754+
const now = Date.parse("2026-06-09T00:00:00.000Z");
1755+
const state = createOkIsolatedCronState({ storePath, now });
1756+
const removed = await add(state, {
1757+
...makeCreateInput("deleted agent job"),
1758+
agentId: "doomed",
1759+
});
1760+
const malformed = await add(state, {
1761+
...makeCreateInput("malformed surviving job"),
1762+
agentId: "survivor",
1763+
schedule: { kind: "cron", expr: "0 1 * * *" },
1764+
});
1765+
if (state.timer) {
1766+
clearTimeout(state.timer);
1767+
}
1768+
malformed.state.nextRunAtMs = undefined;
1769+
malformed.state.scheduleErrorCount = 2;
1770+
const enqueueSystemEvent = vi.mocked(state.deps.enqueueSystemEvent);
1771+
const requestHeartbeat = vi.mocked(state.deps.requestHeartbeat);
1772+
enqueueSystemEvent.mockClear();
1773+
requestHeartbeat.mockClear();
1774+
const computeNextRunAtMs = cronSchedule.computeNextRunAtMs;
1775+
vi.spyOn(cronSchedule, "computeNextRunAtMs").mockImplementation((schedule, nowMs) => {
1776+
if (schedule.kind === "cron" && schedule.expr === "0 1 * * *") {
1777+
throw new Error("simulated schedule failure");
1778+
}
1779+
return computeNextRunAtMs(schedule, nowMs);
1780+
});
1781+
1782+
const commit = vi.fn(async () => {
1783+
expect(enqueueSystemEvent).not.toHaveBeenCalled();
1784+
expect(requestHeartbeat).not.toHaveBeenCalled();
1785+
const persisted = await loadCronStore(storePath);
1786+
expect(persisted.jobs.find((job) => job.id === removed.id)).toBeUndefined();
1787+
expect(persisted.jobs.find((job) => job.id === malformed.id)?.enabled).toBe(false);
1788+
if (outcome === "failed") {
1789+
throw new Error("roster commit failed");
1790+
}
1791+
if (outcome === "uncertain") {
1792+
throw new AgentDeletionCommitUncertainError(new Error("roster commit uncertain"));
1793+
}
1794+
return "roster committed";
1795+
});
1796+
const transaction = removeAgentJobsTransactional(state, "doomed", commit);
1797+
if (outcome === "committed") {
1798+
await expect(transaction).resolves.toBe("roster committed");
1799+
} else if (outcome === "uncertain") {
1800+
await expect(transaction).rejects.toBeInstanceOf(AgentDeletionCommitUncertainError);
1801+
} else {
1802+
await expect(transaction).rejects.toThrow("roster commit failed");
1803+
}
1804+
if (state.timer) {
1805+
clearTimeout(state.timer);
1806+
}
1807+
1808+
const rolledBack = outcome === "failed";
1809+
const notificationCount = rolledBack ? 0 : 1;
1810+
expect(commit).toHaveBeenCalledOnce();
1811+
expect(enqueueSystemEvent).toHaveBeenCalledTimes(notificationCount);
1812+
expect(requestHeartbeat).toHaveBeenCalledTimes(notificationCount);
1813+
expect(state.store?.jobs.some((job) => job.id === removed.id)).toBe(rolledBack);
1814+
expect(state.store?.jobs.find((job) => job.id === malformed.id)?.enabled).toBe(rolledBack);
1815+
const persisted = await loadCronStore(storePath);
1816+
expect(persisted.jobs.some((job) => job.id === removed.id)).toBe(rolledBack);
1817+
expect(persisted.jobs.find((job) => job.id === malformed.id)?.enabled).toBe(rolledBack);
1818+
},
1819+
);
1820+
1821+
it("does not auto-disable a job during manual-run preflight", async () => {
1822+
const { storePath } = await makeStorePath();
1823+
const now = Date.parse("2026-06-09T00:00:00.000Z");
1824+
const state = createOkIsolatedCronState({ storePath, now });
1825+
const job = await add(state, {
1826+
...makeCreateInput("preflight schedule failure"),
1827+
schedule: { kind: "cron", expr: "0 1 * * *" },
1828+
});
1829+
if (state.timer) {
1830+
clearTimeout(state.timer);
1831+
}
1832+
job.state.nextRunAtMs = undefined;
1833+
job.state.scheduleErrorCount = 2;
1834+
const enqueueSystemEvent = vi.mocked(state.deps.enqueueSystemEvent);
1835+
const requestHeartbeat = vi.mocked(state.deps.requestHeartbeat);
1836+
enqueueSystemEvent.mockClear();
1837+
requestHeartbeat.mockClear();
1838+
const computeSpy = vi.spyOn(cronSchedule, "computeNextRunAtMs").mockImplementation(() => {
1839+
throw new Error("simulated preflight schedule failure");
1840+
});
1841+
1842+
try {
1843+
await expect(inspectManualRunDisposition(state, job.id)).resolves.toEqual({
1844+
ok: true,
1845+
ran: false,
1846+
reason: "not-due",
1847+
});
1848+
expect(job.enabled).toBe(true);
1849+
expect(job.state.scheduleErrorCount).toBe(2);
1850+
expect(enqueueSystemEvent).not.toHaveBeenCalled();
1851+
expect(requestHeartbeat).not.toHaveBeenCalled();
1852+
} finally {
1853+
computeSpy.mockRestore();
1854+
}
1855+
});
17411856
});
17421857
/* oxlint-disable max-lines -- TODO: split this grandfathered oversized file. */

‎src/cron/service/timer-catchup.ts‎

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import {
1515
runWithCronAdmission,
1616
updateQueuedCronRunReservationMarker,
1717
} from "./run-admission.js";
18-
import { type CronServiceState, emit } from "./state.js";
18+
import { type CronServiceState, type DeferredCronNotifications, emit } from "./state.js";
1919
import { ensureLoaded, persist, persistOrRestore, snapshotStoreForRollback } from "./store.js";
2020
import { tryCreateCronTaskRun } from "./task-runs.js";
2121
import {
@@ -88,8 +88,12 @@ async function releaseStartupCatchupReservationsAfterFailure(
8888
if (pendingReleases.length === 0) {
8989
return;
9090
}
91-
recomputeNextRunsForMaintenance(state, { repairFutureCronNextRunAtMs: false });
92-
await persistOrRestore(state, rollbackSnapshot);
91+
const postPersistNotifications: DeferredCronNotifications = [];
92+
recomputeNextRunsForMaintenance(state, {
93+
repairFutureCronNextRunAtMs: false,
94+
deferredNotifications: postPersistNotifications,
95+
});
96+
await persistOrRestore(state, rollbackSnapshot, { postPersistNotifications });
9397
for (const pending of pendingReleases) {
9498
releaseQueuedCronRun(state, pending.jobId, pending.reservationIdentity);
9599
}
@@ -309,8 +313,12 @@ async function executeStartupCatchupPlan(
309313
) {
310314
const rollbackSnapshot = snapshotStoreForRollback(state);
311315
delete job.state.queuedAtMs;
312-
recomputeNextRunsForMaintenance(state, { repairFutureCronNextRunAtMs: false });
313-
await persistOrRestore(state, rollbackSnapshot);
316+
const postPersistNotifications: DeferredCronNotifications = [];
317+
recomputeNextRunsForMaintenance(state, {
318+
repairFutureCronNextRunAtMs: false,
319+
deferredNotifications: postPersistNotifications,
320+
});
321+
await persistOrRestore(state, rollbackSnapshot, { postPersistNotifications });
314322
releaseQueuedCronRun(state, candidate.jobId, candidate.reservationIdentity);
315323
return undefined;
316324
}
@@ -437,8 +445,12 @@ async function applyStartupCatchupOutcomes(
437445
const rollbackSnapshot = snapshotStoreForRollback(state);
438446
const pendingReleases = clearUnstartedStartupCatchupReservationMarkers(state, plan, outcomes);
439447
if (pendingReleases.length > 0) {
440-
recomputeNextRunsForMaintenance(state, { repairFutureCronNextRunAtMs: false });
441-
await persistOrRestore(state, rollbackSnapshot);
448+
const postPersistNotifications: DeferredCronNotifications = [];
449+
recomputeNextRunsForMaintenance(state, {
450+
repairFutureCronNextRunAtMs: false,
451+
deferredNotifications: postPersistNotifications,
452+
});
453+
await persistOrRestore(state, rollbackSnapshot, { postPersistNotifications });
442454
for (const pending of pendingReleases) {
443455
releaseQueuedCronRun(state, pending.jobId, pending.reservationIdentity);
444456
}
@@ -450,8 +462,12 @@ async function applyStartupCatchupOutcomes(
450462
const pendingReleases = clearUnstartedStartupCatchupReservationMarkers(state, plan, outcomes);
451463
if (outcomes.length === 0 && plan.deferredJobs.length === 0) {
452464
if (pendingReleases.length > 0) {
453-
recomputeNextRunsForMaintenance(state, { repairFutureCronNextRunAtMs: false });
454-
await persistOrRestore(state, rollbackSnapshot);
465+
const postPersistNotifications: DeferredCronNotifications = [];
466+
recomputeNextRunsForMaintenance(state, {
467+
repairFutureCronNextRunAtMs: false,
468+
deferredNotifications: postPersistNotifications,
469+
});
470+
await persistOrRestore(state, rollbackSnapshot, { postPersistNotifications });
455471
for (const pending of pendingReleases) {
456472
releaseQueuedCronRun(state, pending.jobId, pending.reservationIdentity);
457473
}
@@ -484,8 +500,12 @@ async function applyStartupCatchupOutcomes(
484500

485501
// Startup overflow owns these staggered wake times; repairing future
486502
// schedules here would silently move a deferred run to its natural slot.
487-
recomputeNextRunsForMaintenance(state, { repairFutureCronNextRunAtMs: false });
488-
await persistOrRestore(state, rollbackSnapshot);
503+
const postPersistNotifications: DeferredCronNotifications = [];
504+
recomputeNextRunsForMaintenance(state, {
505+
repairFutureCronNextRunAtMs: false,
506+
deferredNotifications: postPersistNotifications,
507+
});
508+
await persistOrRestore(state, rollbackSnapshot, { postPersistNotifications });
489509
for (const pending of pendingReleases) {
490510
releaseQueuedCronRun(state, pending.jobId, pending.reservationIdentity);
491511
}

0 commit comments

Comments
 (0)