npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@fabricorg/webhook-delivery

v0.3.3

Published

Outbound webhook subscription delivery for @fabricorg/platform-host: the fabric.webhook-delivery.v1 wire contract, persistence and egress projections, response classification, retry schedule, and the store, signer, resolver, transport, admission and autho

Readme

@fabricorg/webhook-delivery

Outbound webhook subscription delivery fed by the @fabricorg/platform-host outbox, as decided in ADR 0018.

Install and requirements

pnpm add @fabricorg/webhook-delivery@^0.1.0 @fabricorg/platform@^1.7.0 @fabricorg/platform-host@^7.3.0
  • Peers. @fabricorg/platform ^1.7.0 and @fabricorg/platform-host ^7.3.0. Platform 1.7.0 defines ActionDefinition.admitSubmission and Host 7.3.0 runs it before it persists submission parameters. Every operator action declares the check, so against an older Host the actions refuse at execution as admission_not_enforced (Secrets and parameters). @fabricorg/platform is imported for types only.
  • Runtime. Node.js 22 or newer; run 22.23.4, 24.22.1, or 26.12.1 or newer in the same release line in production for the Brotli decoder fix in CVE-2026-111497; Node 20 is end-of-life and has no fixed release. The package ships ESM and CommonJS builds with two entry points: @fabricorg/webhook-delivery and @fabricorg/webhook-delivery/node (the Node transport and DNS lookup). It has no runtime dependencies; the PostgreSQL stores take an injected pool such as pg.Pool.
  • Storage. Production uses the PostgreSQL stores, and ensureSchema() must run on both before a worker or action uses them (PostgreSQL stores). The memory stores are for tests and explicit local development.
  • Host features to enable (ADR 0018, "Adoption gates"): the Host outbox relay on a transactional store, with createWebhookFanOutPublisher() as its publisher; outbox dead-letter requeue (requeueOutboxDeadLetter with authorizeOutboxRequeue); the opt-in envelope actor (outbox.includeActor) when a subscription's admission needs the actor; and Host 7.3.0's submission admission, which needs no option or wiring.
  • No scheduler. The package starts none. The application calls runWebhookFanOutCycle() and runWebhookDeliveryCycle() from its own workers.

The docs-app page Webhook delivery shows the composition root end to end.

What is here

  • Wire contract. renderWebhookDeliveryBodyV1() renders the fabric.webhook-delivery.v1 body in the ADR's field order; buildWebhookRequestHeaders() and webhookSignedContentV1() give the headers and the exact string a v1 signer MACs: v1= + hex(HMAC-SHA256(secret, "<unix-seconds>.<raw-body>")).
  • Persistence projection. projectWebhookFanOutJob() reduces a Host envelope to a fan-out job holding metadata, the allowlisted payload fields and declared admission facts only. How it reads the envelope is described under Security properties.
  • Egress projection. projectWebhookEgressPayload() lets a payload out only for allowlisted event types, never for a restricted event without opt-in, and for a scoped type only when the injected predicate returns true; otherwise the body is metadata-only (payload: null, payloadProjected: false).
  • Classification. classifyWebhookDeliveryObservation() implements decision 10's table, with a bounded Retry-After on 429. 401 and 403 are retryable with receiverActionLikely: true.
  • Retry schedule. createWebhookRetryDelay() gives 1m, 5m, 15m, 1h, 6h, 12h, 24h with jitter bounded to [base, base * (1 + jitterRatio)) from an injected random source.
  • Limits. resolveWebhookDeliveryLimits() rejects any deadline, count, delay, jitter, Retry-After cap or replay horizon that is not positive and finite with a WebhookDeliveryConfigError.
  • Stores. MemoryWebhookSubscriptionStore and MemoryWebhookDeliveryStore, for tests and explicit local development, and PostgresWebhookSubscriptionStore and PostgresWebhookDeliveryStore for production. See Stores.
  • Delivery cycle. runWebhookDeliveryCycle() claims intents, re-reads subscription state and configuration, runs delivery authorization, signs each attempt, hands it to the transport and settles it. See Delivery.
  • Governed actions. createWebhookDeliveryModule() builds the operator mutations (subscription create, update, pause, resume and delete; staged and emergency rotation; delivery-intent and fan-out-job requeue; actor enrichment) as a Platform FabricModule. See Governed actions.
  • Ports. WebhookSubscriptionStore, WebhookSubscriptionWriter, WebhookDeliveryStore, WebhookSigner, WebhookDestinationResolver, WebhookTransport, WebhookEventAdmission, WebhookDeliveryAuthorization, WebhookClock and WebhookRetryDelay. Every awaited call takes an absolute deadline and an AbortSignal.

Stored diagnostics, denial reasons and attempt outcomes are typed as codes from fixed sets (WEBHOOK_*_CODES), not free strings, and the decision normalizers turn an unknown code into unavailable rather than storing it.

Stores

Ports

  • WebhookSubscriptionStore is the read port the fan-out and delivery cycles depend on: revisions by recordedAt, the current status (with statusSinceRevision, the revision that status began at) and configuration, and a subscription's revision history. It has no write method; a type test (tests/ports.test.ts) checks that.
  • WebhookSubscriptionWriter is the write port for the governed actions (PR 9): create, pattern change, pause, resume, delete and configuration replacement. Each appends one eligibility revision or one configuration version. A revision takes effect at the store's clock, or at the previous revision's start if the clock is behind it, so intervals do not invert. The store checks each transition against its own current state. An optional expectedRevision or expectedVersion makes the write a compare-and-set. Stored revisions are never changed: a revision's effectiveUntil is derived from its successor's start when read.
  • WebhookDeliveryStore holds fan-out jobs, intents, denials, tombstones, the attempt log and requeue evidence. Insert-if-absent, fenced leases and compare-and-set requeue are as ADR 0018 describes. Refusals the caller is expected to handle are results: already_present, lease_lost, past_horizon, stale, not_dead_letter, not_found. Malformed input, a record that does not match its parent, a reused deliveryId, a call aborted or past its deadline, and a failing store clock throw a WebhookStoreError with a fixed code (WEBHOOK_STORE_ERROR_CODES). Nothing is written in either case. The attempt log has three writes: appendAttempt (a whole entry, fenced), beginAttempt (fenced, before a handoff) and finishAttempt (its outcome, not fenced, bound to a receipt); see The attempt log. renewFanOutJobLease and renewDeliveryIntentLease (PR 8) extend a lease the caller still holds, fenced like every other lease write and never past the record's processing deadline; see Lease renewal. enrichFanOutJobActor (PR 9) repairs a legacy job's actor as a compare-and-set on the job's fence, and refuses not_enrichable, actor_present and actor_suppressed too; see Governed actions.

