Skip to content

Commit 0484d92

Browse files
committed
test(cron): prove finalization→durable streak+alert via shared production mapper (#116731)
Extract resolveCronRunFinalStatus as the single exported production mapper from cron payload outcome to terminal run status, and use it at both finalization sites in run-finalize.ts (diagnostics finalStatus and run status). This removes the two inline copies of the status ternary so finalization diagnostics, run status, and downstream timer/alert state share one source of truth. Rewrite the streak proof to route through the REAL shared mapper (not a copied ternary) and the REAL finalizeCompletedCronRunOutcomes, which persists job state and emits the failure alert. The test now asserts DURABLE state reloaded from the store (consecutiveErrors, lastRunStatus) and a FIRED alert (lastFailureAlertAtMs + sendCronFailureAlert), across all four silent forms — addressing the production-finalizer and durable- state/alert proof gates.
1 parent b207721 commit 0484d92

2 files changed

Lines changed: 144 additions & 86 deletions

File tree

‎src/cron/isolated-agent/run-finalize.ts‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,19 @@ async function loadUsageFormatRuntime() {
5858
return await import("../../utils/usage-format.js");
5959
}
6060

61+
/**
62+
* Maps a resolved cron payload outcome to the terminal run status. A fatal
63+
* error payload (or run-level error/failure signal) makes the run an error;
64+
* otherwise the run is ok. This is the single production mapper from the
65+
* payload-outcome owner to the finalization status, so finalization diagnostics
66+
* and downstream timer/alert state share one source of truth.
67+
*/
68+
export function resolveCronRunFinalStatus(outcome: {
69+
hasFatalErrorPayload: boolean;
70+
}): "error" | "ok" {
71+
return outcome.hasFatalErrorPayload ? "error" : "ok";
72+
}
73+
6174
export async function finalizeCronRun(params: {
6275
prepared: PreparedCronRunContext;
6376
execution: CronExecutionResult;
@@ -298,7 +311,7 @@ export async function finalizeCronRun(params: {
298311
embeddedRunError,
299312
} = cronPayloadOutcome;
300313
const agentDiagnostics = createCronRunDiagnosticsFromAgentResult(finalRunResult, {
301-
finalStatus: hasFatalErrorPayload ? "error" : "ok",
314+
finalStatus: resolveCronRunFinalStatus(cronPayloadOutcome),
302315
});
303316
const runDiagnostics = mergeCronRunDiagnostics(prepared.preflightDiagnostics, agentDiagnostics);
304317
const resolveRunOutcome = (result?: {
@@ -308,7 +321,7 @@ export async function finalizeCronRun(params: {
308321
delivery?: CronDeliveryTrace;
309322
}) =>
310323
prepared.withRunSession({
311-
status: hasFatalErrorPayload ? "error" : "ok",
324+
status: resolveCronRunFinalStatus(cronPayloadOutcome),
312325
...(hasFatalErrorPayload
313326
? { error: embeddedRunError ?? "cron isolated run returned an error payload" }
314327
: {}),
Lines changed: 129 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -1,126 +1,171 @@
1-
// Finalization-to-timer-state proof: drives the REAL resolveCronPayloadOutcome
2-
// (the cron finalization classifier at run-finalize.ts:251) through the
3-
// run-finalize finalStatus mapping (run-finalize.ts:301) into the REAL
4-
// applyJobResult (the persisted timer-state update at timer-outcomes.ts:144) to
5-
// show that an error payload plus a silent (NO_REPLY) final assistant text
6-
// stays fatal, marks the run "error", and increments consecutiveErrors so
7-
// failureAlert can fire. This is the default cron path — no mock stands in for
8-
// resolveCronPayloadOutcome or applyJobResult.
1+
// Finalization-to-durable-state proof: drives the REAL resolveCronPayloadOutcome
2+
// (the cron finalization classifier at run-finalize.ts:251) through the REAL
3+
// shared production finalization mapper resolveCronRunFinalStatus (run-finalize.ts)
4+
// into the REAL finalizeCompletedCronRunOutcomes (timer-outcome-finalization.ts),
5+
// which persists job state and emits the failure alert. No mock stands in for
6+
// the classifier, the finalization mapper, or the persisted timer-state update.
97
import { describe, expect, it, vi } from "vitest";
10-
import { makeCronJob } from "../delivery.test-helpers.js";
8+
import {
9+
createDueIsolatedJob,
10+
noopLogger,
11+
setupCronRegressionFixtures,
12+
} from "../../../test/helpers/cron/service-regression-fixtures.js";
13+
import { markCronJobActive } from "../active-jobs.js";
1114
import { resolveCronPayloadOutcome } from "../isolated-agent/helpers.js";
12-
import { createNoopLogger } from "../service.test-harness.js";
15+
import { resolveCronRunFinalStatus } from "../isolated-agent/run-finalize.js";
16+
import { loadCronStore, saveCronStore } from "../store.js";
1317
import type { CronJob } from "../types.js";
1418
import { createCronServiceState } from "./state.js";
15-
import { applyJobResult } from "./timer.js";
19+
import { finalizeCompletedCronRunOutcomes } from "./timer-outcome-finalization.js";
1620

17-
const STARTED_AT = 1_000;
18-
const ENDED_AT = 2_000;
21+
const fixtures = setupCronRegressionFixtures({
22+
prefix: "cron-finalization-streak-",
23+
baseTimeIso: "2026-08-01T14:50:00.000Z",
24+
});
25+
26+
const DUE_AT = Date.parse("2026-08-01T14:50:00.000Z");
27+
const ENDED_AT = DUE_AT + 10;
28+
const ERROR_PAYLOAD = { text: "⚠️ 🛠️ Exec failed: ENOENT /mnt/d unreachable", isError: true };
29+
30+
type SendCronFailureAlert = NonNullable<
31+
Parameters<typeof createCronServiceState>[0]["sendCronFailureAlert"]
32+
>;
33+
34+
function makeAlertJob(id: string): CronJob {
35+
const job = createDueIsolatedJob({ id, nowMs: DUE_AT, nextRunAtMs: DUE_AT });
36+
job.schedule = { kind: "every", everyMs: 60 * 60_000, anchorMs: DUE_AT - 60_000 };
37+
// after:1 so a single error run fires the failure alert through the real
38+
// maybeEmitFailureAlert path (failure-alerts.ts).
39+
job.failureAlert = { after: 1, cooldownMs: 60_000 };
40+
job.state.runningAtMs = DUE_AT;
41+
return job;
42+
}
1943

20-
function makeState() {
44+
function makeState(storePath: string, sendCronFailureAlert: SendCronFailureAlert) {
2145
return createCronServiceState({
22-
storePath: "/tmp/cron-finalization-streak/jobs.json",
2346
cronEnabled: true,
24-
log: createNoopLogger(),
47+
storePath,
48+
log: noopLogger,
2549
nowMs: () => ENDED_AT,
2650
enqueueSystemEvent: vi.fn(),
2751
requestHeartbeat: vi.fn(),
28-
runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" as const })),
52+
sendCronFailureAlert,
53+
runIsolatedAgentJob: vi.fn(),
2954
});
3055
}
3156

32-
function makeJob(): CronJob {
33-
return makeCronJob({
34-
schedule: { kind: "every", everyMs: 60 * 60_000, anchorMs: STARTED_AT },
35-
state: { nextRunAtMs: STARTED_AT, consecutiveErrors: 0 },
57+
// Real finalization: classifier -> shared production mapper -> persisted timer
58+
// state + alert. The status is produced by the REAL resolveCronRunFinalStatus,
59+
// not a copied ternary, so the proof tracks the production finalization owner.
60+
async function finalizeSilentReplyRun(
61+
state: ReturnType<typeof createCronServiceState>,
62+
job: CronJob,
63+
silentText: string,
64+
startedAt = DUE_AT,
65+
endedAt = ENDED_AT,
66+
) {
67+
const outcome = resolveCronPayloadOutcome({
68+
payloads: [ERROR_PAYLOAD],
69+
finalAssistantVisibleText: silentText,
70+
preferFinalAssistantVisibleText: true,
3671
});
72+
const status = resolveCronRunFinalStatus(outcome);
73+
await finalizeCompletedCronRunOutcomes(state, [
74+
{
75+
jobId: job.id,
76+
job: structuredClone(job),
77+
activeJobMarker: markCronJobActive(job.id),
78+
status,
79+
error: status === "error" ? outcome.embeddedRunError : undefined,
80+
startedAt,
81+
endedAt,
82+
},
83+
]);
84+
return { outcome, status };
3785
}
3886

39-
// run-finalize.ts:301 — finalStatus: hasFatalErrorPayload ? "error" : "ok".
40-
// The real production mapping; cited here because it is an inline ternary in
41-
// finalizeCronRun, not an exported helper.
42-
function finalStatusFromOutcome(hasFatalErrorPayload: boolean): "ok" | "error" {
43-
return hasFatalErrorPayload ? "error" : "ok";
44-
}
45-
46-
describe("cron finalization → persisted timer state (real classifier + real applyJobResult)", () => {
87+
describe("cron finalization → durable timer state + failure alert (real classifier + real mapper + real persistence)", () => {
4788
it.each([
4889
["token-only", "NO_REPLY"],
4990
["json string", '"NO_REPLY"'],
5091
["action envelope", '{"action":"NO_REPLY"}'],
5192
["reasoning-prefixed", "<thinking>considered</thinking>NO_REPLY"],
5293
])(
53-
"an error payload plus a %s silent final reply stays fatal and increments consecutiveErrors (#116731)",
54-
(_form, silentText) => {
55-
const state = makeState();
56-
const job = makeJob();
57-
58-
// Real cron finalization classifier (run-finalize.ts:251).
59-
const outcome = resolveCronPayloadOutcome({
60-
payloads: [{ text: "⚠️ 🛠️ Exec failed: ENOENT /mnt/d unreachable", isError: true }],
61-
finalAssistantVisibleText: silentText,
62-
preferFinalAssistantVisibleText: true,
63-
});
64-
65-
// Real run-finalize mapping (run-finalize.ts:301).
66-
const finalStatus = finalStatusFromOutcome(outcome.hasFatalErrorPayload);
67-
68-
// Real persisted timer-state update (timer-outcomes.ts:144).
69-
applyJobResult(state, job, {
70-
status: finalStatus,
71-
startedAt: STARTED_AT,
72-
endedAt: ENDED_AT,
73-
error: finalStatus === "error" ? outcome.embeddedRunError : undefined,
74-
});
94+
"an error payload plus a %s silent final reply stays fatal, persists consecutiveErrors, and fires the alert (#116731)",
95+
async (_form, silentText) => {
96+
const store = fixtures.makeStorePath();
97+
const job = makeAlertJob(`silent-${_form.replace(/\s+/g, "-")}`);
98+
await saveCronStore(store.storePath, { version: 1, jobs: [job] });
7599

100+
const sendCronFailureAlert = vi.fn(async () => undefined);
101+
const state = makeState(store.storePath, sendCronFailureAlert);
102+
103+
const { outcome, status } = await finalizeSilentReplyRun(state, job, silentText);
104+
105+
// Real classifier + real shared production mapper.
76106
expect(outcome.hasFatalErrorPayload).toBe(true);
77-
expect(finalStatus).toBe("error");
78-
expect(job.state.consecutiveErrors).toBe(1);
79-
expect(job.state.lastRunStatus).toBe("error");
107+
expect(status).toBe("error");
108+
109+
// Durable state: reload from the store and assert the persisted streak.
110+
const reloaded = (await loadCronStore(store.storePath)).jobs[0];
111+
expect(reloaded?.state.consecutiveErrors).toBe(1);
112+
expect(reloaded?.state.lastRunStatus).toBe("error");
113+
// Fired alert: the real maybeEmitFailureAlert recorded the durable alert
114+
// marker and dispatched sendCronFailureAlert after the terminal write.
115+
expect(reloaded?.state.lastFailureAlertAtMs).toBe(ENDED_AT);
116+
expect(sendCronFailureAlert).toHaveBeenCalledOnce();
80117
},
81118
);
82119

83-
it("a recovering final answer clears the error streak (control)", () => {
84-
const state = makeState();
85-
const job = makeJob();
120+
it("a recovering final answer clears the error streak and fires no alert (control)", async () => {
121+
const store = fixtures.makeStorePath();
122+
const job = makeAlertJob("silent-recovering-control");
86123
job.state.consecutiveErrors = 2;
124+
await saveCronStore(store.storePath, { version: 1, jobs: [job] });
125+
126+
const sendCronFailureAlert = vi.fn(async () => undefined);
127+
const state = makeState(store.storePath, sendCronFailureAlert);
87128

88129
const outcome = resolveCronPayloadOutcome({
89-
payloads: [{ text: "⚠️ 🛠️ Exec failed", isError: true }],
130+
payloads: [ERROR_PAYLOAD],
90131
finalAssistantVisibleText: "**Daily report**: 34 closed",
91132
preferFinalAssistantVisibleText: true,
92133
});
93-
const finalStatus = finalStatusFromOutcome(outcome.hasFatalErrorPayload);
94-
95-
applyJobResult(state, job, {
96-
status: finalStatus,
97-
startedAt: STARTED_AT,
98-
endedAt: ENDED_AT,
99-
});
134+
const status = resolveCronRunFinalStatus(outcome);
135+
expect(status).toBe("ok");
136+
await finalizeCompletedCronRunOutcomes(state, [
137+
{
138+
jobId: job.id,
139+
job: structuredClone(job),
140+
activeJobMarker: markCronJobActive(job.id),
141+
status,
142+
startedAt: DUE_AT,
143+
endedAt: ENDED_AT,
144+
},
145+
]);
100146

101-
expect(outcome.hasFatalErrorPayload).toBe(false);
102-
expect(finalStatus).toBe("ok");
103-
expect(job.state.consecutiveErrors).toBe(0);
104-
expect(job.state.lastRunStatus).toBe("ok");
147+
const reloaded = (await loadCronStore(store.storePath)).jobs[0];
148+
expect(reloaded?.state.consecutiveErrors).toBe(0);
149+
expect(reloaded?.state.lastRunStatus).toBe("ok");
150+
expect(reloaded?.state.lastFailureAlertAtMs).toBeUndefined();
151+
expect(sendCronFailureAlert).not.toHaveBeenCalled();
105152
});
106153

107-
it("accumulates the error streak across consecutive silent-reply failures", () => {
108-
const state = makeState();
109-
const job = makeJob();
154+
it("accumulates the error streak across consecutive silent-reply failures", async () => {
155+
const store = fixtures.makeStorePath();
156+
const job = makeAlertJob("silent-streak");
157+
await saveCronStore(store.storePath, { version: 1, jobs: [job] });
158+
159+
const sendCronFailureAlert = vi.fn(async () => undefined);
160+
const state = makeState(store.storePath, sendCronFailureAlert);
110161

162+
// Three consecutive silent-reply error runs through the real finalization
163+
// path. Each call reloads the durable store, so the streak accumulates 1->2->3.
111164
for (let i = 1; i <= 3; i++) {
112-
const outcome = resolveCronPayloadOutcome({
113-
payloads: [{ text: "⚠️ 🛠️ Exec failed: ENOENT /mnt/d unreachable", isError: true }],
114-
finalAssistantVisibleText: '{"action":"NO_REPLY"}',
115-
preferFinalAssistantVisibleText: true,
116-
});
117-
applyJobResult(state, job, {
118-
status: finalStatusFromOutcome(outcome.hasFatalErrorPayload),
119-
startedAt: STARTED_AT + i,
120-
endedAt: ENDED_AT + i,
121-
error: outcome.embeddedRunError,
122-
});
123-
expect(job.state.consecutiveErrors).toBe(i);
165+
await finalizeSilentReplyRun(state, job, '{"action":"NO_REPLY"}', DUE_AT + i, ENDED_AT + i);
166+
const reloaded = (await loadCronStore(store.storePath)).jobs[0];
167+
expect(reloaded?.state.consecutiveErrors).toBe(i);
168+
expect(reloaded?.state.lastRunStatus).toBe("error");
124169
}
125170
});
126171
});

0 commit comments

Comments
 (0)