openai / gpt-6.1-sol / low / low 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.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 / 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
Prefer B for a concrete crash-recovery rule that enforces the required retry bound even when workers never report failure. This is a substantive assurance advantage rather than an optional refinement or a preference based on presentation. It does not establish that either design has been implemented successfully, and B remains conditional on obtaining dependency metadata.
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_708eb59c1a3556cdc4ac97e57926ec056d5f7a4cd0b3145bb65367b1a08e441f. A separate independent review is required before calling a concern a verified factual defect. Judge disagreement is not recorded here.