← Model losses

Head-to-head comparison

openai / gpt-6-astra / high / high effort preferred over xai / grok-4.7-efficient / medium / medium effort · clear win.

Primary judge: Sol 6.1, requested Low. Effective provider effort and internal attempts were not verified. A close win is still a scored preference; it does not establish a material defect.

Reviewed public evidence

Task goal

Design a durable webhook inbox for one PostgreSQL database and multiple workers. An authenticated source supplies eventID, accountID and payload; deliveries are duplicated and reordered. Persist acknowledgement before returning success, deduplicate by source/account/eventID, process with expiring leases and fencing, preserve per-account dependencies, bound retries and poison events, and recover crashes without claiming exactly-once external effects. Define state transitions, transaction boundaries, backpressure and acceptance failure cases.

Give one coherent design with explicit requirements, assumptions and alternatives, state/invariant/transaction details appropriate to the stated scope, and measurable pass/fail acceptance checks. Do not invent benchmark measurements, provider costs, source inspection, executed tests or objective passes. Every contributor must independently answer the complete identical question; there are no separate roles, files or tool evidence.

openai / gpt-6-astra / high / high effort answer

## Recommendation and assumptions

Use a **transactional PostgreSQL inbox, one execution lane per account, and renewable leases with monotonically increasing fencing tokens**. A successful webhook response means “durably accepted,” not “processed.”

This is an independent design based only on the supplied requirements. No implementation was inspected and no tests were executed.

### Required contracts

1. **Authenticated identity:** derive `source` from authentication and verify that it may submit for `accountID`. Do not trust source identity supplied inside the payload.
2. **Stable event identity:** retries retain the same `(source, accountID, eventID)` and immutable event contents.
3. **Dependency information:** event IDs and arrival order alone cannot reveal dependencies. For this design, require an authoritative, contiguous **per-account sequence number** in the authenticated envelope or payload.
   - Provision the account’s starting sequence explicitly; never assume the first arrival is the first event.
   - If multiple sources affect the same account, they must share that sequencing authority. Independent source sequences cannot establish cross-source order.
   - Without this additional contract, the system can serialize arrival order, but cannot truthfully guarantee preservation of source dependencies.
4. **Source retry behavior:** the source retries timeouts, retryable non-success responses, and ambiguous outcomes using the same identity.
5. **Durability scope:** acknowledge only after PostgreSQL reports a durable commit. Use logged tables and appropriate WAL/fsync settings. If success must survive primary loss and failover, synchronous replication and promotion policy must preserve acknowledged commits; asynchronous replication alone does not provide that guarantee.
6. **External effects:** downstream systems may support stable idempotency keys or fencing. Where they do not, ambiguous effects require reconciliation or explicitly accepted duplicate risk.

Sequence numbers impose stronger ordering than a dependency DAG, but make the correctness boundary straightforward.

## Durable records and invariants

### Records

**`account_lane`**
- Canonical account key.
- `completed_seq`: highest contiguously resolved sequence.
- Monotonic `fence`, never reset or reused.
- Optional active event, owner, lease expiry, and attempt deadline.
- Administrative hold and reason.

**`inbox_event`**
- Primary key: `(source, accountID, eventID)`.
- Unique constraint: `(account_lane, sequence)`.
- Immutable sequence, payload, and fingerprint of the defined immutable envelope.
- State: `pending`, `running`, `retry_wait`, `succeeded`, `quarantined`, or `skipped`.
- Attempt count, retry deadline, next eligibility time.
- Current attempt token, error classification, and timestamps.

**Supporting records**
- Attempt/audit records.
- Transactional capacity accounting.
- Optional effect-intent/outbox records, uniquely keyed by event identity and effect name.

Define the fingerprint precisely: either require identical bytes on retries or specify canonical encoding. Include sequence and all other semantically immutable metadata. A mismatching duplicate is an identity conflict, not a harmless retry.

### Invariants

1. At most one accepted event exists for each deduplication key.
2. At most one accepted event occupies each account sequence.
3. Only sequence `completed_seq + 1` can execute.
4. At most one **currently authorized** attempt exists per account. Expired workers may still physically run.
5. Every worker mutation requires the current event, owner, fence, and an unexpired lease.
6. Local business changes, event completion, and cursor advancement commit together.
7. Failure, expiry, and quarantine do not advance the cursor.
8. Attempts and processing time have finite configured budgets.
9. Quarantining an event does not silently declare its dependencies satisfied.

