Skip to content

Commit 0b87dd0

Browse files
committed
fix(cron): stop reaping deleted agents
1 parent 96cacfd commit 0b87dd0

6 files changed

Lines changed: 80 additions & 2 deletions

File tree

‎src/cron/service.session-reaper-in-finally.test.ts‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,72 @@ describe("CronService - session reaper runs in finally block (#31946)", () => {
333333
});
334334
});
335335

336+
it.each([
337+
{ name: "deleted persisted owner", includeStaleJob: false },
338+
{ name: "blocked-delete owner with unfinished job cleanup", includeStaleJob: true },
339+
])("skips an unavailable $name without hiding a live owner", async ({ includeStaleJob }) => {
340+
const store = await makeStorePath();
341+
const now = Date.parse("2026-02-10T10:00:00.000Z");
342+
const liveAgentId = "live";
343+
const unavailableAgentId = includeStaleJob ? "blocked" : "deleted";
344+
const sessionStorePath = path.join(path.dirname(store.storePath), "sessions", "sessions.json");
345+
const jobs = includeStaleJob
346+
? [
347+
{
348+
...createDueIsolatedJob({ id: "unfinished-cleanup", nowMs: now }),
349+
agentId: unavailableAgentId,
350+
enabled: false,
351+
},
352+
]
353+
: [];
354+
await saveCronStore(store.storePath, { version: 1, jobs });
355+
await replaceSessionEntry(
356+
{
357+
agentId: liveAgentId,
358+
storePath: sessionStorePath,
359+
sessionKey: `agent:${liveAgentId}:cron:old-job:run:expired`,
360+
},
361+
{ sessionId: "live-expired", updatedAt: now - 25 * 3_600_000 },
362+
);
363+
const resolveSessionStorePath = vi.fn((agentId?: string) => {
364+
if (agentId === unavailableAgentId) {
365+
throw new Error(
366+
`OpenClaw agent database is unavailable while agent ${unavailableAgentId} is deleted.`,
367+
);
368+
}
369+
return sessionStorePath;
370+
});
371+
const state = createCronServiceState({
372+
storePath: store.storePath,
373+
cronEnabled: true,
374+
log: noopLogger,
375+
nowMs: () => now,
376+
enqueueSystemEvent: vi.fn(),
377+
requestHeartbeat: vi.fn(),
378+
runIsolatedAgentJob: vi.fn(),
379+
resolveDefaultAgentId: () => undefined,
380+
resolveSessionStoreAgentIds: () => [liveAgentId, unavailableAgentId],
381+
isAgentAvailable: (agentId) => agentId === liveAgentId,
382+
resolveSessionStorePath,
383+
});
384+
385+
await withCronServiceStateForTest(state, async () => {
386+
await onTimer(state);
387+
await onTimer(state);
388+
389+
expect(resolveSessionStorePath.mock.calls).toEqual([[liveAgentId], [liveAgentId]]);
390+
expect(listSessionEntriesCore({ agentId: liveAgentId, storePath: sessionStorePath })).toEqual(
391+
[],
392+
);
393+
expect(noopLogger.warn).not.toHaveBeenCalled();
394+
expect(
395+
noopLogger.debug.mock.calls.filter(
396+
([, message]) => message === "cron-reaper: skipped unavailable agent",
397+
),
398+
).toEqual([[{ agentId: unavailableAgentId }, "cron-reaper: skipped unavailable agent"]]);
399+
});
400+
});
401+
336402
it("sweeps a persisted owner after it leaves the roster and cron store", async () => {
337403
const store = await makeStorePath();
338404
const now = Date.parse("2026-02-10T10:00:00.000Z");

‎src/cron/service.test-harness.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,7 @@ export function createMockCronStateForJobs(params: {
259259
op: Promise.resolve(),
260260
warnedDisabled: false,
261261
warnedInvalidPersistedJobKeys: new Set<string>(),
262+
reportedUnavailableReaperAgentIds: new Set<string>(),
262263
pendingQuarantineConfigJobs: [],
263264
lastQuarantineFailureWarnKey: null,
264265
deps: {

‎src/cron/service/state.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,8 @@ export type CronServiceState = {
295295
* until the runtime can quarantine and sanitize the active store.
296296
*/
297297
warnedInvalidPersistedJobKeys: Set<string>;
298+
/** Availability is rechecked every tick; this set only bounds skip diagnostics. */
299+
reportedUnavailableReaperAgentIds: Set<string>;
298300
pendingQuarantineConfigJobs: QuarantinedCronConfigJob[];
299301
lastQuarantineFailureWarnKey: string | null;
300302
storeLoadedAtMs: number | null;
@@ -323,6 +325,7 @@ export function createCronServiceState(deps: CronServiceDeps): CronServiceState
323325
op: Promise.resolve(),
324326
warnedDisabled: false,
325327
warnedInvalidPersistedJobKeys: new Set<string>(),
328+
reportedUnavailableReaperAgentIds: new Set<string>(),
326329
pendingQuarantineConfigJobs: [],
327330
lastQuarantineFailureWarnKey: null,
328331
storeLoadedAtMs: null,

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,14 @@ async function onAdmittedTimer(state: CronServiceState) {
466466
if (reaperAgentIds.size > 0) {
467467
const nowMs = state.deps.nowMs();
468468
for (const agentId of reaperAgentIds) {
469+
if (state.deps.isAgentAvailable?.(agentId) === false) {
470+
if (!state.reportedUnavailableReaperAgentIds.has(agentId)) {
471+
state.reportedUnavailableReaperAgentIds.add(agentId);
472+
state.deps.log.debug({ agentId }, "cron-reaper: skipped unavailable agent");
473+
}
474+
continue;
475+
}
476+
state.reportedUnavailableReaperAgentIds.delete(agentId);
469477
const storePath = state.deps.resolveSessionStorePath
470478
? state.deps.resolveSessionStorePath(agentId)
471479
: state.deps.sessionStorePath;

‎src/gateway/local-request-context.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ function createLocalGatewayRequestContext(
8383
storePath,
8484
cronEnabled: cfg.cron?.enabled !== false,
8585
cronConfig: cfg.cron,
86-
log: getChildLogger({ module: "cron", storePath }),
86+
log: getChildLogger({ module: "cron", storeKey: storePath }),
8787
defaultAgentId: tryResolveLegacyCompatibilityAgentId(cfg),
8888
legacyDefaultAgentId: tryGetLegacyDefaultAgentId(cfg),
8989
resolveDefaultAgentId: () =>

‎src/gateway/server-cron.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1022,7 +1022,7 @@ export function buildGatewayCronService(params: {
10221022
webhookToken: params.cfg.cron?.webhookToken,
10231023
ssrfPolicy: webhookSsrfPolicy,
10241024
}),
1025-
log: getChildLogger({ module: "cron", storePath }),
1025+
log: getChildLogger({ module: "cron", storeKey: storePath }),
10261026
onEvent: (evt) => {
10271027
// Any job/store change can alter session automation bindings, including
10281028
// in-place enable flips during runs; run/schedule events bump too (cheap).

0 commit comments

Comments
 (0)