From b3a4fb361768eeeea0dc992680e783bd2e6afb92 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Fri, 13 Nov 2026 21:39:36 -0600 Subject: [PATCH] fix(pm-stack): preserve DO fan-out on ingest failure and deduplicate by eventId (#9612) --- pm-stack/decision-events-worker/src/index.ts | 90 ++++++++++++------ .../test/events.test.ts | 94 +++++++++++++++++++ 2 files changed, 154 insertions(+), 30 deletions(-) diff --git a/pm-stack/decision-events-worker/src/index.ts b/pm-stack/decision-events-worker/src/index.ts index 18a3209a17..f080c5cb04 100644 --- a/pm-stack/decision-events-worker/src/index.ts +++ b/pm-stack/decision-events-worker/src/index.ts @@ -88,25 +88,41 @@ export class DecisionSetEvents { this.setId = body.setId; const state = await this.loadState(); state.setId = body.setId; + const seenList = (await this.state.storage.get("seenEventIds")) ?? []; + const seen = new Set(seenList); + const newEvents: DecisionSetEvent[] = []; for (const e of body.events) { + if (seen.has(e.eventId)) continue; + seen.add(e.eventId); + seenList.push(e.eventId); + newEvents.push(e); state.fannedOut += 1; state.lastEventId = e.eventId; state.lastType = e.type; state.lastTs = e.ts; } - state.updatedAt = new Date().toISOString(); - await this.state.storage.put("state", state); - const message = JSON.stringify({ type: "decision-events", setId: body.setId, events: body.events }); let delivered = 0; - for (const ws of this.state.getWebSockets()) { - try { - ws.send(message); - delivered += 1; - } catch { - // A dead socket drops out of getWebSockets on its own. + if (newEvents.length > 0) { + state.updatedAt = new Date().toISOString(); + const trimmedSeen = seenList.length > 1000 ? seenList.slice(-1000) : seenList; + await this.state.storage.put("seenEventIds", trimmedSeen); + await this.state.storage.put("state", state); + const message = JSON.stringify({ type: "decision-events", setId: body.setId, events: newEvents }); + for (const ws of this.state.getWebSockets()) { + try { + ws.send(message); + delivered += 1; + } catch { + // A dead socket drops out of getWebSockets on its own. + } } } - return Response.json({ ...state, subscribers: this.state.getWebSockets().length, delivered }); + return Response.json({ + ...state, + subscribers: this.state.getWebSockets().length, + delivered, + deduplicated: body.events.length - newEvents.length, + }); } if (url.pathname === "/state") { const state = await this.loadState(); @@ -151,39 +167,53 @@ async function handlePostEvents(request: Request, env: Env): Promise { return Response.json({ accepted: 0, inserted: 0, duplicates: 0, errors }); } - // Store first (D1, idempotent), fan out only what was actually new. + // Store first (D1, idempotent), then fan out to each set's Durable Object. + // Fan out all valid events (not just insertedEvents) because DO /ingest + // deduplicates by eventId; if DO ingest failed on an earlier attempt, a retry + // will report 0 D1 changes but still needs to reach the DO. const statements = events.map((e) => env.DB.prepare( "INSERT OR IGNORE INTO decision_set_events (event_id, set_id, question_ref, type, payload, ts) VALUES (?, ?, ?, ?, ?, ?)", ).bind(e.eventId, e.setId, e.questionRef, e.type, JSON.stringify(e.payload), e.ts), ); const results = await env.DB.batch(statements); - const insertedEvents: DecisionSetEvent[] = []; let inserted = 0; - results.forEach((r, i) => { - const changes = r.meta?.changes ?? 0; - inserted += changes; - if (changes > 0) insertedEvents.push(events[i] as DecisionSetEvent); + results.forEach((r) => { + inserted += r.meta?.changes ?? 0; }); const fanout: Record = {}; - for (const [setId, setEvents] of groupBySet(insertedEvents)) { + let fanoutFailed = false; + for (const [setId, setEvents] of groupBySet(events)) { const stub = env.SET_EVENTS.get(env.SET_EVENTS.idFromName(setId)); - const res = await stub.fetch("https://do/ingest", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ setId, events: setEvents }), - }); - fanout[setId] = res.ok ? await res.json().catch(() => null) : { error: `do ingest HTTP ${res.status}` }; + try { + const res = await stub.fetch("https://do/ingest", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ setId, events: setEvents }), + }); + if (!res.ok) { + fanoutFailed = true; + fanout[setId] = { error: `do ingest HTTP ${res.status}` }; + } else { + fanout[setId] = await res.json().catch(() => null); + } + } catch (err) { + fanoutFailed = true; + fanout[setId] = { error: err instanceof Error ? err.message : String(err) }; + } } - return Response.json({ - accepted: events.length, - inserted, - duplicates: events.length - inserted, - errors, - fanout, - }); + return Response.json( + { + accepted: events.length, + inserted, + duplicates: events.length - inserted, + errors, + fanout, + }, + { status: fanoutFailed ? 502 : 200 }, + ); } async function handleGetEvents(url: URL, env: Env, setId: string): Promise { diff --git a/pm-stack/decision-events-worker/test/events.test.ts b/pm-stack/decision-events-worker/test/events.test.ts index b7bc56aa33..15ec119eeb 100644 --- a/pm-stack/decision-events-worker/test/events.test.ts +++ b/pm-stack/decision-events-worker/test/events.test.ts @@ -1,5 +1,6 @@ import { describe, expect, test } from "bun:test"; import { groupBySet, isAuthorized, parseEventBatch, timingSafeEqual, validateDecisionEvent } from "../src/events.ts"; +import worker, { DecisionSetEvents, type Env } from "../src/index.ts"; const ev = (eventId: string, setId = "set-1") => ({ eventId, @@ -68,3 +69,96 @@ describe("groupBySet", () => { expect(groups.get("set-1")?.map((e) => e.eventId)).toEqual(["e1", "e3"]); }); }); + +describe("DecisionSetEvents & POST /events fan-out retry", () => { + function makeMockEnv() { + const d1Events = new Set(); + const doStorage = new Map(); + const doInstance = new DecisionSetEvents({ + storage: { + get: async (k: string) => doStorage.get(k) as T | undefined, + put: async (k: string, v: unknown) => { + doStorage.set(k, v); + }, + }, + getWebSockets: () => [], + } as unknown as DurableObjectState); + + let failNextIngest = false; + const env = { + WEBHOOK_SECRET: "s3cr3t", + DB: { + prepare: () => ({ + bind: (eventId: string) => ({ eventId }), + }), + batch: async (stmts: Array<{ eventId: string }>) => + stmts.map((s) => { + if (d1Events.has(s.eventId)) return { meta: { changes: 0 } }; + d1Events.add(s.eventId); + return { meta: { changes: 1 } }; + }), + } as unknown as D1Database, + SET_EVENTS: { + idFromName: (name: string) => name as unknown as DurableObjectId, + get: () => ({ + fetch: async (url: string, init?: RequestInit) => { + if (failNextIngest) { + failNextIngest = false; + return new Response("boom", { status: 500 }); + } + return doInstance.fetch(new Request(url, init)); + }, + }), + } as unknown as DurableObjectNamespace, + } satisfies Env; + + return { + env, + setFailNextIngest: (v: boolean) => { + failNextIngest = v; + }, + }; + } + + test("returns 502 on DO ingest failure and fans out exactly once on retry", async () => { + const { env, setFailNextIngest } = makeMockEnv(); + const post = () => + worker.fetch( + new Request("https://worker/events", { + method: "POST", + headers: { Authorization: "Bearer s3cr3t", "Content-Type": "application/json" }, + body: JSON.stringify({ events: [ev("e1")] }), + }), + env, + ); + + setFailNextIngest(true); + const first = await post(); + expect(first.status).toBe(502); + const firstBody = (await first.json()) as { inserted: number; fanout: Record }; + expect(firstBody.inserted).toBe(1); + expect(firstBody.fanout["set-1"]?.error).toContain("500"); + + // Retry: D1 reports 0 changes, DO ingest succeeds and fans out e1 once. + const retry = await post(); + expect(retry.status).toBe(200); + const retryBody = (await retry.json()) as { + inserted: number; + duplicates: number; + fanout: Record; + }; + expect(retryBody.inserted).toBe(0); + expect(retryBody.duplicates).toBe(1); + expect(retryBody.fanout["set-1"]?.fannedOut).toBe(1); + expect(retryBody.fanout["set-1"]?.deduplicated).toBe(0); + + // Second retry: DO deduplicates e1, fannedOut remains 1. + const secondRetry = await post(); + expect(secondRetry.status).toBe(200); + const secondBody = (await secondRetry.json()) as { + fanout: Record; + }; + expect(secondBody.fanout["set-1"]?.fannedOut).toBe(1); + expect(secondBody.fanout["set-1"]?.deduplicated).toBe(1); + }); +});