Skip to content

fix: deleted events, undefined perKey keys, uncapped fan-out errors and defer opt-out - #98

Merged
dillonstreator merged 5 commits into
mainfrom
fix/orphans-keys-defer
Nov 28, 2026
Merged

dillonstreator merged 5 commits into
mainfrom
fix/orphans-keys-defer

Conversation

@dillonstreator

@dillonstreator dillonstreator commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

What was wrong

Three ways one bad delivery could stop more than itself, and one documented defer behavior that didn't exist:

  1. A delivery whose event was deleted crashed or wedged processors (TXOB-RES-001, Medium). Only Postgres cascades event deletes. The README tells MongoDB, Redis and DynamoDB users to delete events themselves, and nothing says to wait for pending deliveries first.
    • MongoDB: the claim returned the delivery with event: undefined. runDelivery read event.correlation_id outside any try, and the fire-and-forget promise turned that into an unhandled rejection. Every processor exited with code 1, again on every restart, and the attempt cap never ran.
    • Redis: the claim script leased and counted an attempt for the whole batch, then JSON.parse(undefined) threw for the batch. In the PoC all 5 deliveries sat at 9 attempts against a cap of 5; none ran and none died.
    • DynamoDB: orphans were dropped from the result after being leased, so they were leased again forever.
  2. A perKey key function that returns undefined blocked every handler of the event forever (TXOB-CONS-003, Medium). Its type is string | null | undefined, and key: (e) => e.data.accountId with an optional field returns undefined. Fan-out rejected it, and the event was never fanned out, so the event's other handlers never ran either.
  3. Fan-out errors had no cap. A priority, key or defer function that throws, or returns an invalid value, leaves the event unfanned so it is retried. That much is intended and tested. But it was retried forever, with an error log every leaseMs as the only signal.
  4. defer opt-out (TXOB-DOC-002, Low). README and handlers.ts say a handler's defer function sees event.defer_until, "so a handler can opt out of honoring it". Fan-out never called the function once defer_until was set.

What changed

  • Deleted events. MongoDB, Redis (inside the claim script) and DynamoDB mark such a delivery dead during the claim, fenced by the new lease, with last_error { name: "TxOBEventMissingError", message: "event '<id>' not found" }. They don't return it. The processor marks dead any delivery a (custom) store returns without its event, and logs it. It also catches anything that escapes runDelivery, so a store bug can't become an unhandled rejection again. Postgres is unchanged: its foreign key already deletes the delivery. The README retention notes now say to delete events only once none of their deliveries is pending.
  • undefined key now means no key, like null. Type and runtime agree.
  • Fan-out cap. A failing priority/key/defer function still leaves the event unfanned and retried, as the existing tests require. Each fan-out attempt now counts against the failing handler's retry.maxAttempts. When that's used up, the event fans out: the other handlers get normal deliveries, and the failing handler's delivery is created dead with the error as last_error. That's logged at error level and counted in the delivery telemetry as dead. TxOBNewDelivery gains an optional error, which all five stores honor (dead, never claimable). onDeliveryDead is not called for these, because no transaction is open at fan-out. This is documented.
  • defer functions are called for every event. A non-null result is used. null/undefined keeps the publisher's defer_until. A static defer is still overridden by publish.
  • New exported helper eventMissingError(eventId) for custom stores.
  • README, MIGRATING (0.6 → 0.7), JSDoc, changeset.

Compatibility

  • Stored data: no schema change. Postgres completeFanout sets status, last_error and completed_at on insert, which are existing columns. Redis's completeFanout script takes one more argument per delivery. Each processor sends its own script, so mixed versions during a rollout are fine.
  • Public types: additive. TxOBNewDelivery.error? and eventMissingError are new, and recordDelivery is internal. Custom stores must honor TxOBNewDelivery.error, or a capped delivery would be created pending and run without its key. That's called out in MIGRATING, and the contract test "creates deliveries that carry an error dead, and never claims them" checks it.
  • Behavior changes: (a) a defer function that returns a value for an event published with defer used to be ignored and now wins. A function that wants the publisher to win returns null when event.defer_until is set. The existing unit test's fromEvent handler already does that, and it still passes. (b) After maxAttempts fan-out attempts, a broken priority/key/defer dead-letters that handler instead of blocking the event forever.
  • Semver: minor.

How it was tested

