From 965937352dc0a3c705c56524b476f70440c52b20 Mon Sep 17 00:00:00 2001 From: Julian Cuni Date: Sun, 11 Oct 2026 18:58:10 +0200 Subject: [PATCH] fix(readers): never replay a failed read decision; bound the recent-reads map Follow-up to ec01591. A first decision that threw was cached and replayed to repeats inside the window, and the telemetry hook on it had no rejection handler, so one throwing flow became an unhandled rejection per repeat. A failed decision is now forgotten (the next read decides afresh) and the hook handles rejection. The recent-reads map prunes above 512 entries and never exceeds 4096, whatever a misbehaving reader sends. --- .../server/src/read-dispatch-debounce.test.ts | 28 ++++++++++++++++++ apps/server/src/read-dispatch.ts | 29 ++++++++++++++++--- 2 files changed, 53 insertions(+), 4 deletions(-) diff --git a/apps/server/src/read-dispatch-debounce.test.ts b/apps/server/src/read-dispatch-debounce.test.ts index 4ae3a6c..b4f2651 100644 --- a/apps/server/src/read-dispatch-debounce.test.ts +++ b/apps/server/src/read-dispatch-debounce.test.ts @@ -110,6 +110,34 @@ describe("read-dispatch same-code debounce", () => { expect(ledger()).toHaveLength(2); }); + it("a FAILED first decision is not replayed: the repeat decides afresh, no unhandled rejection", async () => { + seed({}); + // Make the exit flow blow up once (e.g. a signer hiccup), then work. + const log = makeLog(db); + const flaky = new ExitFlow(db, log, silentLogger()); + let calls = 0; + const orig = flaky.handleAt.bind(flaky); + flaky.handleAt = async (...args: Parameters) => { + calls++; + if (calls === 1) throw new Error("signer busy"); + return orig(...args); + }; + const d2 = new ReadDispatcher(db, flaky, new SubscriptionFlow(db, log, silentLogger()), silentLogger()); + const rejections: unknown[] = []; + const onUnhandled = (r: unknown) => rejections.push(r); + process.on("unhandledRejection", onUnhandled); + try { + await expect(d2.dispatch(read("00000000000"))).rejects.toThrow("signer busy"); + const second = await d2.dispatch(read("00000000000")); // inside the window, but nothing to replay + expect(second.accepted).toBe(false); // a real decision (refused: no session), signed once + expect(ledger()).toHaveLength(1); + await new Promise((r) => setTimeout(r, 10)); + expect(rejections).toEqual([]); + } finally { + process.off("unhandledRejection", onUnhandled); + } + }); + it("a repeat arriving while the first read is still deciding gets the SAME decision", async () => { const d = seed({}); const [a, b] = await Promise.all([d.dispatch(read("00000000000")), d.dispatch(read("00000000000"))]); diff --git a/apps/server/src/read-dispatch.ts b/apps/server/src/read-dispatch.ts index baa768c..17268c1 100644 --- a/apps/server/src/read-dispatch.ts +++ b/apps/server/src/read-dispatch.ts @@ -48,6 +48,11 @@ import { relayForDevice, type ResolvedRelay } from "./device-resolve.js"; /** Default same-code debounce when a reader's config has none (ms). */ export const DEFAULT_READ_DEBOUNCE_MS = 5000; +/** Recent-reads map housekeeping: prune above the soft cap, never exceed the hard cap, and + * treat any entry older than this as expired whatever the reader's configured window. */ +const RECENT_READS_SOFT_CAP = 512; +const RECENT_READS_HARD_CAP = 4096; +const RECENT_READS_MAX_AGE_MS = 60_000; interface ReaderConfig { readonly debounceMs?: number | string | null; @@ -104,19 +109,35 @@ export class ReadDispatcher { this.#logger.info( `read debounced: '${e.value}' (${e.kind}) again on ${e.deviceId} after ${sinceMs}ms (window ${debounceMs}ms) — first verdict replayed`, ); - void prev.outcome.then((o) => this.#recordDebounced(e, sinceMs, debounceMs, o)); + prev.outcome.then( + (o) => this.#recordDebounced(e, sinceMs, debounceMs, o), + () => undefined, // the first decision failed: the caller gets that rejection, not us + ); return prev.outcome; } const outcome = this.#decide(resolved, e); if (debounceMs > 0) { this.#recent.set(key, { at: now, outcome }); - if (this.#recent.size > 512) { - for (const [k, r] of this.#recent) if (now - r.at >= debounceMs) this.#recent.delete(k); - } + // A failed decision is NOT a verdict to replay — forget it so the next read retries. + outcome.catch(() => this.#recent.delete(key)); + this.#pruneRecent(now); } return outcome; } + /** Keep the recent-reads map small: drop expired entries, and if a flood of distinct + * values inside one window still leaves it over the cap, drop the oldest. Bounded + * memory whatever a misbehaving (or hostile) reader sends. */ + #pruneRecent(now: number): void { + if (this.#recent.size <= RECENT_READS_SOFT_CAP) return; + for (const [k, r] of this.#recent) if (now - r.at >= RECENT_READS_MAX_AGE_MS) this.#recent.delete(k); + while (this.#recent.size > RECENT_READS_HARD_CAP) { + const oldest = this.#recent.keys().next().value; // insertion order = oldest first + if (oldest === undefined) break; + this.#recent.delete(oldest); + } + } + /** The actual routing of a FRESH read (not a debounced repeat). */ async #decide(resolved: ResolvedRelay, e: DeviceReadEvent): Promise { const sub = this.#subscription.match(e);