← Model losses

Head-to-head comparison

openai / gpt-6.1-sol / xhigh / xhigh effort preferred over openai / gpt-6-luna / low / low 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.1-sol / xhigh / xhigh effort answer

## Recommended design

Use a PostgreSQL-backed inbox with immutable deduplication records, one eligible event per account, bounded expiring leases, and fenced completion transactions. Guarantee durable acceptance and atomic local effects—not exactly-once external effects.

This is an independent, reasoning-only design; no implementation, source inspection, or tests were supplied.

## 1. Requirements and necessary assumptions

### Acceptance contract

A successful HTTP response means:

> This delivery, or an identical earlier delivery, has been durably recorded.

It does **not** mean processing succeeded. A duplicate of a failed event still receives an acknowledgement; delivery retries must not silently restart processing.

Assume:

- Authentication identifies a stable `source_id`, and authorization binds that source to `account_id`.
- `(source_id, account_id, event_id)` identifies one immutable event.
- PostgreSQL uses durable WAL settings, including `fsync=on` and `synchronous_commit=on`.
- Workers can crash, pause beyond lease expiry, and lose responses.
- Availability and recovery guarantees assume PostgreSQL and its durable storage eventually recover. One database does not protect against permanent destruction of its storage.

### Dependency contract

Opaque event IDs and reordered deliveries do **not** reveal causal order.

For the primary design, require the authenticated payload to contain a gap-free, monotonically increasing account sequence number. Provision each account with an authoritative starting sequence. Never infer the starting point from the first delivery received.

Dependencies are scoped to `(source_id, account_id)`. Cross-source dependencies require an additional authoritative ordering contract.

Without sequence or predecessor metadata, the available alternative is arrival-order serialization. That prevents simultaneous account processing but cannot reconstruct source order or preserve unknown dependencies.

## 2. Durable state and invariants

### Tables

**`inbox_event`**

- `source_id`, `account_id`, `event_id`: primary key.
- `sequence`: unique within source/account.
- Immutable payload and payload digest.
- `received_at`.
- `state`: `PENDING`, `LEASED`, `SUCCEEDED`, `DEAD`, or `SKIPPED`.
- `attempt_count`, `next_attempt_at`, `retry_deadline`.
- `lease_owner`, `lease_fence`, `lease_until`, `attempt_started_at`.
- Last classified error and completion metadata.

**`inbox_account`**

- Source/account primary key.
- `last_resolved_sequence`.
- Monotonically increasing `fence_counter`.
- Scheduling and gap-observation metadata.

**Resolution/audit records**

Record successful resolutions and explicitly authorized dependency waivers. Never represent a waiver as successful execution.

Use a partial unique index allowing at most one `LEASED` event per source/account.

### Invariants

1. One immutable record exists for each accepted deduplication key.
2. Only `sequence = last_resolved_sequence + 1` may be claimed.
3. A cursor advances only through successful completion or an explicit, audited business-authorized waiver.
4. Every lease grant receives a strictly newer account fence.
5. Only the current, unexpired lease may authorize local completion or renewal.
6. Business mutations, completion state, and cursor advancement commit atomically.
7. `DEAD` does not advance the account cursor.
8. Physical execution may overlap after expiry; only one execution has current database authority.

Retain deduplication tombstones for at least the source’s maximum replay horizon. If arbitrary old duplicates must remain deduplicated forever, retain them indefinitely. Payload deletion must not delete the identity, sequence, or conflict-detection information required by that contract.

## 3. Transaction boundaries and transitions

### A. Receive and acknowledge

Before admission:

- Verify authentication and account authorization.
- Enforce request-size, identifier-size, and schema limits.
- Extract and validate sequence metadata.
- Define payload equality explicitly—for example, canonical validated JSON bytes. Use a digest for lookup efficiency, with exact canonical-content comparison where needed.

For an existing committed key:

- Identical content and sequence: return success without creating work.
- Different content or sequence: reject, for example with `409`, and alert. Never overwrite the original.

For a new event, execute one short admission transaction:

1. Acquire capacity reservations and the account row in a consistent lock order.
2. Repeat the deduplication check to handle concurrent deliveries.
3. Validate sequence uniqueness, account baseline, and admission limits.
4. Insert `PENDING`.
5. Update capacity accounting.
6. Commit.

Only then return success. A lost connection during `COMMIT` has an uncertain outcome: return no success, and let a retry resolve it through deduplication.

Malformed or unauthorized requests are rejected without admission. A sequence collision with another event ID is a source-contract violation, not another valid delivery.

### B. Claim

Workers periodically scan eligible accounts using short transactions and `FOR UPDATE SKIP LOCKED`. Notifications may reduce latency but are never the sole wake-up mechanism.

Within the transaction:

1. Lock the account, then its next unresolved event.
2. Sample fresh database time **after** acquiring locks.
3. Require the head event to be pending, due, within its deadline, and below its attempt limit.
4. Increment `attempt_count` and the account fence.
5. Set `LEASED`, a fresh owner identifier, the fence, and an expiry.
6. Commit.

Perform computation or network operations outside this transaction.

All account/event mutation paths use the same lock order. Transactions updating global capacity acquire capacity locks before account/event locks.

### C. Renew

A renewal transaction must verify:

- State is `LEASED`.
- Owner and fence match.
- The lease has not expired.
- The event is still the account head.

Extend only up to:

```text
min(database_now + lease_duration,
    attempt_started_at + maximum_attempt_runtime,
    retry_deadline)
```

A worker cannot keep one attempt alive indefinitely. Failed renewal means it must stop initiating work; cancellation cannot retract an already-issued external request.

### D. Complete

Lock account then event, and conditionally verify the current lease and head position. In the same transaction:

- Apply all local business mutations.
- Insert any durable external-effect intents.
- Mark the event `SUCCEEDED`.
- Record its resolution and advance the account cursor.
- Commit.

If the ownership check fails, perform no local mutations. If anything fails before commit, roll back everything.

Lease authorization is evaluated at a database linearization point while the relevant rows are locked. Expiry does not forcibly abort an already-authorized transaction; keep these transactions short and enforce statement and lock timeouts.

### E. Failure, expiry, and poison handling

Transitions are:

```text
PENDING → LEASED → SUCCEEDED
              ↘ PENDING       transient failure or expired attempt
              ↘ DEAD          permanent failure or exhausted budget

DEAD → PENDING                explicitly authorized, audited retry
DEAD → SKIPPED                explicitly authorized dependency waiver
```

For transient failures or expired attempts:

- Clear lease ownership.
- Schedule capped exponential backoff with jitter.
- Mark `DEAD` instead if attempts or the total retry deadline are exhausted.

Count attempts on **claim**, so crashing workers consume the budget.

Permanent business-validation failures become `DEAD` immediately. Missing predecessors do not consume processing attempts, but generate gap alerts; a configured dependency-wait deadline can mark affected events `DEAD` with a dependency-timeout reason.

A poisoned head blocks its account, not other accounts. Operators may repair the handler or required reference data and grant an audited, finite retry budget. They must not silently mutate accepted payloads, reset attempts indefinitely, or skip prerequisites automatically.

Missing events require authoritative replay or an explicit domain-authorized gap waiver.

## 4. External effects and fencing limits

Prefer performing local changes and inserting an outbox record in the completion transaction. An outbox makes external intent durable; its publisher still requires retries, leases, and duplicate handling.

For every external operation, use a stable idempotency key such as:

```text
(source_id, account_id, event_id, effect_name)
```

Do not include the attempt number.

If the destination supports fencing, send the account fence. The destination must atomically compare/store the fence and apply the operation. A lower fence is rejected after a newer fence has been established.

Important limits:

- A destination without idempotency may apply an operation again after “effect succeeded, response lost.”
- A stale worker may have already issued a request before losing its lease.
- Fencing alone does not deduplicate repeated requests carrying the same fence.
- Checking PostgreSQL ownership immediately before a remote call does not eliminate the check-to-call race.

Define dependency completion precisely:

- **Local-state dependencies:** completion means the local mutation and any outbox intent committed.
- **External-result dependencies:** do not release a dependent event until the predecessor’s required external result is confirmed. Use a separate effect-pending stage or ordered publisher, plus downstream idempotency/fencing.

Without destination cooperation, strict external ordering under stale in-flight requests cannot be guaranteed. Do not describe this system as exactly-once externally.

## 5. Backpressure, retention, and recovery

Configure explicit limits for:

- Payload size.
- Retained payload bytes and unresolved event counts, globally and per account.
- Ahead-of-cursor sequence window.
- Worker concurrency and external-request concurrency.
- Attempts, attempt runtime, total retry age, and dependency-wait time.
- Database connections and transaction timeouts.

Admission limits must use transactional reservations, not an unlocked `COUNT(*)`. Count retained storage until it is actually reclaimed or archived.

At capacity:

- Existing identical duplicates remain acknowledgeable.
- New events receive a retryable response such as `429` with `Retry-After`.
- Database unavailability or inability to commit receives `503`, never success.
- Preserve disk/WAL headroom rather than admitting until the filesystem is full.

These policies depend on the source retrying long enough or supporting replay. Rejected deliveries are not durable inbox entries.

Recovery requires no worker memory:

- Committed pending events remain discoverable.
- Expired leases are requeued or terminated by a sweeper or claim path.
- Committed completion is terminal despite a lost worker response.
- Fair scheduling and per-account isolation prevent one blocked or busy account from monopolizing workers.

Monitor queue age, missing-sequence age, expired leases, retries, dead heads, admission rejections, storage headroom, and scheduler lag.

## 6. Measurable acceptance checks

These are proposed tests—not executed results. Configure lease duration `L`, sweep interval `S`, retry limits `M/R`, runtime limit `H`, and capacity `B` before testing.

| Scenario | Pass condition |
|---|---|
| Concurrent duplicates | Send 100 identical deliveries from 20 clients. Exactly one inbox record and one processing lineage exist; successful responses refer to committed acceptance. |
| Conflicting duplicate | Same key with changed payload or sequence is rejected; original content remains unchanged. |
| Sequence collision | Different event IDs using one account sequence cannot both be admitted. |
| Authentication | Invalid credentials or unauthorized accounts create no inbox record. |
| Acknowledgement durability | Crash PostgreSQL immediately after observed successes, preserving durable storage. Every acknowledged identity remains recoverable after restart. |
| Ambiguous commit | Drop the connection during commit, then retry. There is one durable record whether the first transaction committed or rolled back. |
| Reordering | Deliver sequences `3, 1, 2`. Local business mutations commit in order `1, 2, 3`. |
| Missing predecessor | Deliver only sequence `2` with a baseline expecting `1`. No processing attempt for `2` starts; configured alert/timeout behavior occurs without cursor advancement. |
| Lease takeover | Pause worker A beyond expiry; worker B acquires a newer fence. A’s renewal and completion are rejected, with no local mutations. |
| Crash before completion | Crash after claim or during the completion transaction. Uncommitted local changes disappear; recovery schedules another attempt. |
| Crash after completion | Crash after completion commit but before worker acknowledgement. The event is not locally applied again. |
| Retry bounds | Repeated failure, worker crashes, or continuous renewals cannot exceed `M` attempts, `H` per attempt, or `R` total retry age, apart from documented sweep latency. |
| Poison isolation | A dead head blocks successors on that account; another account progresses within the configured scheduler SLA. |
| Backpressure | Concurrent admissions never exceed reserved capacity `B`; rejected deliveries create no entry; existing duplicates remain acknowledgeable. |
| External ambiguity | Inject success followed by response loss. Observe possible repeated requests; require one applied operation only when the destination’s idempotency contract provides it. |
| Retention | Replay an acknowledged identity after payload archival. Its tombstone prevents new processing throughout the promised replay horizon. |

For an expired lease, recovery should become eligible within the configured sweep interval plus backoff. Actual start latency additionally depends on database availability and admitted worker capacity; establish and test a scheduler SLA rather than assuming `SKIP LOCKED` guarantees fairness.

## 7. Alternatives, missing dependencies, and next action

- Explicit predecessor IDs can replace sequence numbers, but require cycle detection, missing-dependency policy, and durable resolution records.
- Arrival-order serialization is simpler but is not a substitute for causal ordering.
- Account advisory locks alone are insufficient: they provide neither durable lease state nor downstream fencing.
- Holding database transactions open across network calls is not an external atomicity solution.

The logical design has high confidence under its stated contracts. Its unresolved dependencies are the source’s ordering/replay guarantees, destination idempotency/fencing behavior, processing semantics, and operational limits.

**Next action:** agree on those contracts, then implement the schema and fault-injection tests above before tuning capacity or making performance claims.

openai / gpt-6-luna / low / low effort answer

## Durable inbox design

### Requirements and assumptions

- One PostgreSQL database is the authority for inbox state; workers may run concurrently.
- Authenticate the source before accepting a delivery. Enforce an appropriate request-size limit and validate required identifiers and payload structure.
- Deduplicate on `(source_id, account_id, event_id)`. Assume this key identifies one logical event; if the same key arrives with a different payload, treat that as a conflict, not a replacement.
- Acknowledge only after the event and its durable scheduling state commit. A successful acknowledgement means “durably accepted,” not “processed” or “external effects completed.”
- Preserve dependencies within an account: process only the earliest nonterminal event for that account. This deliberately allows a poison event to block later events for that account until an operator resolves or explicitly skips it.
- Use bounded retries and lease fencing for database state changes. External effects are not exactly-once unless the downstream system independently supports idempotency or fencing.

### State and invariants

An inbox row contains the dedupe key, payload, payload hash, acceptance time, account sequence, state, attempt count, next-attempt time, lease owner, lease expiry, monotonically increasing lease generation, and terminal/error metadata. Suggested states:

`ready → leased → done`

`leased → ready` on retryable failure or expired lease, subject to retry limits.

`ready/leased → dead` on permanent failure or exhausted retries. `dead → ready` only through an explicit audited operator retry; an explicit skip/resolve action may unblock the account.

Unique constraint on the dedupe key prevents duplicate logical rows. Assign a per-account sequence in the acceptance transaction, serialized using an account cursor row (or equivalent locking mechanism); do not rely on timestamps to order dependencies. Only the lowest-sequence nonterminal row for an account is eligible. Keep terminal rows, or equivalent dedupe tombstones, for the full required dedupe-retention period.

A lease has an expiry and generation. Every claim increments the generation. A worker must include its claimed generation in all inbox updates; updates succeed only if the row remains leased to that worker/generation. Expiry permits reclamation, but does not prove the prior worker stopped. Fencing protects database state, not arbitrary external side effects.

### Transaction boundaries

1. **Accept:** Authenticate and validate before database work. In one transaction, reserve/lock the account cursor, insert the inbox row and assign its sequence, and commit. If the unique key already exists, compare payload hash: identical content is an idempotent duplicate; differing content is a conflict to record/alert and reject or quarantine according to policy. Return success only after commit. Acknowledgement loss after commit is safe: redelivery hits the unique key.
2. **Claim:** In a short transaction, select eligible account heads with row locks (`FOR UPDATE SKIP LOCKED` or equivalent), mark them leased, increment generation and attempts, set expiry, then commit. Do not hold database locks while processing.
3. **Process:** Perform work outside the claim transaction. For effects in the same database, write effects and mark the inbox row done in one transaction, checking lease generation. For external effects, use a stable idempotency key derived from the dedupe key where supported; otherwise acknowledge that crash/retry can repeat effects. A transactional outbox can durably record intended external work, but cannot alone guarantee the remote effect happened exactly once.
4. **Complete/retry:** In a short transaction, conditionally update using row ID, leased state, owner/generation. Mark done, or set ready with backoff and `next_attempt_at`; if the retry budget is exhausted or error is permanent, mark dead. Stale workers’ conditional updates affect zero rows and must not overwrite newer state.

### Backpressure and failures

Bound request size, database connections, queue growth, and worker concurrency. Monitor oldest ready age, queue depth, lease expirations, retry counts, dead rows, and per-account blockage. Apply admission limits or return a retryable overload response before acceptance when capacity is exhausted; never return success for an uncommitted event. If commit outcome is uncertain, return a retryable failure: a later duplicate is safe. Database unavailability, authentication failure, malformed input, key/payload conflict, and capacity rejection must not be reported as successful acceptance. Use exponential backoff with jitter and a maximum attempt count; classify permanent errors explicitly. Alert and provide audited replay/skip procedures for poison events.

### Acceptance checks

Pass only if tests or operational checks demonstrate:

- Concurrent duplicate deliveries create one logical row; same-key/different-payload deliveries are surfaced as conflicts.
- No success acknowledgement is emitted before durable commit; redelivery after an acknowledgement loss does not create a second row.
- Reordered deliveries are processed in assigned per-account order; different accounts can progress independently.
- Concurrent workers cannot claim the same current lease; after expiry, a new generation can reclaim it, and stale-generation updates cannot change inbox state.
- Crash before commit yields no accepted event; crash after commit but before acknowledgement is recoverable by redelivery; crash after claim is recoverable after lease expiry.
- Retryable failures back off and stop at the configured bound; permanent/exhausted failures become dead and visibly block later events for that account until explicit resolution.
- External-effect tests explicitly demonstrate the documented duplicate-effect behavior or verify downstream idempotency; they do not assert generic exactly-once behavior.
- Overload and database failure produce no false success, and queue/age/lease/dead-letter metrics and alerts have configured thresholds.

Thresholds, retention durations, retry limits, and downstream idempotency capabilities are deployment-specific and must be set and tested; none can be inferred from the supplied task. The main alternative is partitioning/streaming infrastructure, but it is unnecessary for the stated single-database scope and does not remove the need for durable acknowledgement, dedupe, fencing, and explicit external-effect semantics.

**Next useful action:** choose concrete retention, retry, lease, capacity, and poison-event policies, then validate the listed checks against the application’s actual downstream effects.

Primary judge's stated reason

A provides a materially better-supported dependency contract: its authoritative sequence and gap handling prevent a successor from executing merely because it arrived first. B's acceptance-order design can execute a dependent event before its prerequisite. This is a clear task-relevant advantage, not a slight forced preference, although A still requires source capabilities not established by the prompt.

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

Battle wave: 5b3a3868-ff64-4c03-9e3c-d769b74c6749. Pair: brp1_3b2f2a4b5ae1195edd14326d4c66ffbd020b5792894e193b64a2f0b7adefb342. A separate independent review is required before calling a concern a verified factual defect. Judge disagreement is not recorded here.