Real backends in temporary containers: Postgres 17, MongoDB 9 replica set, Redis 8, DynamoDB Local.

  • pnpm install --frozen-lockfile, pnpm test:prepare, pnpm typecheck, pnpm build (ESM + CJS): pass.
  • Full suite: 610 passed, 9 skipped (the delete test is skipped on memory and the 8 ORM setups, whose harnesses have no event delete; baseline on main: 557/557). One earlier full run on this branch had a 5 s timeout in the existing Prisma "doesn't let one key's backlog starve other keys" test (it publishes 2,505 events). It passed in isolation 3 times and in the next full run; this PR doesn't touch the code it exercises**.
  • New contract tests run on every store (memory, Postgres, 8 Postgres ORM adapter setups, MongoDB, 3 Redis clients, DynamoDB):
    • marks deliveries whose event was deleted dead, and keeps processing. Uses a per-key limited handler, so the Redis keyed queue, the Mongo lock path and the DynamoDB limiter are all exercised. Memory has no delete, so it's skipped there. On Postgres the delivery is gone with its event.
    • creates deliveries that carry an error dead, and never claims them (store level).
    • creates a delivery dead once its concurrency key has failed for all its attempts, without holding up the other handlers. Also covers the undefined key.
    • lets a handler's defer function override the publish-time defer.
    • Unit tests: the cap after 2 fan-out attempts through lease expiry, and a store that returns a delivery without its event.
  • Before/after: with src/ reverted, 28 of the new test runs fail. The MongoDB, Redis and DynamoDB delete tests fail; the Postgres one passes because of the cascade. With the fix, all pass.
  • Audit PoCs: poc-mongo-orphan.mjs now ends with "still alive after 2s", exit code 0 (it was exit code 1). poc-redis-orphan.mjs: the other 4 events deliver, the orphan has 0 attempts and is dead, and no poll errors are logged. poc-undefined-key.mjs: both handlers run, and the event is fanned out on the first attempt.

For the reviewer to decide

  • defer precedence. I made the documented opt-out real, rather than deleting the sentence from the docs. That changes behavior for defer functions that return a value for events published with defer. The feature shipped in 0.6.0 three weeks ago. If you'd rather keep "publish always wins", revert ffb5d60 and I'll fix the docs instead.
  • The cap uses the handler's retry.maxAttempts, rather than a new option. Fan-out attempts happen once per leaseMs (30 s by default), so a broken key dead-letters after about 2.5 minutes by default.
  • Dead at fan-out, without onDeliveryDead. The alternative I rejected was re-running the fan-out functions at every claim to route these through the normal dead path, which does run the hook. It would evaluate them on every attempt and couple this PR to the schema round-trip PR.
  • fix: store event data as published and validate it in the form the store keeps #97 merged while this was open. I merged main into this branch. The fan-out loop now passes the parsed event to computeDelivery, and the MIGRATING notes are combined. Full suite after the merge: 655 passed, 9 skipped.

Not in this PR

  • Hung handlers holding their lease (RES-002): documented behavior per the verification. It's left out here; the docs PR adds a note.
  • A missing local renewal discarding a result that may still be committable (CONS-004): it changes lease-loss semantics, so it's not a small, unambiguous fix.

… or wedging

Only Postgres cascades event deletes to deliveries. On MongoDB a pending
delivery whose event was deleted reached the processor without an event
and crashed it through an unhandled rejection, on every restart. On
Redis the claim script leased the whole batch and then failed to parse
the missing event, so attempts climbed and nothing ran or died. DynamoDB
dropped such deliveries from the result, so they were leased forever.

Each of these stores now marks the delivery dead in the claim, with an
"event '...' not found" error. The processor marks dead any delivery a
store returns without its event, and catches unexpected errors from a
running delivery instead of leaving an unhandled rejection.
…er handler

The key function's type allows undefined, but fan-out rejected it and
left the event unfanned, so none of its handlers ever ran. undefined now
means no key, like null.

A priority, key or defer function that throws or returns an invalid
value still leaves the event unfanned and retried, but only for the
failing handler's retry.maxAttempts fan-out attempts. After that, the
event fans out: the failing handler's delivery is created dead with the
error as last_error (TxOBNewDelivery gains an optional error that
stores honor), and the other handlers run.
The docs said a handler's defer function sees event.defer_until and can
opt out of it, but fan-out never called the function when defer_until
was set. Call it for every event: its result is used, and returning
null or undefined keeps the publisher's defer_until. A static defer is
still overridden by publish.
@codecov

codecov Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.56962% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 96.04%. Comparing base (b9a22f4) to head (8d2729e).

Files with missing lines Patch % Lines
src/processor.ts 89.09% 6 Missing ⚠️
test/contract.ts 98.55% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #98      +/-   ##
==========================================
- Coverage   96.13%   96.04%   -0.10%     
==========================================
  Files          34       34              
  Lines        2355     2478     +123     
  Branches      478      497      +19     
==========================================
+ Hits         2264     2380     +116     
- Misses         74       81       +7     
  Partials       17       17              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Resolve the fan-out loop against the schema round-trip change from #97:
computeDelivery now receives the parsed event, and events whose stored
data fails the schema still get default deliveries. Both 0.6 -> 0.7
migration notes are kept.
@dillonstreator
dillonstreator merged commit 2e4f459 into main Nov 28, 2026
2 of 4 checks passed
@dillonstreator
dillonstreator deleted the fix/orphans-keys-defer branch November 28, 2026 19:47
@github-actions github-actions Bot mentioned this pull request Nov 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant