← Model losses

Head-to-head comparison

openai / gpt-6-luna / low / low effort preferred over xai / grok-4.7-efficient / medium / medium effort · close 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-luna / low / low effort answer

## Recommendation

Use a durable inbox table as the acknowledgement boundary and a separate per-account cursor/lock to serialize dependent processing. Acknowledge a delivery only after the inbox insert or deduplication check commits. Workers claim eligible events using short transactions and expiring leases with monotonically increasing fencing tokens. Order events within each account by a defined source ordering key; `eventID` alone is not necessarily an ordering key.

This design provides durable acceptance and at-least-once processing attempts. It does **not** guarantee exactly-once external effects: a worker can perform an effect and crash before recording completion. Require idempotent downstream operations, an outbox, or reconciliation where duplicate effects matter.

## Requirements and assumptions

- Authenticate the source and bind its identity to the deduplication key; do not trust a caller-supplied source identity.
- Key uniqueness by `(source_id, account_id, event_id)`. Retain deduplication records for at least the maximum possible redelivery horizon, or indefinitely if that horizon is unknown.
- Store the payload and required metadata durably in PostgreSQL before returning success.
- Assume the source provides a per-account ordering sequence/version (or define another authoritative dependency relation). If it does not, strict causal ordering cannot be inferred from reordered deliveries; buffer for a bounded gap or reject/quarantine unresolved ordering.
- Define payload size limits, retry policy, poison-event handling, retention, and operational recovery procedures before launch.

## State and invariants

An inbox row includes the deduplication key, ordering key, payload, received time, state, attempt count, `next_attempt_at`, lease expiry, lease owner, fencing token, and error/dead-letter metadata.

States: `pending`, `leased`, `retry_wait`, `succeeded`, `dead_letter`. Terminal states are `succeeded` and `dead_letter`; redrive is an explicit audited transition back to `pending`.

Invariants:

1. A success response implies the authenticated event and deduplication key are committed.
2. One durable row exists per deduplication key. A duplicate with matching content returns success without creating work; a conflicting payload for the same key is recorded/alerted and does not overwrite the accepted event.
3. An account’s next event is not claimable until all earlier required events have succeeded or an explicit operator policy has resolved the blocker. Dead-lettering does not silently advance the account.
4. Only the current lease holder with the current fencing token may change a leased row or mark it complete.
5. Retries and event age are bounded by policy; exhaustion leads to durable dead-letter state, not infinite retry.

## Transactions and crash recovery

**Receive:** In one transaction, insert the inbox row with `ON CONFLICT` handling and commit. Return 2xx only after commit. If PostgreSQL is unavailable, the transaction times out, authentication fails, validation fails, or capacity limits reject the event, do not return success. Return retryable failure for transient storage/backpressure conditions; use appropriate client-error responses for invalid or unauthorized requests. A response lost after commit is safe: redelivery hits the unique key.

**Claim:** In a short transaction, select eligible account heads with `FOR UPDATE SKIP LOCKED`, mark them `leased`, set owner and expiry, increment the fencing token and attempt count, then commit. Never hold a database transaction open while calling an external service. Expired leases become eligible for reclaim; reclaim increments the token so a stale worker cannot update inbox state.

**Process/finish:** Perform work outside the claim transaction. In a new transaction, record success (and advance the account cursor, if used) only with a conditional update matching row ID, `leased` state, owner, and fencing token. On retryable failure, conditionally set `retry_wait` and a bounded backoff time; on permanent failure or exhausted attempts/age, set `dead_letter`. A crash before finish leaves an expiring lease; a crash after an external effect but before finish can cause a duplicate effect. Fencing protects database state, not arbitrary external systems. Pass the token to downstream systems when they can reject stale tokens, and use an idempotency key/outbox for duplicate-effect control.

## Backpressure and acceptance checks

Bound request body size, database connections, queue depth, per-account backlog, and worker concurrency. Apply admission limits before accepting; reject rather than acknowledge events that cannot be durably stored. Alert on oldest pending age, lease expiry/reclaim rate, retry volume, dead letters, storage pressure, and account blockers. Keep dead letters inspectable and redrivable with audit history.

Measurable pass/fail checks:

- **Durability:** After a 2xx, restart the service and database under the declared durability configuration; the event remains queryable. Any acknowledged-but-lost event is a failure.
- **Deduplication:** Submit the same key concurrently and repeatedly; exactly one inbox row exists and every valid duplicate receives the documented response. Conflicting content is not silently substituted.
- **Ordering:** Deliver account sequence numbers out of order and concurrently; later events do not execute before required predecessors. Different accounts may progress independently.
- **Lease/fencing:** Pause a worker past lease expiry, reclaim with another worker, then resume the old worker; its stale completion/update is rejected.
- **Crash recovery:** Crash before processing, during processing, and after an external effect but before completion; work is reclaimed, and duplicate external effects are either prevented by the downstream idempotency mechanism or explicitly accepted and reconciled.
- **Retry/poison:** Inject transient and permanent failures; retries follow configured bounds, and exhausted/permanent failures reach durable dead-letter state without silently unblocking dependent events.
- **Backpressure/failure:** Exhaust configured admission capacity or make PostgreSQL unavailable; the service never returns success without commit and returns the documented failure response within its timeout.
- **Redrive:** Redrive a dead letter; audit data is preserved, and per-account ordering policy remains enforced.

Alternatives include a per-account advisory lock instead of a cursor, or a transactional outbox for downstream publication. Advisory locks can simplify serialization but require careful lease/crash semantics; an outbox makes database-to-message publication atomic but downstream consumers still need idempotency. No source inspection or tests were supplied or performed; actual guarantees depend on PostgreSQL durability settings, source ordering semantics, and downstream capabilities.

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 receives a weak, forced preference because refusing to infer causal dependencies from reordered arrival better protects the requested dependency guarantee. B offers stronger operational detail and could be preferable under an explicitly admission-ordered contract. This judgment does not establish a material overall quality gap; an independent review could reasonably weigh that tradeoff differently.

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_35d67d3a0dee3d9b3fadd7a78096d9ff477c8b801985aef46ecfeff7df2a3b63. A separate independent review is required before calling a concern a verified factual defect. Judge disagreement is not recorded here.