|
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. |
9 | 7 | 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"; |
11 | 14 | 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"; |
13 | 17 | import type { CronJob } from "../types.js"; |
14 | 18 | import { createCronServiceState } from "./state.js"; |
15 | | -import { applyJobResult } from "./timer.js"; |
| 19 | +import { finalizeCompletedCronRunOutcomes } from "./timer-outcome-finalization.js"; |
16 | 20 |
|
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 | +} |
19 | 43 |
|
20 | | -function makeState() { |
| 44 | +function makeState(storePath: string, sendCronFailureAlert: SendCronFailureAlert) { |
21 | 45 | return createCronServiceState({ |
22 | | - storePath: "/tmp/cron-finalization-streak/jobs.json", |
23 | 46 | cronEnabled: true, |
24 | | - log: createNoopLogger(), |
| 47 | + storePath, |
| 48 | + log: noopLogger, |
25 | 49 | nowMs: () => ENDED_AT, |
26 | 50 | enqueueSystemEvent: vi.fn(), |
27 | 51 | requestHeartbeat: vi.fn(), |
28 | | - runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" as const })), |
| 52 | + sendCronFailureAlert, |
| 53 | + runIsolatedAgentJob: vi.fn(), |
29 | 54 | }); |
30 | 55 | } |
31 | 56 |
|
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, |
36 | 71 | }); |
| 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 }; |
37 | 85 | } |
38 | 86 |
|
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)", () => { |
47 | 88 | it.each([ |
48 | 89 | ["token-only", "NO_REPLY"], |
49 | 90 | ["json string", '"NO_REPLY"'], |
50 | 91 | ["action envelope", '{"action":"NO_REPLY"}'], |
51 | 92 | ["reasoning-prefixed", "<thinking>considered</thinking>NO_REPLY"], |
52 | 93 | ])( |
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] }); |
75 | 99 |
|
| 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. |
76 | 106 | 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(); |
80 | 117 | }, |
81 | 118 | ); |
82 | 119 |
|
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"); |
86 | 123 | 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); |
87 | 128 |
|
88 | 129 | const outcome = resolveCronPayloadOutcome({ |
89 | | - payloads: [{ text: "⚠️ 🛠️ Exec failed", isError: true }], |
| 130 | + payloads: [ERROR_PAYLOAD], |
90 | 131 | finalAssistantVisibleText: "**Daily report**: 34 closed", |
91 | 132 | preferFinalAssistantVisibleText: true, |
92 | 133 | }); |
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 | + ]); |
100 | 146 |
|
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(); |
105 | 152 | }); |
106 | 153 |
|
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); |
110 | 161 |
|
| 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. |
111 | 164 | 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"); |
124 | 169 | } |
125 | 170 | }); |
126 | 171 | }); |
0 commit comments