Use database constraints plus explicit row locks under `READ COMMITTED`; application checks alone are insufficient. Establish one lock order, for example capacity records → account lane → event. Worker transactions that do not need capacity records start at the account lane.

## State transitions

| From | To | Condition |
|---|---|---|
| Absent | `pending` | Valid admission commits |
| `pending` / `retry_wait` | `running` | Event is the account head, retry time has arrived, and budgets remain |
| `running` | `succeeded` | Current unexpired attempt commits successful processing |
| `running` | `retry_wait` | Current attempt records a retryable failure |
| Expired `running` | `retry_wait` | Recovery records lease expiry; another attempt remains allowed |
| `pending` / `retry_wait` / `running` | `quarantined` | Permanent failure, exhausted budget, or unresolved effect ambiguity |
| `quarantined` | `retry_wait` | Audited recovery grants a new bounded budget |
| `quarantined` | `skipped` | Explicit, authorized resolution establishes that continuing is valid |

`pending` also covers dependency-blocked events. Eligibility is derived from the account cursor; it need not be materialized in another state.

A missing sequence blocks later events. A gap timer raises an operational alert and may place the lane on hold; it never manufactures success for the missing event.

## Transaction boundaries

### 1. Receive and acknowledge

Before opening a transaction, authenticate, authorize, enforce request-size limits, and validate the envelope.

Inside one transaction:

1. Acquire the required capacity and account locks in the prescribed order.
2. Look up the deduplication key:
   - Same immutable envelope: return the existing acceptance result without reserving capacity again.
   - Different envelope: reject with an identity-conflict response.
3. Check sequence validity and uniqueness. A new identity cannot replace an already accepted or resolved sequence.
4. Verify capacity and the allowed sequence-gap window.
5. Insert the event and reserve its storage/work capacity.
6. Commit.

Return `202 Accepted` only after that commit succeeds. An exact duplicate may also receive `202`, even if processing later failed: acceptance and processing status are separate concepts.

If the connection fails during commit, the outcome may be unknown. Do not claim that admission failed atomically. Return a retryable error if possible; a same-key retry discovers the committed record or inserts it once.

A notification can wake workers after admission, but polling remains authoritative. Notifications are not durable work storage.

### 2. Claim an account head

In a short transaction:

1. Select an eligible account using `FOR UPDATE SKIP LOCKED`.
2. Lock its head event and recheck eligibility.
3. If an old attempt expired, record expiry and apply retry/exhaustion policy.
4. Increment the persistent account fence.
5. Increment the event attempt count.
6. Assign owner, attempt token, lease expiry, and an absolute attempt deadline.
7. Change the event to `running` and commit.

Perform processing outside the transaction. Do not hold database locks across network calls.

Use database wall-clock time, sampled after lock acquisition, for lease decisions. Transaction-start timestamps can become stale while waiting for locks.

The claim counts as an attempt even if the worker crashes before doing useful work. This conservatively bounds crash loops.

### 3. Renew

A short transaction locks the lane and event and verifies:

- Matching owner, event, and fence.
- State is `running`.
- The current lease has not expired.
- The absolute attempt deadline has not passed.

Extend the lease only up to that deadline. An already expired worker cannot revive its lease, even if nobody has reclaimed the event.

If renewal fails or its outcome is unknown, the worker stops initiating new effects. Already-issued external requests may still complete.

### 4. Commit successful local processing

Lock the lane and event, then validate ownership and expiry again.

In the same transaction:

- Apply PostgreSQL business mutations.
- Record any durable effect intentions.
- Mark the event `succeeded`.
- Advance `completed_seq` by exactly one.
- Clear active ownership.

A stale worker must roll back all those writes. Checking the token and then committing business changes in a separate transaction would defeat fencing.

For accounts whose next event depends on external completion, do **not** advance the cursor merely because an outbox entry exists. Advance only after the required external result is durably resolved.

### 5. Failure and recovery

A current worker can record failure and clear its lease transactionally:

- Transient failure: `retry_wait`, with capped exponential backoff and jitter.
- Permanent failure or exhausted budget: `quarantined`.
- Ambiguous non-idempotent external outcome: quarantine or reconciliation hold.

A reaper uses the same locks to reclaim expired attempts. Recovery must work without cooperation from the crashed worker. Apply backoff to crash recovery too, so repeated worker deaths cannot produce a hot reclaim loop.

Enforce a maximum claim count, absolute processing deadline, and per-attempt runtime ceiling. An independent sweep can quarantine expired pending work, including events that never became runnable.

## External effects and fencing limits

A PostgreSQL fence protects PostgreSQL state only when every relevant write validates it transactionally. It cannot retract an external request.

For each logical external effect:

1. Persist an immutable intent before sending.
2. Use a stable idempotency key derived from event identity and effect name—not from attempt number.
3. Retry or query that same logical operation after an ambiguous outcome.
4. Record the confirmed outcome durably.
5. Unblock dependent account work only when the dependency’s completion condition is satisfied.

Where supported, pass the account fence downstream. The downstream must atomically reject obsolete fences. Fencing and idempotency solve different problems: fencing limits obsolete attempts; idempotency prevents repetition of one logical operation.

The key failure window remains:

> The downstream performs an effect; the worker crashes before PostgreSQL records success.

An outbox preserves the intent but does not close this window. Without downstream idempotency, a transactional integration, or reliable reconciliation, automatic retries can duplicate effects. Holding an account avoids unsafe progression but sacrifices availability.

Multiple external effects within an event need separate durable effect identities and reconciliation rules.

## Poison events, ordering, and operations

Quarantine stores the original immutable event and diagnostic history. It blocks dependent successors but must not block unrelated accounts.

Operators may:

- Correct the processing implementation and grant a bounded replay budget.
- Reconcile an ambiguous external operation.
- Apply an audited compensating resolution.
- Skip only when domain rules explicitly permit successors to proceed.

Skipping is a business decision, not a retry policy. Update the event and account cursor atomically, with an audit record. Preserve the original payload rather than overwriting accepted evidence.

Expose queue depth/bytes, oldest unresolved age, sequence gaps, head-of-line blocking, retry counts, lease expiries, quarantine counts, and per-account processing lag. Schedule accounts fairly so one busy or failing account cannot monopolize workers.

## Backpressure and retention

Configure hard limits for:

- Request and payload size.
- Global and per-account unresolved events and bytes.
- Accepted sequence distance ahead of the cursor.
- Concurrent attempts and downstream calls.
- Database connections.
- Retry/recovery budgets and retained history.

Admission reservations must be transactional; independently sampled queue counts can oversubscribe capacity. A simple global capacity row is correct but may contend. If necessary, replace it with bounded reservation allocations whose sum cannot exceed the global budget.

Reserve storage headroom for WAL, indexes, maintenance, and operational writes; logical payload-byte quotas alone do not bound physical disk usage.

Suggested admission responses:

| Condition | Response |
|---|---|
| Unauthenticated / unauthorized | `401` / `403` |
| Malformed or missing required ordering metadata | `400` or `422` |
| Payload too large | `413` |
| Identity or sequence conflict | `409` |
| Account/rate/backlog limit reached | `429`, with retry guidance |
| Database unavailable or global capacity exhausted | `503` |
| Durably accepted or matching accepted duplicate | `202` |

Exact duplicates should remain acknowledgeable when new admission is throttled, provided their durable receipt can be verified.

Retain compact deduplication tombstones after deleting bulky completed payloads. Permanent deduplication requires permanent identity retention. With finite storage, this eventually requires adding capacity or refusing new events. A bounded retention horizon is an alternative only with an explicit source replay/expiry contract; deleting receipts and admitting arbitrary old identities loses deduplication.

## Proposed measurable acceptance checks

These are pass/fail criteria, not executed results.

| Check | Pass condition |
|---|---|
| Concurrent duplicate admission | Concurrent identical submissions produce exactly one durable event and one capacity reservation |
| Conflicting duplicate | Changed immutable contents under the same key receive conflict; original contents remain unchanged |
| Sequence collision | Two identities targeting one account sequence cannot both be accepted |
| Commit/response crash window | Killing the receiver after commit but before response still permits a retry to find exactly one accepted event |
| Durability | Every observed success remains present after crashes/failovers covered by the declared durability policy |
| Reordering | Deliver sequences `3, 1, 2`; execution follows `1, 2, 3`, with no execution of `3` before its predecessors resolve |
| Missing predecessor | With sequence `2` absent, later sequences never execute and the configured gap alert fires |
| Competing claims | Under simultaneous claims, at most one valid lease exists per account; independent accounts can proceed |
| Lease fencing | Pause worker A past expiry, reclaim with B, then resume A: all A’s completion, renewal, and local business writes are rejected |
| Crash recovery | A crashed attempt is recovered within the configured lease/reaper timing bound; renewal cannot exceed the attempt ceiling |
| Retry bound | Persistent failures produce no more than the configured number of automatic claims and then quarantine |
| Poison isolation | Quarantined head blocks its successors while healthy accounts continue within the configured scheduling target |
| Local atomicity | Injected failure cannot leave business writes committed without matching event completion and cursor advancement |
| External ambiguity | An effect accepted before a worker crash is retried with the same idempotency key, or held for reconciliation when safe retry is unavailable |
| Capacity race | Concurrent new admissions never exceed transactional event/byte limits; matching duplicates consume no additional reservation |
| Retention | A replay inside the promised deduplication horizon cannot create another event; the expiry policy is explicitly exercised |
| Lost notifications | Dropping every wake-up notification still results in polling-based processing |

## Alternatives and remaining decisions

- **Explicit dependency DAG:** allows independent events within an account, but requires cycle detection, missing-dependency policy, and more complex claiming.
- **Arrival-order serialization:** works with the three supplied fields alone, but cannot preserve unknown source ordering.
- **Whole-account database lock during processing:** simpler for short database-only work; unsuitable for network-bound work and does not fence external effects.
- **Finite receipt retention:** reduces storage requirements by weakening the deduplication contract explicitly.

Confidence is high in the transactional and fencing approach. End-to-end ordering depends on authoritative dependency metadata; safe external retries depend on downstream capabilities.

**Next action:** agree on the sequencing contract, acknowledged-failure durability scope, downstream idempotency/reconciliation behavior, and numerical capacity/retry/retention limits. Then implement the transactions and execute the fault-injection checks above.

xai / grok-4.7-efficient / medium / medium effort answer

The design is a single-primary PostgreSQL transactional inbox with fenced leases. Admission is idempotent and acknowledged only after commit. Processing is at-least-once, per-account admission-order, and does not promise exactly-once external effects.

## 1. Design

**Conclusion.** Use one inbox table as the system of record. Authenticate, then commit the event, then return success. Workers claim only the per-account head with `FOR UPDATE SKIP LOCKED`, a database-clock lease, and a monotonic fence. Side effects run outside any inbox transaction. Stale workers cannot complete, retry, or extend a lease. Confidence is high on the inbox, lease, and fence mechanics, and medium on dependency and poison policy because the supplied fields do not define source order.

### Requirements

- R1. Reject unauthenticated requests before any inbox mutation.
- R2. Return success only after the ingest transaction commits with `synchronous_commit` on. A lost response is recovered by source redelivery, not by acknowledging early.
- R3. Deduplicate on `(source_id, account_id, event_id)`.
- R4. Same key and same raw-body hash is a no-op success. Same key and different hash does not overwrite.
- R5. Many workers may process different accounts at once. One account has at most one leased head.
- R6. Leases expire by PostgreSQL `now()`, not worker clocks. Every claim or reclaim increments `fence_token`.
- R7. Per-account dependency order is admission order (`inbox_seq`). A later row is ineligible while an earlier blocking row exists.
- R8. Attempts are bounded. Retryable failures wait until `next_attempt_at`. Exhaustion or a permanent failure becomes `poisoned` and blocks that account until an operator abandons or replays it.
- R9. Crash recovery is lease expiry plus reclaim. External effects may run more than once. The design must not be accepted under an exactly-once external-effect requirement.
- R10. Over-depth admission returns pressure failure and inserts nothing. An already committed key still returns success.
- R11. Ingest, claim, heartbeat, and complete are short transactions. External I/O is not inside them.

