From 994bd500b8ee7b3d2ae670df180bd2092bcb0549 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Fri, 13 Nov 2026 21:42:27 -0600 Subject: [PATCH] fix(pm-stack): don't ack Worker-rejected decision events and align ts validation (#9613) --- .../aggregator/src/decision-events-sync.ts | 59 ++++++++++++++++--- .../aggregator/test/decision-events.test.ts | 47 +++++++++++++++ 2 files changed, 99 insertions(+), 7 deletions(-) diff --git a/pm-stack/aggregator/src/decision-events-sync.ts b/pm-stack/aggregator/src/decision-events-sync.ts index 60fafc0061..f0b5678cbd 100644 --- a/pm-stack/aggregator/src/decision-events-sync.ts +++ b/pm-stack/aggregator/src/decision-events-sync.ts @@ -161,7 +161,7 @@ export function validateDecisionEvent( return { ok: false, error: "event.payload exceeds 64 KiB" }; } } - if (typeof b.ts !== "string" || !isIsoDate(b.ts)) { + if (typeof b.ts !== "string" || !b.ts.includes("T") || !isIsoDate(b.ts)) { return { ok: false, error: "event.ts must be an ISO timestamp string" }; } return { ok: true, value: { eventId, setId, questionRef, type, payload, ts: b.ts } }; @@ -322,17 +322,26 @@ export async function insertDecisionEventsTurso( } /** POST one batch to the decision-events Worker webhook. The Worker - * answers 200 with {accepted, inserted, duplicates}; a non-200 (or a - * 200 without that shape) is a failed leg, never a silent success. */ + * answers 200 with {accepted, inserted, duplicates, errors?}; a non-200 + * (or a 200 without that shape) is a failed leg, never a silent success. + * Per-event rejections in `errors` are returned in `rejected` so callers + * only ack `acceptedEvents`. */ export async function postDecisionEventsWebhook( webhookUrl: string, secret: string, events: DecisionSetEvent[], fetchFn: FetchFn = fetch, batchSize = 100, -): Promise<{ attempted: number; inserted: number }> { +): Promise<{ + attempted: number; + inserted: number; + acceptedEvents: DecisionSetEvent[]; + rejected: { event: DecisionSetEvent; error: string }[]; +}> { if (!webhookUrl || !secret) throw new Error("webhook url/secret unset"); let inserted = 0; + const acceptedEvents: DecisionSetEvent[] = []; + const rejected: { event: DecisionSetEvent; error: string }[] = []; for (let i = 0; i < events.length; i += batchSize) { const batch = events.slice(i, i + batchSize); const res = await fetchFn(webhookUrl, { @@ -342,11 +351,37 @@ export async function postDecisionEventsWebhook( signal: AbortSignal.timeout(30_000), }); if (!res.ok) throw new Error(`webhook failed: HTTP ${res.status}`); - const out = (await res.json().catch(() => null)) as { inserted?: unknown } | null; + const out = (await res.json().catch(() => null)) as { + inserted?: unknown; + errors?: unknown; + } | null; if (!out || typeof out.inserted !== "number") throw new Error("webhook failed: malformed response"); inserted += out.inserted; + const rejectedIndices = new Set(); + if (Array.isArray(out.errors)) { + for (const entry of out.errors) { + if ( + entry && + typeof entry === "object" && + typeof (entry as { index?: unknown }).index === "number" && + (entry as { index: number }).index >= 0 && + (entry as { index: number }).index < batch.length + ) { + const idx = (entry as { index: number }).index; + rejectedIndices.add(idx); + const errMsg = + typeof (entry as { error?: unknown }).error === "string" + ? (entry as { error: string }).error + : "rejected by webhook"; + rejected.push({ event: batch[idx] as DecisionSetEvent, error: errMsg }); + } + } + } + for (let j = 0; j < batch.length; j++) { + if (!rejectedIndices.has(j)) acceptedEvents.push(batch[j] as DecisionSetEvent); + } } - return { attempted: events.length, inserted }; + return { attempted: events.length, inserted, acceptedEvents, rejected }; } // --- Per-leg sync state (which eventIds each sink has acked) --- @@ -444,6 +479,7 @@ export async function syncDecisionEvents(opts: SyncOptions): Promise 0) { + markAcked(opts.state, leg, r.acceptedEvents); + } + if (r.rejected.length > 0) { + const sample = r.rejected + .slice(0, 3) + .map((x) => `${x.event.eventId}: ${x.error}`) + .join("; "); + report.error = `webhook rejected ${r.rejected.length} event(s): ${sample}`; + } } - markAcked(opts.state, leg, pending); } catch (err) { report.error = err instanceof Error ? err.message : String(err); } diff --git a/pm-stack/aggregator/test/decision-events.test.ts b/pm-stack/aggregator/test/decision-events.test.ts index 0d194d82ac..b6655ccdc5 100644 --- a/pm-stack/aggregator/test/decision-events.test.ts +++ b/pm-stack/aggregator/test/decision-events.test.ts @@ -285,3 +285,50 @@ describe("Track A outbox format (reconciliation with PR #9343)", () => { if (v.ok) expect(v.value.questionRef).toBe("ledger-1#2"); }); }); + +describe("Worker contract alignment (#9613)", () => { + test("validateDecisionEvent rejects date-only timestamps without T", () => { + const v = validateDecisionEvent({ + eventId: "e-date-only", + setId: "s1", + type: "answer", + ts: "2026-11-14", + payload: {}, + }); + expect(v.ok).toBe(false); + }); + + test("syncDecisionEvents does not ack events rejected per-event by webhook", async () => { + const state = emptySyncState(); + const events = [ + { eventId: "e1", setId: "s1", questionRef: null, type: "answer", payload: {}, ts: "2026-11-14T00:00:00Z" }, + { eventId: "e2", setId: "s1", questionRef: null, type: "answer", payload: {}, ts: "2026-11-14T00:00:01Z" }, + { eventId: "e3", setId: "s1", questionRef: null, type: "answer", payload: {}, ts: "2026-11-14T00:00:02Z" }, + ]; + const fetchFn = (async () => + new Response( + JSON.stringify({ + accepted: 2, + inserted: 2, + duplicates: 0, + errors: [{ index: 1, error: "event.ts must be an ISO timestamp string" }], + }), + { status: 200, headers: { "Content-Type": "application/json" } }, + )) as unknown as typeof fetch; + + const reports = await syncDecisionEvents({ + events, + state, + legs: ["webhook"], + webhookUrl: "https://example.invalid/webhook", + webhookSecret: "test-secret", + fetchFn, + }); + + expect(reports).toHaveLength(1); + expect(reports[0]?.inserted).toBe(2); + expect(reports[0]?.error).toContain("webhook rejected 1 event(s)"); + expect(reports[0]?.error).toContain("e2"); + expect(state.acked.webhook).toEqual(["e1", "e3"]); + }); +});