Requeue names one dead letter. A job or intent carries a fence that each claim and each applied requeue advances. A requeue request must carry the fence the operator read (WebhookRequeueRequest.expectedFence). The store compares it in the same atomic step as the status check, the transition and the evidence append, and refuses a mismatch as stale. Two requests built from one read therefore apply at most once. A request read before the record was requeued, re-run and dead-lettered again does not apply to the new dead letter, even though its status is dead_letter once more; a fresh read does. This mirrors Host's expectedLeaseToken on requeueOutboxDeadLetter. Contract cases: "two requeues built from one read …" and "a request read before a requeue, re-run and second dead letter is stale …".

Pause and pending intents. Pause, resume and delete write a subscription revision only. The two stores need not share a database, so the governed action (PR 9) does the second step itself: it calls cancelPendingIntents with the same scope and subscriptionId once the revision is written, and passes the revision it wrote as beforeRevision. Only pending intents bound to an earlier eligibility revision are cancelled. A pause cleanup delayed past a resume therefore leaves alone the intents written under the resumed revision (contract case "a pause cleanup delayed past a resume …"). The contract case "pause then cancelPendingIntents …" runs that sequence. That step is a bulk cleanup, not the guarantee, and nothing depends on it succeeding. The guarantee is the delivery cycle's pre-handoff readSubscription check: it cancels an intent while the subscription is paused or deleted, and while it is active with a statusSinceRevision above the intent's eligibilityRevision, which is how an intent of an interval a pause ended looks after a resume. See Pause and resume are enforced at dispatch.

Replay horizon (R5)

Decision. The horizon is one configured duration, replayHorizonMs. It defaults to 30 days and is validated as a positive whole number of milliseconds. resolveWebhookDeliveryLimits() also requires it to be at least fanOutDeadlineMs + deliveryDeadlineMs. The store constructor checks again that it is a positive whole number within the Date range (WEBHOOK_MAX_REPLAY_HORIZON_MS). It is measured from the event's recordedAt, which Host stamps with its own clock and which every job, intent and denial carries; the store copies it onto an intent from the parent job as eventRecordedAt.

