openai / gpt-6.1-sol / low / low effort preferred over xai / grok-4.7-efficient / high / high 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.1-sol / low / low effort answer
## Recommendation and assumptions
Use PostgreSQL as the durable inbox, scheduler, and authority for worker ownership. A successful HTTP acknowledgement means **the delivery is durably recorded**, not processed. Processing is retryable; database effects can be atomic with completion, but arbitrary external effects are not exactly once.
This is an independent design based only on the supplied requirements; no source inspection or tests were performed.
Assumptions and required contracts:
- Authentication determines `source_id` and authorizes the supplied `account_id`; neither is trusted merely because it appears in the payload.
- Deduplication identity is `(source_id, account_id, event_id)`.
- PostgreSQL commit durability is configured to match the promised failure model. If success must survive primary loss, synchronous replication and failover fencing are required; local durable WAL alone is insufficient.
- **Delivery order cannot establish causal order.** Require a source-provided account sequence or explicit predecessor IDs. The design below uses explicit predecessor IDs. If neither exists, only serial processing in an arbitrary observed order is possible—not preservation of unknown dependencies.
- Dependency IDs use the same source/account scope, and handlers have versioned, validated payload contracts.
- External calls have bounded deadlines. Downstream idempotency or fencing support is used where available.
## Persistent model and invariants
An `inbox_event` row contains:
- Identity, immutable payload, canonical payload digest, receipt time, handler version.
- State: `waiting`, `ready`, `running`, `retry_wait`, `succeeded`, `dead`, or `skipped`.
- Attempt count, next eligible time, first-attempt time, error classification.
- Current owner, lease expiry, and account fencing token.
Additional tables:
- `event_dependency(event, predecessor_identity)`: predecessor identities can exist before their events arrive.
- `account_lane`: one row per source/account, holding current event, owner, lease expiry, and monotonically increasing fencing token.
- Optional transactional outbox for external commands.
- Compact deduplication tombstones if completed payloads are removed.
Constraints and invariants:
1. A unique constraint enforces deduplication identity.
2. Duplicate delivery never changes payload or dependencies.
3. An event is runnable only when every prerequisite has succeeded or has been explicitly waived by an audited policy.
4. At most one **current database-authorized** worker exists per account.
5. Every claim increments the account fencing token; every worker mutation checks that token and an unexpired lease.
6. Terminal states are not changed by automatic retries.
7. A worker may still execute code after losing ownership; database fencing does not physically stop it.
8. Deduplication lasts only as long as identity records are retained. Define a replay horizon, or retain tombstones indefinitely.
Multiple independent ready events within an account may be processed in deterministic receipt/identity order. This does not assert causal ordering between them.
## Transactions and state transitions
### 1. Receive and acknowledge
Before opening a transaction, authenticate, authorize account scope, enforce size limits, and perform cheap structural validation.
In one transaction:
1. Create the account lane if needed.
2. Insert the event and its immutable dependency records.
3. On unique conflict, compare canonical digest and dependency metadata:
- Identical: treat as a duplicate.
- Different: return an identity-conflict error; do not overwrite.
4. Commit.
Return `2xx` only after confirmed commit. A duplicate may receive `2xx` even if the original is still waiting or already dead: it has been durably accepted.
A commit timeout or lost response has an **unknown** outcome. Return a retriable failure, never assert rollback; the sender repeats the same identity.
Authenticated, structurally valid events with invalid business content can be durably recorded as `dead`. Clearly malformed requests can instead receive a permanent `4xx`; document this distinction.
### 2. Claim
Workers poll; notifications are optional wake-up hints, never the source of truth.
In a short transaction:
1. Select and lock an eligible account lane using `FOR UPDATE SKIP LOCKED`.
2. If its current event has expired, reclaim that event before starting another account event.
3. Otherwise choose a due `ready`/`retry_wait` event, or a `waiting` event whose prerequisites now satisfy the rule.
4. Check retry and age limits.
5. Increment the lane token, increment the attempt count, set owner and lease expiry using database time, and transition the event to `running`.
6. Commit, then execute outside the transaction.
All paths lock lane before event to avoid inconsistent lock order. Eligibility indexes should cover state and retry time; dependency lookups need predecessor identity indexes.
### 3. Renew
Renew in a short transaction using a conditional update matching lane, event, owner, token, `running` state, and `lease_until > clock_timestamp()`.
Renew both lane and event atomically. Zero affected rows means ownership is lost; stop initiating effects. An expired worker cannot resurrect its lease even if nobody has reclaimed it.
Use database time, not worker clocks. Set renewal cadence comfortably below lease duration; enforce an overall processing deadline so heartbeats cannot preserve a hung attempt forever.
### 4. Finish successfully
Lock the lane and verify current ownership, fencing token, and lease.
- **Database-only effects:** apply business changes and set `succeeded` in the same transaction; release the lane atomically. A stale worker’s entire transaction must roll back.
- **External work via outbox:** commit the business transition, unique outbox command, and event completion atomically. Here, `succeeded` means “command durably scheduled,” not “remote action confirmed.”
- **Direct external call:** perform it outside a database transaction, then conditionally record completion. An unknown remote outcome remains possible.
Do not hold lane locks across network calls.
### 5. Fail or expire
A current worker records a classified failure and either:
- Sets `retry_wait`, computes capped exponential backoff with jitter, and releases the lane.
- Sets `dead` when the failure is permanent, attempt limit is reached, or maximum processing age is exceeded.
Lease expiration permits reclamation with a **new** token. Expired claims count toward the attempt budget, including crashes before handler execution. A recovery worker marks exhausted expired events dead rather than leaving them stranded.
Retry limits, age limits, lease duration, and error classifications are explicit configuration—not unbounded defaults.
## Dependencies and poison events
A missing predecessor keeps an event in `waiting`; later arrival makes it eligible. Periodic reconciliation is necessary even if notifications are lost.
- A dead prerequisite blocks its dependents by default.
- A deadline for missing prerequisites triggers an alert and quarantine reason; it must not silently authorize processing.
- Cycles are invalid. Validate self-dependencies immediately and detect larger cycles through transactional validation or reconciliation.
- Poison events do not monopolize workers through tight retry loops.
- Independent events may continue; descendants remain blocked.
- Operators may explicitly waive a dependency, skip an event, or authorize a bounded replay. Record actor, reason, prior state, and replay generation; never reset the fencing counter.
If strict contiguous account sequence is required instead, use an account cursor and source sequence numbers. Gaps then block all later sequence entries, and an explicit gap-resolution policy is mandatory.
## External effects and crash recovery
Use a stable external idempotency key derived from event identity and effect name—not the retry attempt. Multiple effects need separate persistent effect records.
A downstream service can enforce fencing only if it checks tokens atomically with its effects. A token included merely as request metadata provides no protection. The downstream idempotency retention window must cover possible retries and replays.
Without downstream guarantees:
- A worker can perform an external effect and crash before recording success.
- A retry can repeat that effect.
- A stale worker can act after its lease expires.
Therefore the guarantee is durable intake and retryable processing, with possible duplicate external effects. An outbox closes the database-to-command persistence gap, but its dispatcher still needs downstream idempotency or reconciliation.
Crash recovery follows stored state:
| Crash point | Recovery |
|---|---|
| Before intake commit | Sender retries; no acknowledgement was promised. |
| After intake commit, before response | Duplicate delivery finds the existing row. |
| After claim, before completion | Lease expires; bounded retry with a new token. |
| During database-effect transaction | Effects and completion commit together or roll back together. |
| After external effect, before completion | Retry/reconcile an ambiguous outcome; duplication is possible. |
| After completion commit | Event is terminal and not automatically reprocessed. |
## Backpressure and operations
Set explicit limits for request size, admitted event count/bytes, per-account backlog, worker concurrency, database connections, and external-call concurrency.
For race-free admission, reserve bounded capacity inside the intake transaction—for example through locked capacity counters. Check an existing duplicate before denying a new capacity reservation.
- Reject new work with `429` or `503` and `Retry-After` when capacity is exhausted.
- Never acknowledge an unpersisted event.
- Reserve headroom for duplicate acknowledgements, recovery, terminal-state updates, and operational access.
- Separate per-account limits from global limits and schedule lanes fairly to avoid noisy-account starvation.
- Require sender retries or reconciliation for rejected work; admission rejection can otherwise lose events permanently.
Monitor queue depth/bytes, oldest runnable and waiting ages, missing prerequisites, dead count, retries, expired leases, fencing rejections, intake commit failures, outbox age, and storage headroom. Retention must preserve identities and dependency-resolution evidence.
## Measurable acceptance checks
These are proposed checks, not executed results. Set concrete operational thresholds before testing.
| Test | Pass condition |
|---|---|
| Concurrent identical deliveries | Exactly one identity row; all successful responses follow a durable commit. |
| Same identity, different content | Original remains unchanged; conflicting delivery receives the documented non-success response. |
| Crash around acknowledgement | Every observed `2xx` has a recoverable row under the stated durability model; uncertain outcomes deduplicate on retry. |
| Reordered dependencies | Dependent handler never starts before its prerequisite satisfies the declared completion rule. |
| Missing predecessor/cycle | No unauthorized processing; configured deadline produces a visible quarantine/alert. |
| Multi-worker contention | Never more than one current valid lane owner; no duplicate committed database effect. |
| Lease-expiry race | Old-token renewal, failure, and completion mutations affect zero rows after expiration/reclaim. |
| Database-effect crash injection | Every tested interruption leaves both effect and completion committed, or neither. |
| External ambiguity injection | No exactly-once claim; documented duplicate/reconciliation behavior occurs. With downstream idempotency, repeated keys produce one logical effect. |
| Poison event | Handler claims never exceed configured automatic limits; descendants remain blocked; independent work progresses. |
| Notification loss/restart | Polling recovers eligible and expired work within the configured recovery bound. |
| Capacity exhaustion | New admissions stop at configured reservations; duplicates remain serviceable within reserved headroom; no rejected request is acknowledged as accepted. |
| Retention/replay | Replays within the promised horizon deduplicate and dependencies remain resolvable. |
| Fairness | A continuously eligible account receives service within a specified bound under the declared load envelope. |
## Alternatives, uncertainties, and next action
- Strict sequence cursors are simpler when the source supplies complete ordering; explicit dependencies allow independent progress but require cycle and missing-parent handling.
- Long transactions around external calls are rejected: they consume connections and do not solve remote atomicity.
- In-memory deduplication and locks are insufficient across crashes and workers.
- Unbounded retries or silently skipping poison predecessors violate the durability/dependency contract.
**Confidence:** high in the transaction and fencing pattern; actual durability, capacity, and downstream-effect guarantees depend on deployment and source contracts.
**Next action:** establish the source’s ordering metadata, PostgreSQL failure model, external idempotency contract, and numeric limits; then implement and run the acceptance matrix with crash and lease-race injection.
xai / grok-4.7-efficient / high / high effort answer
The coherent design is a primary-only PostgreSQL inbox: acknowledge a delivery only after a committed deduplicated row, then let workers claim one per-account head at a time with expiring, fenced leases. Acceptance is exactly-once for the retention window; handling is at-least-once. This does not provide exactly-once external effects.
## 1. Design
### Requirements
- Authenticate the source before any write. Persist `source_id`, `account_id`, `event_id`, and exact payload bytes, then commit, then return success.
- Deduplicate on `(source_id, account_id, event_id)`. Identical redeliveries ack again and create no second obligation. Same key with different bytes is a conflict and must not overwrite.
- Deliveries may be duplicated and reordered. Per-account source order is still the processing order.
- Many workers may run. At most one live lease exists per account. A lease expires, and a later claim fences the crashed holder.
- Retry attempts, including claims that crash, are bounded. Exhausted or non-retryable events become poison and block only that account.
- Crash recovery must not leave a permanent lease and must not be described as exactly-once downstream execution.
- Backpressure rejects new keys without persisting them. Already-accepted duplicates still succeed so the source can stop retrying.
### Assumptions
- One PostgreSQL primary is the only coordination store. Accept, claim, renew, and complete use the primary. Accept transactions run with `synchronous_commit=on`. Durability means local WAL flush before commit returns, not a proven replicated standby.
- Workers are fail-stop and cooperative, not Byzantine. A worker with unrestricted write credentials can bypass fencing SQL. Enforcement is the conditional `UPDATE`, not trust in worker memory.
- The authenticated source supplies a contiguous per-account `sequence` starting at 1, in addition to `eventID`, `accountID`, and payload. Opaque `eventID`s alone cannot reconstruct order after reordering.
- Payload identity is the exact received bytes, hashed with SHA-256. Semantic JSON equality is not used.
- Database time (`clock_timestamp()`) is authoritative. Worker wall clocks are not.
- Downstream handlers are idempotent on `(source_id, account_id, event_id)`, or they tolerate duplicates. The inbox does not run two-phase commit with the effect destination.
- Terminal rows are retained at least as long as the source’s retry horizon. Workers use a new incarnation id after restart.
- Isolation is Read Committed. Ownership is decided only by single-row `UPDATE ... WHERE` predicates, never by a prior `SELECT` kept in application memory.
### Data and invariants
`inbox_events` stores the identity, `sequence`, `payload_bytes`, `payload_hash`, `state`, `attempt_count`, `max_attempts`, `available_at`, `lease_owner`, `lease_token`, `lease_expires_at`, and error class. Uniqueness: `(source_id, account_id, event_id)` and `(source_id, account_id, sequence)`. A partial unique index on `(source_id, account_id) WHERE state = 'leased'` enforces single-flight.
`account_cursors` stores `(source_id, account_id)`, `next_sequence` starting at 1, and `nonterminal_count`. Hashed `ingress_gate` rows hold exact bucket counts so a global cap does not require one counter row for every insert. Lock order is gate bucket, then account cursor, then event insert.
Invariants:
- A 2xx for a new key occurs only after that key’s commit. A crash before commit yields no success response and no row.
- `lease_token` increases by one on every claim or reclaim and is never reused.
- A leased row changes to `succeeded`, `retry_wait`, or `poisoned` only when id, token, owner, `state='leased'`, and `lease_expires_at > clock_timestamp()` all match.
- `next_sequence` advances by exactly one in the same transaction that marks that sequence `succeeded` or operator-`skipped`.
- No sequence greater than `next_sequence` can be leased. A missing head stalls the account and does not consume attempts.
- `attempt_count` increments only when a claim or reclaim is committed. Poison is not claimable. Other accounts remain claimable.
- External I/O never runs inside a database transaction.
### States
`accepted` means durably stored and not the claimable head, or waiting for backoff. `leased` means a token holder owns it until database expiry. `retry_wait` means a fenced retryable failure is waiting for `available_at`. `succeeded` means a fenced handler completion was committed, not that the external effect happened once. `poisoned` means attempts are exhausted or the error class is non-retryable; this blocks the account. `skipped` is an audited operator break of that dependency. Auth, validation, capacity, and payload-conflict failures are not stored as events.
Transitions: insert to `accepted`; claim of `sequence = next_sequence` to `leased`; fenced success plus cursor advance to `succeeded`; fenced retryable failure to `retry_wait`; fenced exhaustion or non-retryable failure to `poisoned`; expired `leased` is reclaimed with a new token or becomes `poisoned` if attempts are already exhausted; operator action moves `poisoned` to `accepted` with attempts reset, or to `skipped` with a one-step cursor advance. Duplicates and stale fence writes do not change state.
### Transaction boundaries
- **Authenticate outside a write transaction.** Failure returns 401 or 403 and writes nothing.
- **Accept:** lock the gate bucket and account cursor; reject a new key over the global or per-account cap; insert the event and increment counters; commit; only then return 200. On event-id conflict, read the committed row, return 200 for the same hash, or 409 for a different hash. If the concurrent inserter aborted and the row is absent, retry the insert. A new event id whose sequence is already taken returns 409 and does not ack success.
- **Claim:** one short transaction selects the eligible head `FOR UPDATE SKIP LOCKED`, increments token and `attempt_count`, sets owner and expiry, and commits. If this claim would exceed `max_attempts`, set `poisoned` instead of leasing. No handler call is inside this transaction.
- **Renew:** conditional expiry extension with the same fence. Zero rows means stop and do not rely on a later complete.
- **Effect:** outside any transaction, call the handler with the idempotency key. A lease expiry here means another worker may also run the handler.
- **Complete or fail:** one short fenced transaction. Success sets `succeeded` and advances `next_sequence` only if it still equals this sequence. Retryable failure sets `retry_wait` and `available_at` from database time using bounded exponential backoff plus jitter, without a second attempt increment. Non-retryable failure or exhausted attempts sets `poisoned` and does not advance the cursor.
- **Reclaim** is another claim of an expired lease, not a background unlock service. Correctness does not depend on `LISTEN/NOTIFY`; notification may wake workers, but polling is required because notifications are not durable.
- **Operator skip or replay** is a separate audited transaction. Skip advances the cursor once. Replay resets attempts and does not advance it.
Backoff parameters, lease length, caps, poll interval, and retention are named policy, not measured capacities.
### Backpressure
- New keys over the per-account cap or a gate-bucket global cap return 429 with `Retry-After` and are not inserted.
- Payload over the configured byte limit returns 413 and is not inserted.
- Missing identity, non-positive sequence, or invalid sequence returns 400 and is not inserted.
- Pool exhaustion or database unavailability returns 503 and is not success.
- Identical duplicates of a stored key still return 200 while over cap; otherwise the source would retry forever.
- Each worker has a fixed claim concurrency. Empty polls sleep with jitter. A poisoned or gapped account occupies no worker slot. Only that account’s later sequences wait.
- Terminal rows are deleted only after the configured retention. Poisoned rows are not auto-deleted.
### Crash and effect contract
If the effect succeeds and the worker crashes before the fenced complete, expiry causes another claim and the handler can run again. If complete commits and the worker crashes before its own bookkeeping, the row stays `succeeded` and ingress duplicates only ack. A stale holder’s late complete matches zero rows and must not advance the cursor. No path claims exactly-once external effects.
### Acceptance checks
These are pass/fail criteria, not executed results.
- Pass iff every 200 has a committed matching row after primary recovery, and a pre-commit crash has neither 200 nor a row.
- Pass iff concurrent identical deliveries create one row and all return 200, including when the unique-conflict inserter loses.
- Pass iff a same-key different payload returns 409 and leaves the original bytes and hash unchanged.
- Pass iff sequences delivered as 3, then 1, then 2 are handled in order 1, 2, 3.
- Pass iff withheld sequence 2 prevents 3 from being leased, consumes no attempts, and a late 2 unblocks it without an operator skip.
- Pass iff killing a holder and waiting past database expiry lets another worker reclaim with a greater token, while the old token’s complete or fail updates zero rows.
- Pass iff ten workers produce never more than one `leased` row per account, while another account can still finish while the first is poisoned.
- Pass iff repeated retryable failure or crash-before-complete reaches `poisoned` at `max_attempts` and produces no further claims; a non-retryable class poisons even when attempts remain.
- Pass iff a new key at either cap is absent and not 200, while an existing duplicate is still 200.
- Pass iff auth failure and oversize payload persist nothing.
- Pass iff a lease renewal and reclaim race leaves exactly one winner under Read Committed conditional updates.
- Pass iff no handler call holds an open or idle transaction, and expiry math does not use worker-local time.
- A replay after terminal deletion may create a new obligation. That is a failure of the retention assumption, not recovery of exactly-once delivery.
## 2. Alternatives and discarded hypotheses
- Receipt order per account was discarded as the primary order. It is simple and avoids gaps, but reordered delivery becomes reordered processing, so it does not preserve source dependencies. It is the fallback only if no sequence or predecessor exists.
- A predecessor graph is viable when dependencies are partial rather than a total account order. It needs cycle rejection and a rule for multiple roots; contiguous sequence is the tighter, testable special case.
- Advisory locks, expiry without a token, and check-then-act ownership were discarded. None stops a stale commit after lock loss or reclaim.
- Incrementing attempts only on an explicit failure was discarded. A crash loop would never reach poison.
- Overwriting conflicting payload, treating gap timeout as an automatic skip, and using a global FIFO were discarded. They break identity, silently break dependencies, or let one account block others.
- `LISTEN/NOTIFY`, Redis, or SQS as the durability path was discarded. Notifications are lossy, and a second queue creates a dual-write the single-database requirement does not need.
- Two-phase commit or an “exactly-once handler” claim was discarded. Generic webhook destinations do not provide that transaction.
## 3. Missing evidence
No source, schema, provider retry contract, or handler contract was supplied. The ordering field, byte-identical payload rule, local-WAL durability bar, fail-stop worker model, and retention horizon are therefore assumptions. If any is false, the corresponding guarantee is unsupported: in particular, unordered event IDs cannot preserve source order, and retention shorter than source retries cannot preserve deduplication. No latency, cost, or capacity figure is asserted.
## 4. Next useful action
Confirm, from the source contract, whether a contiguous per-account sequence or an explicit predecessor exists, how long the source retries, and whether payload equality is exact bytes. Those three facts decide whether this primary design can be implemented or must fall back to serial receipt order without a source-order claim.
Primary judge's stated reason
A receives a slight, forced preference because its explicit ambiguous-commit guidance better supports correct intake failure handling. Both answers substantially satisfy the complete assignment, including bounded crash retries, fencing, dependencies, backpressure, and proposed acceptance checks. This is not an established material quality gap; an independent review could reasonably favor B's more concrete sequence model.
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_5b750b9c9a9de8bacfbd0f11db67216ce5d2065ea6400516358b2f2e0d7f983a. A separate independent review is required before calling a concern a verified factual defect. Judge disagreement is not recorded here.