Skip to content

Commit fa0b9bd

Browse files
authored
fix(cron): emit disable notifications only after durable roster commits
1 parent 15ed0e2 commit fa0b9bd

3 files changed

Lines changed: 89 additions & 3 deletions

File tree

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -506,12 +506,17 @@ export async function removeAgentJobsTransactional<T>(
506506
);
507507
const postPersistNotifications: DeferredCronNotifications = [];
508508
recomputeNextRunsForMaintenance(state, { deferredNotifications: postPersistNotifications });
509-
await persistOrRestore(state, snapshot, { postPersistNotifications });
509+
// Cron is durable first, but notifications stay speculative until the roster commits.
510+
await persistOrRestore(state, snapshot);
510511
let result: T;
511512
try {
512513
result = await commit();
513514
} catch (error) {
514515
if (error instanceof AgentDeletionCommitUncertainError) {
516+
// Uncertain roster writes intentionally keep the cron deletion durable.
517+
for (const notify of postPersistNotifications) {
518+
notify();
519+
}
515520
armTimer(state);
516521
for (const job of removedJobs) {
517522
noteActiveCronJobRemoval(job.id);
@@ -535,6 +540,9 @@ export async function removeAgentJobsTransactional<T>(
535540
}
536541
throw error;
537542
}
543+
for (const notify of postPersistNotifications) {
544+
notify();
545+
}
538546
for (const job of removedJobs) {
539547
noteActiveCronJobRemoval(job.id);
540548
try {

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

Lines changed: 79 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,7 +17,13 @@ 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";
2128
import { inspectManualRunDisposition } from "./ops-run-preparation.js";
2229
import { run } from "./ops-run.js";
@@ -1740,6 +1747,77 @@ describe("cron service ops persist rollback", () => {
17401747
expect(requestHeartbeat).toHaveBeenCalledTimes(1);
17411748
});
17421749

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+
17431821
it("does not auto-disable a job during manual-run preflight", async () => {
17441822
const { storePath } = await makeStorePath();
17451823
const now = Date.parse("2026-06-09T00:00:00.000Z");

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ import {
2929
updateQueuedCronRunReservationMarker,
3030
} from "./run-admission.js";
3131
import { type CronServiceState, type DeferredCronNotifications, emit } from "./state.js";
32-
import { ensureLoaded, persist, persistOrRestore, snapshotStoreForRollback } from "./store.js";
32+
import { ensureLoaded, persistOrRestore, snapshotStoreForRollback } from "./store.js";
3333
import { tryCreateCronTaskRun } from "./task-runs.js";
3434
import { resolveCronJobTimeoutMs } from "./timeout-policy.js";
3535
import {

0 commit comments

Comments
 (0)