From 26320ba7fc6c115fd98f0a35c992eedc6dbbaf7c Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Fri, 13 Nov 2026 21:45:07 -0600 Subject: [PATCH] fix(pm-stack): composite (ts, event_id) cursor for decision-events read-back (#9614) --- pm-stack/decision-events-worker/README.md | 10 +- pm-stack/decision-events-worker/src/events.ts | 37 ++++++ pm-stack/decision-events-worker/src/index.ts | 48 +++++-- .../test/events.test.ts | 36 +++++- .../test/pagination.test.ts | 117 ++++++++++++++++++ 5 files changed, 236 insertions(+), 12 deletions(-) create mode 100644 pm-stack/decision-events-worker/test/pagination.test.ts diff --git a/pm-stack/decision-events-worker/README.md b/pm-stack/decision-events-worker/README.md index 14917584c1..3c85cdd52c 100644 --- a/pm-stack/decision-events-worker/README.md +++ b/pm-stack/decision-events-worker/README.md @@ -19,11 +19,19 @@ land in three places, all idempotent on `eventId`: | Route | Auth | Purpose | | ---------------------------------------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `POST /events` (alias `/webhook`) | shared secret | Accept an event batch: `{events: [...]}` (or a bare array / single event). Stores new events in D1, fans them out to each set's Durable Object, returns `{accepted, inserted, duplicates, errors, fanout}`. | -| `GET /sets//events?limit=&after=` | shared secret | Read a set's events back from D1, in `ts` order. | +| `GET /sets//events?limit=&after=` | shared secret | Read a set's events back from D1, in `(ts, event_id)` order; the response's `nextAfter` is the composite cursor for the next page (see below). | | `GET /sets//state` | shared secret | The set's Durable Object state merged with D1's stored count. | | `GET /sets//stream` | shared secret | WebSocket upgrade routed to the set's Durable Object; subscribers get `{type:"decision-events", setId, events}` per new batch, plus the current state on connect. Send `ping` → `pong`, `state` → current state. | | `GET /health` | none | Liveness + whether the webhook secret is configured. | +Read-back pagination: pass the previous page's `nextAfter` value as +`after` to get the next page. The cursor is composite — `|`, +the (ts, event_id) pair of the page's last event — so paging returns +every event exactly once, including groups of events that share one +timestamp (#9614). `nextAfter` is null on an empty page. A bare ISO +timestamp is still accepted as `after` with its legacy meaning +(strictly after that ts, skipping any remaining same-ts events). + Auth is the shared secret as `Authorization: Bearer ` or the `X-Webhook-Secret` header, compared in constant time. With no secret configured the Worker fails closed (503 on every data route). diff --git a/pm-stack/decision-events-worker/src/events.ts b/pm-stack/decision-events-worker/src/events.ts index ac1b759e23..0899920d71 100644 --- a/pm-stack/decision-events-worker/src/events.ts +++ b/pm-stack/decision-events-worker/src/events.ts @@ -133,3 +133,40 @@ export function groupBySet(events: DecisionSetEvent[]): Map/events (#9614). + * + * Pagination orders by (ts, event_id), so the cursor must carry BOTH + * components: a bare-ts cursor (`ts > after`) makes every event after + * the first page boundary inside a same-ts group unreachable. The + * wire form is `|` — ts never contains `|`, so splitting + * at the first `|` is unambiguous even if an eventId contains one. + * A bare ISO timestamp is still accepted as a legacy cursor and keeps + * its original meaning (strictly after that ts). */ +export interface EventsCursor { + ts: string; + eventId: string | null; +} + +export function encodeEventsCursor(cursor: { ts: string; eventId: string }): string { + return `${cursor.ts}|${cursor.eventId}`; +} + +export function parseEventsCursor(raw: string): { ok: true; value: EventsCursor } | { ok: false; error: string } { + const sep = raw.indexOf("|"); + if (sep === -1) { + if (!isIsoTimestamp(raw)) { + return { ok: false, error: "after must be an ISO timestamp or a | cursor" }; + } + return { ok: true, value: { ts: raw, eventId: null } }; + } + const ts = raw.slice(0, sep); + const eventId = raw.slice(sep + 1); + if (!isIsoTimestamp(ts)) { + return { ok: false, error: "after cursor ts must be an ISO timestamp" }; + } + if (!ID_RE.test(eventId)) { + return { ok: false, error: "after cursor eventId is invalid" }; + } + return { ok: true, value: { ts, eventId } }; +} diff --git a/pm-stack/decision-events-worker/src/index.ts b/pm-stack/decision-events-worker/src/index.ts index 18a3209a17..d34e18bcfc 100644 --- a/pm-stack/decision-events-worker/src/index.ts +++ b/pm-stack/decision-events-worker/src/index.ts @@ -10,8 +10,13 @@ // event), stores them in D1 (INSERT OR IGNORE on event_id — // redelivery is a no-op), then hands each set's NEW events to that // set's Durable Object for per-set fan-out. -// GET /sets//events?limit=&after= -// Authenticated read-back of a set's events from D1, in ts order. +// GET /sets//events?limit=&after= +// Authenticated read-back of a set's events from D1, in +// (ts, event_id) order. `after` is the composite cursor the +// previous page returned as `nextAfter` (|); a bare +// is still accepted with its legacy meaning (ts > after). +// The response's `nextAfter` is the cursor for the following +// page, or null when the page is empty. // GET /sets//state // Authenticated: the set's Durable Object state (events fanned // out, last event, live subscriber count) merged with D1's count. @@ -27,7 +32,14 @@ // batches to the set's WebSocket subscribers (hibernatable sockets, // so idle sets cost nothing). D1 stays the durable store; the object // holds coordination state only. -import { groupBySet, isAuthorized, parseEventBatch, type DecisionSetEvent } from "./events.ts"; +import { + encodeEventsCursor, + groupBySet, + isAuthorized, + parseEventBatch, + parseEventsCursor, + type DecisionSetEvent, +} from "./events.ts"; export interface Env { DB: D1Database; @@ -189,12 +201,26 @@ async function handlePostEvents(request: Request, env: Env): Promise { async function handleGetEvents(url: URL, env: Env, setId: string): Promise { const limitRaw = Number(url.searchParams.get("limit") ?? "200"); const limit = Number.isFinite(limitRaw) ? Math.min(Math.max(Math.trunc(limitRaw), 1), 1000) : 200; - const after = url.searchParams.get("after"); - const query = after - ? "SELECT event_id, set_id, question_ref, type, payload, ts FROM decision_set_events WHERE set_id = ? AND ts > ? ORDER BY ts, event_id LIMIT ?" - : "SELECT event_id, set_id, question_ref, type, payload, ts FROM decision_set_events WHERE set_id = ? ORDER BY ts, event_id LIMIT ?"; - const stmt = env.DB.prepare(query); - const bound = after ? stmt.bind(setId, after, limit) : stmt.bind(setId, limit); + const afterRaw = url.searchParams.get("after"); + const select = "SELECT event_id, set_id, question_ref, type, payload, ts FROM decision_set_events WHERE set_id = ?"; + let query = `${select} ORDER BY ts, event_id LIMIT ?`; + let bound = env.DB.prepare(query).bind(setId, limit); + if (afterRaw) { + const parsed = parseEventsCursor(afterRaw); + if (!parsed.ok) return jsonError(400, parsed.error); + const { ts, eventId } = parsed.value; + if (eventId !== null) { + // Composite cursor (#9614): resume strictly after the (ts, + // event_id) pair, so events sharing the page-boundary ts are + // not skipped. + query = `${select} AND (ts > ? OR (ts = ? AND event_id > ?)) ORDER BY ts, event_id LIMIT ?`; + bound = env.DB.prepare(query).bind(setId, ts, ts, eventId, limit); + } else { + // Legacy bare-ts cursor: original meaning, ts strictly after. + query = `${select} AND ts > ? ORDER BY ts, event_id LIMIT ?`; + bound = env.DB.prepare(query).bind(setId, ts, limit); + } + } const { results } = await bound.all>(); const events = (results ?? []).map((row) => ({ eventId: row.event_id, @@ -204,7 +230,9 @@ async function handleGetEvents(url: URL, env: Env, setId: string): Promise ({ eventId, @@ -68,3 +76,29 @@ describe("groupBySet", () => { expect(groups.get("set-1")?.map((e) => e.eventId)).toEqual(["e1", "e3"]); }); }); + +describe("events cursor (#9614)", () => { + test("round-trips a composite (ts, event_id) cursor", () => { + const cursor = encodeEventsCursor({ ts: "2026-11-12T10:00:00.000Z", eventId: "e2" }); + expect(cursor).toBe("2026-11-12T10:00:00.000Z|e2"); + const parsed = parseEventsCursor(cursor); + expect(parsed.ok).toBe(true); + if (parsed.ok) expect(parsed.value).toEqual({ ts: "2026-11-12T10:00:00.000Z", eventId: "e2" }); + }); + test("eventIds containing the separator still parse (split at the first |)", () => { + const parsed = parseEventsCursor("2026-11-12T10:00:00.000Z|e|2"); + expect(parsed.ok).toBe(true); + if (parsed.ok) expect(parsed.value.eventId).toBe("e|2"); + }); + test("a bare timestamp is a legacy cursor with no eventId", () => { + const parsed = parseEventsCursor("2026-11-12T10:00:00.000Z"); + expect(parsed.ok).toBe(true); + if (parsed.ok) expect(parsed.value).toEqual({ ts: "2026-11-12T10:00:00.000Z", eventId: null }); + }); + test("rejects malformed cursors", () => { + expect(parseEventsCursor("not-a-date").ok).toBe(false); + expect(parseEventsCursor("2026-11-12T10:00:00.000Z|").ok).toBe(false); + expect(parseEventsCursor("not-a-date|e1").ok).toBe(false); + expect(parseEventsCursor("2026-11-12T10:00:00.000Z|has space").ok).toBe(false); + }); +}); diff --git a/pm-stack/decision-events-worker/test/pagination.test.ts b/pm-stack/decision-events-worker/test/pagination.test.ts new file mode 100644 index 0000000000..d8a3e3118f --- /dev/null +++ b/pm-stack/decision-events-worker/test/pagination.test.ts @@ -0,0 +1,117 @@ +// Read-back pagination regression (#9614): paging through a group of +// events that share one timestamp must return every event exactly +// once. Exercises the real Worker fetch handler and its real SQL +// against an in-memory SQLite database standing in for D1 (D1 is +// SQLite-backed; the fake runs the handler's actual query strings). +import { Database } from "bun:sqlite"; +import { describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import worker from "../src/index.ts"; + +const SECRET = "test-secret"; +const TS = "2026-11-12T10:00:00.000Z"; + +class FakeStatement { + constructor( + private db: Database, + private sql: string, + private args: unknown[] = [], + ) {} + bind(...args: unknown[]): FakeStatement { + return new FakeStatement(this.db, this.sql, args); + } + async all(): Promise<{ results: T[] }> { + return { results: this.db.query(this.sql).all(...(this.args as never[])) as T[] }; + } + async first(): Promise { + return (this.db.query(this.sql).get(...(this.args as never[])) as T) ?? null; + } +} + +class FakeD1 { + constructor(private db: Database) {} + prepare(sql: string): FakeStatement { + return new FakeStatement(this.db, sql); + } +} + +function makeEnv(rows: [string, string, string][]): unknown { + const db = new Database(":memory:"); + const schema = readFileSync(join(import.meta.dir, "..", "schema.sql"), "utf8"); + db.exec(schema); + const insert = db.query( + "INSERT INTO decision_set_events (event_id, set_id, question_ref, type, payload, ts) VALUES (?, ?, ?, ?, ?, ?)", + ); + // Inserted out of order on purpose: ordering is the query's job. + for (const [eventId, setId, ts] of rows) { + insert.run(eventId, setId, "ledger-1#1", "question-answered", JSON.stringify({ optionId: "a" }), ts); + } + return { DB: new FakeD1(db), SET_EVENTS: {}, WEBHOOK_SECRET: SECRET }; +} + +async function getEvents( + env: unknown, + query: string, +): Promise<{ + status: number; + body: { count?: number; events?: { eventId: string }[]; nextAfter?: string | null; error?: string }; +}> { + const res = await worker.fetch( + new Request(`http://worker.test/sets/set-1/events?${query}`, { + headers: { Authorization: `Bearer ${SECRET}` }, + }), + env as never, + ); + return { status: res.status, body: await res.json() }; +} + +const ROWS: [string, string, string][] = [ + ["e3", "set-1", TS], + ["e1", "set-1", TS], + ["e5", "set-1", "2026-11-12T11:00:00.000Z"], + ["e2", "set-1", TS], + ["e4", "set-1", "2026-11-12T11:00:00.000Z"], + ["other-set-event", "set-2", TS], +]; + +describe("GET /sets//events pagination (#9614)", () => { + test("pages through a same-timestamp group: every event exactly once, in (ts, event_id) order", async () => { + const env = makeEnv(ROWS); + const seen: string[] = []; + let after: string | null = null; + for (let page = 0; page < 10; page++) { + const q = after === null ? "limit=2" : `limit=2&after=${encodeURIComponent(after)}`; + const { status, body } = await getEvents(env, q); + expect(status).toBe(200); + const ids = (body.events ?? []).map((e) => e.eventId); + if (ids.length === 0) { + expect(body.nextAfter).toBeNull(); + break; + } + seen.push(...ids); + after = body.nextAfter ?? null; + expect(after).not.toBeNull(); + // A page that ends inside the same-ts group must hand back the + // composite cursor, not the bare timestamp. + if (page === 0) expect(after).toBe(`${TS}|e2`); + } + expect(seen).toEqual(["e1", "e2", "e3", "e4", "e5"]); + expect(new Set(seen).size).toBe(seen.length); + }); + + test("legacy bare-ts after keeps its original meaning (strictly after that ts)", async () => { + const env = makeEnv(ROWS); + const { status, body } = await getEvents(env, `limit=10&after=${encodeURIComponent(TS)}`); + expect(status).toBe(200); + expect((body.events ?? []).map((e) => e.eventId)).toEqual(["e4", "e5"]); + }); + + test("a malformed after cursor is a 400, not a silent first page", async () => { + const env = makeEnv(ROWS); + for (const bad of ["not-a-date", `${TS}|`, `not-a-date|e1`, `${TS}|has space`]) { + const { status } = await getEvents(env, `after=${encodeURIComponent(bad)}`); + expect(status).toBe(400); + } + }); +});