### Assumptions

- A1. One PostgreSQL primary, workers sharing it, `READ COMMITTED`.
- A2. Authentication yields a stable `source_id`. One source is a constant id.
- A3. The source reuses `event_id` for every redelivery of the same logical event and supplies only `eventID`, `accountID`, and payload.
- A4. Because no source sequence is supplied, the preserved dependency order is first-commit order per `(source_id, account_id)`, not an unobserved source causal order.
- A5. Dedupe hash is SHA-256 of raw request bytes. Semantic JSON equality is not required.
- A6. Design parameters, not measurements: payload limit 256 KiB; lease TTL 30s; heartbeat at TTL/3; max attempts 8; exponential backoff capped at 1h; retain key plus hash for at least the source redelivery horizon.
- A7. Downstream calls receive a stable idempotency key derived from the dedupe key. Downstream idempotency is not assumed.
- A8. An operator transaction can abandon or replay poison. That path is in scope because poison would otherwise stall the account forever.

### Schema and invariants

Primary key `(source_id, account_id, event_id)`. `inbox_seq` is an identity assigned only on first insert and never reused. Columns cover raw payload, raw-body hash, state, `attempt_count`, `max_attempts`, `next_attempt_at`, `lease_owner`, `lease_until`, `fence_token`, last error, poison reason, and timestamps. Partial indexes support due heads, expired leases, and per-account blocking predecessors.

States: `admitted`, `leased`, `retry_scheduled`, `succeeded`, `poisoned`, `abandoned`.

Allowed transitions:

- `admitted` → `leased` on claim.
- `retry_scheduled` → `leased` on claim when due.
- `leased` → `leased` on expiry reclaim, with a new owner, `fence_token + 1`, and `attempt_count + 1`.
- `leased` → `succeeded` on fenced success.
- `leased` → `retry_scheduled` on fenced retryable failure while attempts remain.
- `leased` → `poisoned` on fenced permanent failure, or retryable failure at the attempt bound.
- `poisoned` → `abandoned` on operator skip. `abandoned` does not block successors.
- `poisoned` → `admitted` on operator replay, same `inbox_seq`, attempts reset, fence incremented.
- Duplicate delivery does not change state.

Invariants:

- I1. One row per dedupe key.
- I2. `fence_token` never decreases and increases by one on each successful claim or reclaim.
- I3. Mutable worker updates match owner, fence, and `leased`.
- I4. Per account, zero or one row is `leased`, and it is the minimum `inbox_seq` among rows not in `succeeded` or `abandoned`.
- I5. `poisoned` blocks successors. `succeeded` and `abandoned` do not.
- I6. No success response exists without a committed matching row.
- I7. External-effect count may exceed one. That is not an invariant violation.

### Transaction boundaries

T1, ingest: after authentication, lock the pressure counters, reject if at cap, insert or detect conflict, increment depth only for a new row, commit, then respond. Identical duplicate commits no mutation and still succeeds. Hash mismatch responds conflict and leaves the original row. Database unavailability or timeout is a non-success and inserts nothing.

T2, claim: select the oldest eligible account head `FOR UPDATE SKIP LOCKED`. Eligible means admitted or due retry, or leased with `lease_until <= now()`, and no earlier blocking sibling. Set owner, `lease_until = now() + ttl`, increment fence and attempt, commit, then hand payload, fence, and idempotency key to the worker.

T3, heartbeat: extend `lease_until` only if owner, fence, and `leased` still match. Zero rows means lost fence; the worker must stop. Heartbeat does not increment attempts.

T4, effect: no inbox lock and no open inbox transaction. Pass the same idempotency key on every attempt.

T5, finish: one fenced update to `succeeded`, `retry_scheduled`, or `poisoned`. Clear lease fields. Release pressure only when leaving the blocking set. If the fence no longer matches, update zero rows and do not retry that update.

A completion racing an expiry reclaim is serialized by the row lock. The stale predicate fails. A successor is not claimable merely because the head is locked; it becomes claimable only after the head commits to `succeeded` or `abandoned`.