The store reads its own clock. Its horizon floor is the later of now - horizon and the highest cutoff any purge has used. Four rules follow from that floor:

  • A fan-out job insert, an intent insert, a denial insert, a job requeue, an intent requeue and an actor enrichment (PR 9) are refused as past_horizon when the event's recordedAt is earlier than the floor. The job insert checks the horizon before uniqueness. A replay of an old event is therefore past_horizon whether or not its job is still stored, so the answer does not depend on whether a purge has run.
  • purgeExpiredRecords removes only terminal records (completed or dead-lettered jobs; delivered, dead-lettered or cancelled intents; denials) whose recordedAt is earlier than the floor. Each intent and denial goes with its tombstone. Pending records are never removed; the cycles (PRs 6 and 8) are to move them to a terminal state through their processing deadlines (R4). The attempt log and requeue evidence are audit records, and a purge keeps them.
  • The comparison and the write it guards happen in one atomic step. In the memory store that is one synchronous block with no await (#atomic in src/memory-delivery-store.ts). In the PostgreSQL store it is one transaction that takes the horizon lock first and reads the floor and the clock after it (see PostgreSQL stores).
  • A purge raises the floor in the same step as its removals. The floor follows the clock and can fall if the clock steps backwards, but never below the highest cutoff any purge has used. So a store clock that steps backwards after a purge cannot reopen a purged key.

Why. The hazard is a Host outbox requeue that re-publishes an old event. Stage one calls insertFanOutJob, and if a cleanup had removed the job, insert-if-absent would create a new job and deliver the event again. With the rules above, any key a purge removed has a recordedAt below the floor, and every later insert or requeue of that key compares against at least that floor. Whichever runs first, the replay is refused and nothing inside the horizon is removed. The race cases in tests/store-contract.ts force purge and replay, purge and requeue, and purge and a late fan-out insert into each whole-operation order, and check the outcome. They do not test the atomicity of a check and its write: in the memory stores that rests on the synchronous #atomic block (src/memory-delivery-store.ts:232), and in the PostgreSQL store on the horizon lock, which tests/postgres-live.test.ts tests from inside the transaction. Rejected alternatives: a horizon checked only at the start of a method (it races the purge), a cleanup that tombstones what it removes (the tombstone would itself need a horizon), and per-record retention clocks (two clocks for one decision).

What each record keeps for it.

| Record | Kept until | Removed by | | --- | --- | --- | | Fan-out job (holds the actor source for admission) | terminal and older than the horizon | purge | | Intent and its tombstone | terminal and older than the horizon | purge | | Denial and its tombstone | older than the horizon | purge | | Event erasure markers | retained indefinitely (future-dated inserts are accepted) | none | | Eligibility revisions | never removed | none | | Delivery configuration versions | never removed | none | | Replay request receipts and work items (including terminal outcomes) | never removed by the package (audit/idempotency) | application retention policy | | Attempt log, requeue evidence | never removed by the package (audit) | application retention policy |

The rejection is visible at the store, but the publisher (PR 6) decides what Host sees. A past_horizon from insertFanOutJob should fail the publish with a fixed code, so the Host outbox record dead-letters rather than counting as delivered.

Event erasure

redactEventRecords({ tenantId, spaceId, eventIds }, options) atomically clears job payloads (null), projection flags (false) and admission facts ({}), and replaces intent bodies with metadata-only JSON using the shared serializer. It covers pending and terminal records. It keeps metadata and the identifier-only actor and its recorded causedBy unchanged (tests/caused-by.test.ts and the shared cause store contract case). Input accepts 1–100 distinct identifiers, using the identifier validation below; empty lists and duplicates are refused. Results count newly marked events and rows whose content changed. A repeat scrubs payload reintroduced by older writers; a no-op repeat returns zero counts and preserves fences and leases. Jobs carry the additive erased flag. After the tombstone check, fan-out denies undecided pairs with event_erased without calling admission. Decided pairs keep their metadata-only intents (tests/fan-out.test.ts, “erased events”). event_erased is an additive admission denial code; application admission ports may return it too.

For changed rows, the job fence and pending intent fences advance, and their leases are cleared for immediate reclaim, matching actor enrichment. Old fan-out writes return lease_lost; old delivery beginAttempt returns { begun: false }. A request already handed to transport before commit cannot be recalled. The fence check linearizes at beginAttempt: if begin commits first, its receipt remains valid. A PostgreSQL response may arrive after redaction commits, so this store-only port cannot promise that such an already-authorized handoff occurs before the erasure commit. Stronger transport exclusion requires coordination beyond this port. Status, attempt budgets, availability, attempt logs, outcomes, denials and requeue evidence are preserved. Requeue and actor enrichment keep the redacted fields. These operations do not erase the application's event store or deliveries already received by subscribers. An in-flight attempt can still append its outcome using its receipt, but settlement at the old fence is refused. Its pending intent can then be sent again with the metadata-only body, consistent with at-least-once delivery.

A scoped marker is recorded even when no job exists. Inserts check it inside their atomic step and scrub the new draft/body. PostgreSQL migration 4 adds webhook_event_erasures and an intent index on (tenant_id, space_id, event_id). Run ensureSchema() before the new version serves any traffic: job and intent inserts now read the marker table even when redaction is unused. The migration builds the intent index without CONCURRENTLY, so on an existing deployment every intent write (claims, attempts, settlements, inserts, cancellations) waits until the build finishes, for a time that grows with the intents table. Plan the upgrade for that pause. Redaction takes the horizon EXCLUSIVE lock first, then reads the clock and locks matching jobs in event_id order and intents in delivery_id order using set-based queries. Cancellation also locks intents in delivery_id order. Claims use ordered FOR UPDATE SKIP LOCKED, which does not wait on held rows. Ordinary horizon-checked writers continue to use SHARE. The live “check-to-write serialization” erasure cases exercise both lock orders against inserts.

Do not call redactEventRecords until every instance runs this version. Older instances ignore markers and the erased flag: they can write the payload back after an erasure, deliver it before any repair, and ask admission with the cleared facts, which is the fail-open path event_erased closes. Repeating redaction scrubs rows an older instance wrote (tests/store-contract.ts, “repeat erasure repairs legacy rows”, which runs against PostgreSQL), but it cannot recall what was already delivered. Custom WebhookDeliveryStore implementations break at the type boundary and must implement the new method and its atomicity, marker and fail-closed semantics.

Markers are retained indefinitely. The proposed timestamp expiry proof would require event.recordedAt <= redaction time, but the store accepts future-dated jobs (shared contract: “job claim respects availableAt, lease expiry and limit, oldest first”). A pre-recorded marker could otherwise expire before that event's horizon. Purge does not remove markers or count them in removed. Applications should budget this storage until a future contract supplies a safe upper bound on event time.

The shared tests/store-contract.ts erasure cases cover scoped late inserts, terminal and pending data, stale fences, idempotence, and validation. Attempts, outcomes, denials and requeue evidence contain identifiers, timestamps and closed diagnostic fields, not payload or admission facts (delivery-store-core.ts input readers and evidence builders). Actor evidence retains identifiers; this API is payload erasure, not removal of identifying metadata.

Identifiers and stored fields

Every identifier a store takes is refused as input_invalid if it is empty, longer than 256 UTF-16 code units, contains a control character (U+0000–U+001F, U+007F–U+009F), or contains a lone UTF-16 surrogate. This covers tenant, space, subscription, event, delivery, worker and requester ids. All four stores read every argument through the same per-method readers (src/delivery-store-core.ts, src/subscription-store-core.ts), which call one identifier() (src/store-input.ts), so an identifier one store accepts the others accept too. Lone surrogates are refused because they have no UTF-8 form: the pg driver sends each one as U+FFFD, so "t\ud800" and "t\udc00" would be stored as one tenant (tests/postgres-live.test.ts shows the driver doing it). Composite keys are the JSON encoding of the tuple (compositeKey in src/store-input.ts), so distinct tuples never share a key even if a separator character were allowed.

A store keeps only the fields a record's type declares. A fan-out job's event metadata and actor are rebuilt field by field: the WebhookEventMetadata fields, and exactly one member of the WebhookJobActor union. Optional causedBy is rebuilt as a known EventCause alongside a present actor. Anything else on the caller's object is dropped, such as a raw payload, trace context, provenance or a secret. payload and facts are the persistence projection's allowlisted JSON and are kept whole. Intents, denials, attempts, requeue requests and subscription inputs are likewise read field by field. Contract cases with a sentinel check this.

Memory stores

MemoryWebhookSubscriptionStore({ clock }) and MemoryWebhookDeliveryStore({ clock, replayHorizonMs }) keep their state in private class fields of the instance, not in module scope. Every method copies its arguments at entry with the snapshot readers below, then waits once, where a database store would do I/O, so that concurrent calls interleave. Then one synchronous step reads the clock, refuses an aborted or expired call, runs every check and writes. That step has no rollback, so each one computes its result, including every record it returns, before it changes anything. A claim, for instance, builds every lease and every returned record first and checks that the lease expiry is a representable time before it leases anything. Reads return fresh frozen copies, made by a copier with no depth or size limit, so any record the store accepted can be returned. The optional beforeAtomicStep constructor option is a test seam. It is awaited where the store would do I/O, before the atomic step, so a contract case can hold one whole call there while another runs. Leave it unset outside tests. The memory stores claim the input-reading half of P1 and P2 below. P3 and P4 do not apply to them. Their internal bookkeeping uses ordinary Map and array methods, so the capture of built-ins at load is not claimed for it.

PostgreSQL stores

import { Pool } from "pg";
import { PostgresWebhookDeliveryStore, PostgresWebhookSubscriptionStore } from "@fabricorg/webhook-delivery";

const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const deliveries = new PostgresWebhookDeliveryStore({ pool, clock, replayHorizonMs: limits.replayHorizonMs });
const subscriptions = new PostgresWebhookSubscriptionStore({ pool, clock });
await subscriptions.ensureSchema();
await deliveries.ensureSchema();

Client. The pool is injected and structural. WebhookPostgresPool needs query() and connect(), and each connection needs query() and release(). pg.Pool fits, and so does a Lakebase-compatible client with the same methods. The package has no runtime dependency on pg. It needs connect(), which Host's PlatformHostSqlClient does not have, because a method that checks and then writes runs several statements on one connection, with the store's clock read between them. The stores never end the pool.

Schema. ensureSchema() creates the schema and tables, or checks the ones already there. It mirrors Host's migration runner. It runs in one transaction under a transaction-scoped advisory lock keyed by the schema, so concurrent callers apply each migration once. A webhook_schema_migrations ledger records each migration's SHA-256. A recorded migration whose SQL has changed fails as store_failed (field: "ensureSchema.checksum") rather than being re-run. Migration 2 (PR 8) adds the begun-attempt fence and receipt_digest columns and the attempt outcome table to an existing delivery schema. Migration 3 (PR 9) adds webhook_requeue_evidence.action_invocation_id, fills it from existing evidence records, and indexes it by tenant, space and invocation, for the re-run lookups described in "Atomicity and re-runs". Call it at startup or from a migration step, with a role that can create the schema. The schema option names where the tables live. It defaults to fabric_webhook_delivery and allows lower-case letters, digits and underscores. The two stores may share a schema. The horizon floor belongs to the schema, so two delivery stores on one schema share one floor.

Transactions. Every method reads its input through the shared readers, awaits the beforeAtomicStep test seam, and only then takes a connection. A write runs as one READ COMMITTED transaction. The level is named explicitly rather than inherited from the server default. It runs in this order:

  1. Every statement that can wait on another transaction, in a fixed lock order: the horizon table lock first (for the writes that take it), then the record rows (FOR UPDATE, or FOR SHARE on an insert's parent job), then any tentative insert-if-absent. An insert-if-absent's conflict check waits on a concurrent uncommitted insert of the same key, so it runs here too, before anything is decided. A claim's FOR UPDATE SKIP LOCKED also runs here, though it never waits.
  2. With every lock held, the injected clock is read and a call whose signal aborted or whose deadline passed is refused, including one that aborted or expired while it waited in step 1. The horizon floor and the requeue evidence timestamp come from this clock read.
  3. Every check, then the write. An insert that turns out to be past the horizon rolls back its tentative row and returns past_horizon.
  4. The clock is read and the bounds checked once more, then the transaction commits.

The purge is the one exception to step 1: it takes only the horizon lock there. It cannot lock its candidates before it reads the clock, because the clock decides the cutoff and so which records are candidates, and its DELETEs can wait on a row lock. Step 4 refuses it if its signal aborted or its deadline passed during that wait. The wait only makes its cutoff older than the clock at commit, so it removes less, never more. "call bounds while waiting for a lock" in the live suite holds each kind of lock from another connection, aborts the signal or moves the clock past the deadline while the call waits, and checks that the call refuses as the memory store would and commits nothing.

Any error rolls the transaction back. A package error (record_mismatch, delivery_id_conflict, clock_invalid, call_aborted, deadline_passed) passes through. Anything else, such as a driver error or a constraint violation, becomes store_failed without being read. If the rollback itself fails, the connection is discarded instead of being returned to the pool. A read is one statement on the pool, so it sees committed rows only.

Replay-horizon serialization. A purge and a horizon-checked write must not interleave between the write's read of the purge cutoff and its write. The horizon-checked writes are the job, intent and denial inserts, the job and intent requeues and the actor enrichment. The mechanism is a table-level lock on the store's one-row webhook_delivery_horizon table, which also holds the highest purge cutoff:

  • Every horizon-checked write runs LOCK TABLE … IN SHARE MODE as its first statement and reads the highest purge cutoff. It then takes its record locks, reads the clock, checks against the floor, and writes.
  • purgeExpiredRecords runs LOCK TABLE … IN EXCLUSIVE MODE as its first statement and reads the highest cutoff. It then reads the clock, deletes, and raises the floor in the same transaction.

SHARE conflicts with EXCLUSIVE but not with itself. Inserts and requeues therefore run concurrently with each other, but a write and a purge never both hold the lock: one commits before the other reads the floor. A row lock on the horizon row would serialize the same pairs, with FOR SHARE for writers and FOR UPDATE for the purge. It was not chosen because a new FOR SHARE joins the existing share lockers even while a FOR UPDATE waits, so a steady stream of inserts could hold a purge off. PostgreSQL queues a table-lock request behind a conflicting waiting one, so a write that arrives while a purge waits goes after the purge. The test "a write that arrives while a purge waits queues behind the purge" checks this from what the database shows: the later write reads the purge's committed floor and is refused, where running first would have stored its job. A purge holds the lock for one batch, bounded by its limit, so writes wait at most that long. To take the lock, the store's role needs UPDATE on the horizon table. It needs that anyway to raise the floor.

tests/postgres-live.test.ts, "check-to-write serialization", pauses a transaction inside the store through the transactionCheckpoint test seam, while another connection runs the other operation. A write pauses after it has read the purge cutoff under the lock and before it reads the clock or writes. A purge pauses after its writes, just before its commit. The tests give the writer a clock that has not crossed the horizon and the purge one that has, so only the purge's floor can refuse the writer, which is the case the lock exists for. The tests then check the outcome:

  • Host outbox re-publication paused after reading the cutoff races a purge. It finds the job (already_present), then the purge removes it.
  • A purge paused before its commit races Host outbox re-publication. The insert waits, then sees the raised floor (past_horizon).
  • A late intent insert races a purge. It cannot re-create the purged intent or its tombstone.
  • A requeue races a purge that has raised the floor past the record. The requeue is refused (past_horizon).

With the LOCK TABLE statement replaced by a no-op, these four cases fail with the harm itself: the job or intent is re-created, or the requeue applies below the floor. A fifth case, a requeue paused before a purge, keeps its outcome without the lock. The requeue's FOR UPDATE on the record also makes the purge's DELETE wait, and that DELETE re-checks terminal status. That case fails only on the missing wait for the horizon lock, and so does the fairness test above.

Other locks. A claim leases with FOR UPDATE SKIP LOCKED, so concurrent claims never lease one record twice, and each claim advances the fence by one. "concurrent claims" checks this with eight workers on separate connections, round after round. Fenced writes, settlements, attempt appends and beginAttempt lock their intent or job row FOR UPDATE, then judge the lease's expiry on the store's clock read after the lock. finishAttempt locks no intent row: it reads the begun attempt, matching its receipt digest, and inserts its outcome with ON CONFLICT DO NOTHING, so of two racing outcomes the second waits on the key and then finds it. An intent or denial insert locks its parent job FOR SHARE, so a reclaim cannot advance the parent's fence between the lease check and the insert. The tombstone for a (subscription, event) pair is inserted with ON CONFLICT DO NOTHING. Of two racing inserts of one pair, the second waits on the key and then finds it. A subscription write locks the subscription's head row FOR UPDATE, so of several racing transitions with one expectedRevision, exactly one applies.

Revision timing. A revision write takes its head-row lock and reads the current revision and configuration first. Only then does it read the injected clock, inside the transaction, and stamp effectiveFrom. The stamp is the clock, or the previous revision's effectiveFrom if the clock is behind it, so it is never earlier than the previous revision's. After the clock read, the transaction runs one INSERT, the final bounds check (no database round trip) and the COMMIT. Time spent waiting for the lock or reading comes before the stamp. Readers see committed rows only, so a revision becomes visible two statement round trips after its effectiveFrom. The store does not bound those round trips; a stalled connection or a slow commit stretches them. Fan-out waits eligibilitySettleMs (default 5 s) past an event's recordedAt before it reads eligibility. Keep that well above your database's worst commit latency. A server-side statement_timeout on the store's role bounds each statement.

Storage. Times are bigint epoch milliseconds. A timestamptz cannot hold years before 4713 BC, which a Date can, and the memory store accepts any Date. Documents and free text are json columns: payloads, bodies, attempt records, evidence, patterns and configuration strings. They hold the package serializer's output, which escapes control characters and lone surrogates, so they round-trip exactly, key order, NUL and lone surrogates included. jsonb would reorder keys and refuse \u0000. Claim and purge ties are broken by a sort_key column that holds the key's UTF-16 code units in hex, so ties order exactly as the memory store's < comparison orders them. "parity with the memory store" runs one script against both stores and compares the results as JSON text.

Known differences from the memory store.

  • A -0 inside a payload, facts or record comes back as 0, because JSON text cannot carry -0. "parity with the memory store" asserts this difference, and that it is the only one.
  • Requeue evidence for one event is listed in insertion-sequence order. Two requeues of different records of one event can commit out of sequence order, and a read in between sees the later one without the earlier one.
  • A call's deadline and signal are checked after its locks are held, as the memory store checks them at its atomic step, and again just before commit. A call waiting for a lock is not interrupted when its signal aborts. It keeps waiting, then refuses with call_aborted and commits nothing. How the delivery cycle handles that is under Bounds and late results.

Test seams. beforeAtomicStep has the memory store's meaning. transactionCheckpoint, on the delivery store only, is awaited inside the transaction of each horizon-checked method and of the purge. It runs at locked, after the horizon lock, the cutoff read and the record locks, and before the clock is read or anything is written. It also runs at written, after the write and before the commit. A call that returns a refusal does not reach written. Leave both unset outside tests.

Running the live suite. From the repository root, run pnpm build, then pnpm test:postgres. The runner starts a throwaway postgres:16 database on a free localhost port and removes it in its cleanup block after success, failure, Ctrl-C, or SIGTERM. Docker must be installed and usable. FABRIC_POSTGRES_TEST_IMAGE overrides the image, and FABRIC_POSTGRES_TEST_TIMEOUT_SECONDS overrides the 60-second readiness timeout. An existing FABRIC_POSTGRES_TEST_URL bypasses Docker and is passed unchanged, as in the postgres-certification CI job. The runner reports missing builds with Run pnpm build first; rebuild after source changes. See the Live certification section in the repository file docs/operations/releasing.md for cleanup limits and runner tests. Direct Vitest runs skip this file without the URL. The suite creates one database per run and one schema per store pair.

Contract suite

tests/store-contract.ts is a record of named cases, each taking a factory that builds both stores from an injected clock and horizon. tests/memory-stores.test.ts runs it against the memory stores, and tests/postgres-live.test.ts runs the same record against PostgreSQL. It uses the factory-per-case pattern also used by Host's published outboxRequeueChecks in src/outbox-requeue-conformance.ts; this webhook suite remains test-only. Two cycle-level records run the same way against both stores: tests/delivery-cycle-contract.ts and tests/fan-out-lease-contract.ts. A database-backed store meets four requirements; how the PostgreSQL store meets each is under PostgreSQL stores:

  • Purge and the floor are store-wide, so each case needs its own schema or database.
  • The store must read the injected clock inside the transaction that writes.
  • It must await the factory's beforeAtomicStep hook, with the method name, after reading its input and before opening the transaction that checks and writes, with every check inside that transaction. The race cases hold whole calls at that hook to force each operation order.
  • Because the hook cannot reach inside a transaction, the suite does not prove that a check and its write are serialized against a concurrent purge. The PostgreSQL store must prove that with a transaction-level coordination test of its own. For example, a second connection runs a purge while the first connection's insert or requeue transaction is paused just after its floor and horizon check, and the test asserts that no purged key is re-created and nothing inside the horizon is removed, and must name the lock or isolation level that prevents the race.

Security properties

Every exported pure function is built the same way: it copies its inputs into a package-owned snapshot (src/snapshot.ts) and runs inside one guard (src/errors.ts). P2, P3 and P4 hold for every exported pure function and every input. The memory stores' share of these properties is stated under Memory stores. P1 holds in full only for plain-data inputs, and says what remains for a Proxy. tests/snapshot-guard.test.ts and tests/hostile-input.test.ts check them.

  • P1. Read at entry, then only the snapshot. For plain-data inputs (no Proxies), the snapshot is a faithful copy of the input as it was when the function was called. The own properties the function needs are read into the snapshot at entry. Validation, projection, rendering, serialization and header building then use only the snapshot. Most properties are read once. Two cases are read again: a name listed twice in an allowlist whose first read found nothing, and a nested object reachable along two paths. Reading a plain data property has no side effects and returns the same value each time, so those repeats return the same answer. Which fields are read can depend on fields already read: the event type picks the allowlist entry, and the entry picks the payload fields. The package never asks for a payload field that is not allowlisted. A Proxy input gets no such promise. Its traps run during the snapshot, can run more than once for one property in the cases above, and need not return the same value twice; the snapshot holds whichever values were read. What still holds for a Proxy input is P2, P3 and P4. For every input, no read happens after the snapshot is complete. The only caller code that runs after the snapshot is an injected callback: the scope predicate and the retry port's random source. A callback is called inside the guard, receives frozen snapshot copies, and only a primitive result it returns is used, after validation.
  • P2. Package errors only. Every error the package throws is created by the package. It carries a fixed code (WEBHOOK_PROJECTION_ERROR_CODES, WEBHOOK_CONFIG_ERROR_CODES or, on the TypeError and RangeError instances, WEBHOOK_INPUT_ERROR_CODES) and that code's constant message. It is frozen. It never contains, wraps or keeps a caller value or a caller-thrown exception, whether as cause or as a property. Its stack is fixed text, <ErrorName>: <code>, set before anything can read it. A native stack would name the functions on the call stack, and a caller can name its own trap or callback after a secret. field names an envelope, job or option field, or a field name from the caller's own allowlist, never a value. The guard recognises the package's own errors by membership in a module-private WeakSet. Only the package's internal factory adds to it, and WeakSet.prototype.has runs no Proxy trap and reads no property of the thrown value. Anything else is dropped unread and replaced with a fresh constant-code error. A caller who constructs WebhookProjectionError or WebhookDeliveryConfigError cannot get past this check. The decision normalizers never throw: any answer that cannot be read is unavailable.
  • P3. Allowlist only. Only allowlisted payload fields reach a job record or a rendered body, and only declared facts reach a job's facts. A restricted event keeps neither without an opt-in. Envelope trace context and provenance are never kept.
  • P4. Validated is returned. resolveWebhookDeliveryLimits() and createWebhookRetryDelay() validate the snapshot and return it frozen, and buildWebhookRequestHeaders() builds its headers from the values it validated. A schedule is copied by index from its own length, never through its iterator. The delays checked are therefore the delays used, even when a Proxy would answer differently on a later read, because nothing is read later.

How the snapshot reads: properties are read through own property descriptors, and an accessor is refused without being called. Records must have Object.prototype or null as their prototype. JSON values must be primitives, real Dates (read with the Date.prototype intrinsics), arrays without holes, or plain objects. Nesting is limited to 64 levels and a value to 100,000 containers; option lists are limited to 1,024 entries. In option lists, holes and non-primitive elements are kept as invalid entries. Validation then rejects them (in a schedule) or skips them (in an allowlist). Every object the snapshot builds is frozen. Objects have a null prototype and arrays are fresh. Each is populated with defineProperty and null-prototype descriptors. Returned job drafts, egress payloads, rendered bodies, headers, classifications, decisions and limits are these frozen snapshot records. rawBody is produced by the package's serializer from the snapshot, never by JSON.stringify on an object, so no toJSON, getter or prototype member takes part. The built-ins the package calls are captured when the module loads and invoked through the captured Reflect.apply.

Threat model. Inputs are expected to be plain data: what JSON.parse, Host's envelope converter and the stores produce. The snapshot is the defence against inputs that are not. It does not run getters, methods or iterators of the input, but a Proxy's traps still execute while it is taken. Whatever a trap throws is contained by P2. Whatever a trap installs on a shared prototype, such as Object.prototype.toJSON, cannot reach the package's output, because the output is built from null-prototype objects and serialized by package code. Code that can mutate the realm's built-ins, before the call or from a trap during it, is out of scope beyond that. Such code can still change what the caller does afterwards with a returned value: JSON.stringify(rendered.body) would use an Object.prototype.toJSON through the body's arrays. The bytes to store, sign and send are rawBody. An Error.prepareStackTrace hook is never consulted for a package error, because its stack is replaced before anything reads it.

The WeakSet is per copy of the module. When the ESM and CommonJS builds are both loaded, each treats the other's errors as foreign and replaces them with its own.

Fan-out

Fan-out runs in two stages (ADR 0018 decision 2). Stage one runs inside the Host outbox relay and only stores a job. Stage two runs in the application's worker, on its own lease, retry budget and processing deadline, and turns each job into intents or recorded denials. The package starts no scheduler; the application calls runWebhookFanOutCycle() from its worker.

Stage one: createWebhookFanOutPublisher()

createWebhookFanOutPublisher({ store, clock, policy, limits }) returns an EnterpriseEventPublisher for runOutboxRelayCycle(). Its publish(event, context):

  1. projects the envelope with projectWebhookFanOutJob() (metadata, allowlisted fields and declared facts only);
  2. inserts the job, keyed by eventId, insert-if-absent, with createdAt now and a processing deadline fanOutDeadlineMs later, bounded by portTimeoutMs and the relay's signal;
  3. resolves on inserted or already_present, and on nothing else.

The relay marks a record published only after publish() resolves, so an acknowledged record has a stored job. A crash between the insert and the acknowledgement leaves the record for lease expiry; the relay republishes it under the same eventId and the insert is a no-op (test "crash before acknowledgement …", tests/fan-out-host.test.ts).

A rejection makes the relay retry the record and finally dead-letter it, where the Host requeue (requeueOutboxDeadLetter) can replay it (test "relay exhaustion, then the Host dead-letter requeue …"). Each rejection is a package error with a fixed code; an error the store threw is dropped unread:

| Code | When | | --- | --- | | event_past_replay_horizon | The store answered past_horizon (R5): the event is older than the replay horizon and can never get a job. The outbox record dead-letters rather than counting as published. | | fan_out_store_failed | The insert threw, or its answer could not be read or was none of the three outcomes. | | fan_out_store_timeout | The insert did not settle within portTimeoutMs. | | publish_aborted | The relay's signal aborted before the store answered. | | clock_invalid | The injected clock threw or returned an invalid time. |

An envelope that cannot be projected rejects with the projection's own WebhookProjectionError. All codes are in WEBHOOK_FAN_OUT_ERROR_CODES.

Reading what ports return. A port's rejection is dropped unread. A value it resolves with, and the relay's context, are read only through src/fan-out-read.ts and the context readers in src/fan-out-call.ts: inside a try/catch, own data properties only, through descriptors, so no getter runs, and a Proxy trap that throws makes the value unreadable rather than escaping. Unreadable maps to a fixed code. Tests: the "port results that throw when inspected never leak" block in tests/fan-out-hardening.test.ts. Adopters raise the relay budget as ADR 0018 describes (retryDelayMs exponential from 1 s capped at 15 min, maxAttempts at least 24).

Actor identity. The job records the actor as the relay's context.actorDisclosure describes it (decision 5). included with both actorId and actorType on the envelope gives { state: "present" }. suppressed gives { state: "absent", reason: "suppressed" }. Anything else is legacy: a legacy disclosure, no context at all, and an included record whose envelope lacks the fields. An actor on an envelope whose disclosure is not included is ignored.

Bridges. Events written without the Host outbox reach fan-out through a bridge that calls the same publisher with an envelope built by toEnterpriseEventEnvelope(). A bridge overlapping the relay is safe: whichever inserts first stores the job, and the other's insert answers already_present (tests "relay first, bridge second …" and "bridge first, relay second …"). The stored job is never updated, so a bridge that inserts first decides the job's actor. A bridge that passes no context stores a legacy job, which admission needing the actor cannot decide until actor enrichment (PR 9) repairs it. Bridges should pass { signal, actorDisclosure } when they know the disclosure.

Composite: createWebhookCompositePublisher()

createWebhookCompositePublisher({ sinks }) feeds several sinks, for example the fan-out publisher and a message bus, from one relay. A second relay on the same outbox claims the same records, so it is no substitute. Each sink is { name, publisher, includeActor?, required? }, and sinkTimeoutMs (default 10 000, a positive whole number) bounds each sink.

Trust model. Sinks are trusted application code, such as bus adapters wired at the composition root, the same as Host's adapters. The composite isolates sinks from one another, and the relay from them, against ordinary sink behaviour: mutating the envelope or context it was handed, throwing synchronously, returning a rejected native promise or a thenable that calls its reject callback, rejecting late, ignoring its signal, and hanging. It does not confine code that subverts intrinsics. A returned promise with a poisoned constructor getter, a thenable whose then throws asynchronously, and a replaced dispatchEvent or other EventTarget method on the signal a sink was handed are outside its guarantees: such code can run during the composite's work (aborting a sink's signal dispatches the abort event on it) and can raise errors the composite does not catch.

  • Every sink is called concurrently with its own envelope, its own context and its own signal (B1). The composite accepts plain-data envelopes only. The relay's envelope is read once by the package's plain-data copier (src/snapshot.ts; own data properties only, no getter is called, depth and size budgets), which allows null, booleans, finite numbers, strings, arrays, plain objects and the envelope's occurredAt and recordedAt dates. Each sink then gets its own copy of that snapshot, made before any sink runs, so a sink that mutates its envelope or context changes nothing another sink or the relay sees (tests "a sink mutating nested payload objects and arrays ..." and "a sink that mutates its context ..." in tests/fan-out-composite.test.ts). No two sinks, and no sink and the relay, share a mutable object through the envelope, and what enforces it is that allowlist: a value the copier does not allow is never copied or passed on.
  • Anything else is refused with WebhookProjectionError inspection_failed before any sink is called: typed arrays, ArrayBuffer, SharedArrayBuffer, Map, Set, Error, class instances, WebAssembly.Memory, functions, symbols, accessors, and values nested too deeply or in too great a number. Host types payload as unknown and does not guarantee JSON, so an envelope whose payload is not plain data is refused (test "an envelope holding ... is refused before any sink runs"). occurredAt and recordedAt reach sinks as new Dates; a Date elsewhere, in payload for example, reaches them as its ISO-8601 string, as in the persistence projection. An envelope built by Host's toEnterpriseEventEnvelope from plain data reaches every sink equal to the original, apart from actor and cause keys removed for a sink without includeActor: true and the date handling above (test "a Host envelope with plain payload ..."). A Proxy cannot be told from the object it wraps; its traps run while the envelope is read, and only the values they return are copied.
  • A sink's signal aborts when the relay's signal aborts or the sink's sinkTimeoutMs runs out. The composite installs no listener on a sink's signal, and its cleanup calls nothing on the envelope, context or signal it handed a sink, so a sink that shadows removeEventListener on its signal does not change the outcome (test "the composite's cleanup calls no listener method on a sink's signal …"). The runtime functions the composite calls are captured when the module loads, as elsewhere in the package; that is for consistency and does not confine a sink that replaces them.
  • The composite resolves once every required sink (the default) resolved. A sink with required: false is started but never waited for, and its outcome is ignored, so an event it failed is not retried for it. An optional sink still running after publish() settled keeps its relay-abort forwarding and its own timeout until it ends: the composite's one listener on the relay's signal is removed when the last sink ends, not when publish() settles (B4). An optional sink's timer is unref()'d where the runtime supports it, so it does not keep a Node process alive (tests "a caller's abort after publish() resolved …", "… an optional sink's timer is unref'd …").
  • It rejects with publish_aborted, and starts no sink, when the relay's signal aborts at any point before the sinks start, including from a proxy trap run while the envelope is copied: the composite checks the signal again after it starts watching it (test "a caller abort raised while the envelope is copied …"). It rejects with publish_aborted as soon as the relay's signal aborts while a required sink is running, even when that sink ignores its signal. Otherwise, once every required sink has settled or timed out, it rejects for the first required sink in sink order that did not resolve: with that sink's error when this package created it (keeping its code, for example event_past_replay_horizon), sink_failed for any other error, dropped unread, and sink_timeout when it did not settle in time. A sink's rejection reason is only tested by guard (src/errors.ts), which checks it against the package's own errors without reading it, so no other text reaches the rejection (B2).
  • Rejections from ordinary sink behaviour are handled, early or late, required or optional (B3). The sink call, a synchronous throw and the await of what it returned (a rejected native promise, a thenable that calls its reject callback, a non-promise) sit in one try, and the cleanup that follows catches its own errors (the "fixed outcomes and handled rejections" block). A returned value that subverts the promise machinery is outside this guarantee, per the trust model above.
  • The relay retries the whole record after a rejection, so each sink must treat a repeated eventId as a no-op.
  • Only a sink with includeActor: true receives actorId, actorType and a recorded causedBy, with the relay's disclosure unchanged. A sink without that opt-in has those keys deleted, and an included disclosure is reported to it as suppressed. Test: "the composite strips actor identity for every sink that did not opt in …".

Stage two: runWebhookFanOutCycle()

One call claims up to batchSize pending jobs under a fenced lease and processes each:

  1. Past its processing deadline: dead-letter as processing_deadline_exceeded. The deadline is persisted at creation, so deferrals and reclaims count toward it (R4).
  2. Eligibility not settled yet (see below): defer the job to recordedAt + eligibilitySettleMs, writing nothing, as eligibility_unsettled. The store has no way to return a job without spending an attempt, so a deferred job has one attempt fewer for failures. A job is deferred at most once unless the worker's clock steps backwards.
  3. List the revisions whose interval contains recordedAt, in the job's tenant and space. A revision is eligible when it is active, is in the job's scope and one of its patterns matches the event type (matchesWebhookEventTypePattern: * matches everything, prefix.* matches types starting with prefix., anything else matches exactly). A paused or deleted revision gets neither intent nor denial.
  4. For each eligible revision, in subscriptionId order: if the pair already has an intent or a denial (readTombstone finds its marker), it is decided and admission is not asked again, so an admission outage after a decision cannot hold the job open (tests in "decided pairs are not re-admitted on retry"). Otherwise, if actorRequired says the revision needs the actor and the job's actor is suppressed or legacy, the revision is unavailable and admission is not called. Otherwise admission decides; a throw, a timeout or an answer that cannot be read is unavailable. allow renders the v1 body and inserts an intent; deny records a denial with its code; unavailable writes nothing.
  5. If every eligible revision now has an intent or denial (inserted or already_present), the job is completed. Otherwise it is rescheduled after retryDelay(attempt) with the first unavailable cause as its diagnostic, or dead-lettered when its attempts are spent or the next attempt would fall past its deadline. Intents already written stay; the next attempt finds them already_present and adds only the missing ones.

Reading a claimed job. Each claimed record is read in two parts, each in its own try/catch that drops whatever was thrown (readClaimedJobs in src/fan-out-read.ts). The header comes first: eventId, tenantId, spaceId and the lease's owner and fence, each an own data property read once. The body comes second: the event metadata, payload, facts, actor, attemptCount and processingDeadline.

  • Every stored job is readable. The insert holds the whole submitted job to the snapshot limits (MAX_JSON_NODES containers, MAX_JSON_DEPTH levels). The reader never budgets the whole claimed record, because the store adds a lease and other fields to it. It snapshots only payload and facts, with one shared budget seeded with the draft's other containers, at the depth the insert reached them, and reads the store's own fields as scalars. For a store that returns the draft it accepted, the reader's count is therefore never above the insert's count for that draft, whatever the store adds (test "a draft accepted at the node limit round-trips through a claim …" in tests/fan-out-claim-read.test.ts).
  • A body that cannot be read. When the header reads but the body does not (a getter, a Proxy, a non-JSON value, an event naming another eventId, a deadline that does not parse), the job can never be processed, so the cycle dead-letters it through the fenced transition with the fixed diagnostic job_unreadable, without listing revisions or asking admission. Claims take only pending jobs, so it is not claimed again until the fan-out-job requeue (PR 9) returns it. If that dead-letter write itself throws or times out, the job is abandoned for that cycle, like any failed final write.
  • A header that cannot be read. A record whose identity or lease cannot be read cannot be named by a fenced write, and one leased to another owner is not this worker's. Either is counted as abandoned and nothing is written for it. It relies on lease expiry: the store offers it again once the lease runs out, and it stays pending until a store returns a readable header.

Nothing a port's getter or Proxy trap throws reaches a result, an error or a stored diagnostic; the tests for both cases check for a sentinel the hostile values carry.

Every write carries the job's lease, which the worker renews while it works (Lease renewal). When an insert answers lease_lost, a fenced transition answers false, or the store refuses a renewal, the worker writes nothing more for that job (test "concurrent workers: a worker that lost its lease writes nothing …"). A read or an insert that throws or times out stops the job and reschedules it; an insert that timed out may have committed, and the next attempt finds it already_present. A completion, reschedule or dead letter that throws or times out may have committed too, so nothing follows it: the job is counted abandoned, and the next claim finds it as that write left it (tests "a completion that reaches the store after the deadline is refused; the worker cannot tell …" and "a reschedule that reaches the store after the deadline …" in tests/fan-out-hardening.test.ts). An insert answering past_horizon dead-letters it. Tests that a stale worker writes nothing while the job is pending under another worker's fence (intent, denial, completion, reschedule): the last block of tests/fan-out-hardening.test.ts.

Lease renewal

Changed in PR 8. A fenced write is refused once the lease has expired on the store's clock (Leases are judged on the store's clock), and one pass over a job can outlast a lease, because it reads a tombstone for every eligible revision, decided ones included. Without renewal, a job with 16 eligible subscriptions whose tombstone reads took 4 s each never completed under the default 60 s lease: the first pass wrote 14 intents and lost the lease, and every later pass spent about 56 s re-reading those 14 and lost the lease before writing the 15th, until the processing deadline dead-lettered the job.

Rule. Before each port call it makes for a job (every call through jobCall, and the dead-letter transition), the worker renews the job's lease with renewFanOutJobLease when less than 2 * portTimeoutMs of it is left: one bound for the renewal, one for the call it precedes (keepLease, src/fan-out-cycle.ts:468-486). A worker whose calls answer inside their bounds therefore keeps its job, and each pass gets as far as its ports allow. A worker that stops making calls (a crash, a stalled event loop) stops renewing and loses the job when the lease runs out. Jobs claimed in one batch are processed one at a time, so a job late in a batch whose claimed lease ran out while earlier jobs were processed is refused at its first renewal and counted leaseLost; another worker may already have claimed it. leaseDurationMs must exceed 3 * portTimeoutMs, so a renewed lease outlasts the renewal and the margin after it. The store decides a renewal like any fenced write and never extends a lease past the job's processing deadline, which therefore still bounds the whole job (R4).

| Guarantee | Enforced by | Test | | --- | --- | --- | | A worker whose calls answer in time keeps its job through a pass longer than one lease | keepLease before every job call (src/fan-out-cycle.ts:510) and before the dead letter (:794) | tests/fan-out-lease-contract.ts "16 subscriptions and 4-second tombstone reads under the default lease …" (memory and PostgreSQL); tests/fan-out-lease.test.ts "the smallest lease accepted …", "the dead-letter of a job whose body cannot be read renews a short lease first …" | | A renewal applies only while the caller holds the lease: pending, same owner and fence, unexpired on the store's clock read after its locks | holds (src/delivery-store-core.ts:155-157) in renewFanOutJobLease (src/memory-delivery-store.ts:330; src/postgres-delivery-store.ts:613, through #fencedJobWrite) | store contract "a lease renewal extends only a lease the caller holds …", "a renewed lease holds the record against a claim …", "every fenced write decides lease expiry on the store's clock …"; live "renewFanOutJobLease: … while waiting for a lock commits nothing" | | A renewal never shortens a lease and never extends it past the processing deadline | renewedExpiryMs, src/delivery-store-core.ts:320-324 | store contract "a lease renewal extends only a lease the caller holds …" | | A refused renewal stops the pass at once, with nothing more written for the job | throw LEASE_LOST, src/fan-out-cycle.ts:485, caught only by the claim loop (:420-425) | tests/fan-out-lease.test.ts "a refused renewal stops the pass at once …"; "concurrent workers: …" | | A renewal whose outcome is unknown (threw, timed out, unreadable) is not a refusal: the worker carries on, and the store decides its next write | keepLease acts only on a literal true or false | "a renewal that fails is unknown …", "with renewals failing, a pass that outlives the claim's lease is stopped by the store …" | | The worker renews only when the margin requires it | the expiry it last asked for, tracked at src/fan-out-cycle.ts:482 | "16 subscriptions …" expects exactly one renewal |

What it assumes. The worker tracks the lease on its own clock, from the now and leaseDurationMs it sent with the claim and with each renewal; the store sets the expiry from the same now. A store clock running ahead of the worker's by more than portTimeoutMs can expire a lease the worker thinks it holds. The store then refuses the write (its call deadline, or the lease, has passed on the store's clock), and nothing is written.

Why renewal, and why before each call. Durable traversal progress (storing how far a pass got) would make the next pass cheaper, but it needs new stored state that requeue and actor enrichment must reset. Renewal keeps the pass that is making progress alive and reuses the fenced lease the store already has. It renews inline, before each call, rather than from a background heartbeat like Host's outbox relay (startOutboxHeartbeat): jobCall awaits the renewal before it starts its call (src/fan-out-cycle.ts:510), so a renewal never runs alongside the job's own writes, and in PostgreSQL it never queues on the job row behind the worker's own intent insert (which holds FOR SHARE on it); there is no timer to stop or rejection to leave unhandled when the job ends; and a refusal is seen before the next write, not while one is in flight.

Processing deadline (R4). No intent, denial or completion is written for a job at or after its persisted processingDeadline, on the store's clock. Every port call made while processing a job is bounded by the smaller of portTimeoutMs and the job's remaining lifetime, so the absolute deadline it passes is never later than the processing deadline (jobCall in src/fan-out-cycle.ts). The store refuses a write whose call deadline has passed when it reaches the write (store contract case "a call whose signal aborted or whose deadline passed writes nothing"). The cycle also makes no intent, denial or completion call once the deadlin