### Ordering, retries, crashes, backpressure

Workers on other accounts proceed concurrently. Same-account events stay single-flight in `inbox_seq` order. Redelivery after success, poison, or abandonment acknowledges the stored row and does not requeue it.

Retry scheduling uses database time. Crash reclaim consumes an attempt because the crashed attempt may already have performed an effect. Lease loss after the effect was sent is duplicate execution, then one terminal row. The old worker cannot force success.

Exact depth counters in T1 enforce a global cap and a per-account cap. The global counter row serializes admits. Already stored keys bypass the cap so the source can stop retrying. If admission rate makes that hotspot unacceptable, switch only the global cap to a sampled estimate and change the acceptance oracle to a declared overshoot bound. Per-account caps can remain exact.

Terminal payload may be purged only after the redelivery horizon, and the key plus hash must remain. Purging the key early makes a late duplicate look new and reprocesses it.

### Acceptance checks

These are pass/fail oracles. None is claimed as executed.

- Ack: kill before ingest commit and require no success response. Commit, then drop the response; the retry returns success and leaves one row.
- Duplicates: concurrent identical deliveries leave one row and do not add attempts.
- Conflict: different raw body, same key, returns conflict and does not change payload or hash.
- Auth and size: unauthenticated or oversized requests write nothing.
- Reorder: for one account, the first committed event is processed before the second even if the source sent them in the other order.
- Exclusion: two ready events for one account are never both `leased`.
- Parallelism: two ready accounts may be leased by two workers at once.
- Fence: after TTL with no heartbeat, reclaim increases the fence by one; the old owner’s complete and heartbeat update zero rows. A fast worker clock cannot reclaim early.
- Crash window: effect observed, process killed before T5; after reclaim, a second effect is allowed; the final inbox row is still one `succeeded` row. A criterion demanding exactly one external effect fails this design on purpose.
- Bounds: always-retryable work ends `poisoned` at `max_attempts` and is not claimed again. Permanent failure poisons on that attempt. Due time is respected.
- Poison stall: successors stay ineligible until abandon; after abandon, the next head can be claimed. Redelivery does not change poison state or attempt count.
- Pressure: a new key at cap returns pressure failure and inserts nothing; a duplicate of a stored key still succeeds.
- Horizon: a duplicate inside the retention horizon does not create a second row.
- Lock scope: a slow effect does not hold an open inbox transaction across the lease TTL.

## 2. Alternatives discarded

Source-sequence ordering would preserve causal order under reordering, but the stated source fields do not include a sequence. Auto-skipping poison would avoid account stalls and would break the dependency rule, so blocking is the default. A sampled global cap is the scale alternative, not the baseline. `LISTEN/NOTIFY` may wake workers; polling remains the correctness path. A downstream outbox is useful only if the handler must durably remember an intent before an effect; it still does not create exactly-once external effects. Redis or a bus was discarded because the store is one PostgreSQL database.

## 3. Missing evidence

No schema, source contract, retry horizon, or failure taxonomy was supplied. Admission-order dependencies are therefore a contract choice, not an observed source guarantee. If the real source has a monotonic per-account sequence, this design preserves the wrong order. Counter-row contention and retention length are also unknown, so capacity and purge behavior stay conditional.

## 4. Next useful action

Freeze the source contract on sequence-or-admission order, the redelivery horizon, and whether poison blocks. Then implement T1–T5 against the oracles above without treating duplicate external effects as a test failure.

Primary judge's stated reason

A is preferable for its more complete lease-authority boundary, directly supporting safe crash recovery. This is a material specification advantage rather than a slight forced preference: B's stated transaction predicates permit authority to outlive lease expiry. A also supplies an absolute attempt deadline and expiry-aware renewal, making the recovery contract more actionable. Neither answer establishes implementation correctness or executed test success.

This reason is the judge's assessment. No independent factual-defect finding is asserted by this record.

Battle wave: 1fb32bda-9041-4f2e-818c-0fd4669031e2. Pair: brp1_3aadf392d60660b1fb28b6b4adb539cb02cd3875edcf5b69bc80737d115f0ef3. A separate independent review is required before calling a concern a verified factual defect. Judge disagreement is not recorded here.