openai / gpt-6.1-sol / low / low 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 / low / low effort answer
## Recommendation and scope
Use PostgreSQL as the durable inbox, scheduler, and authority for **one active processing lease per source/account**. Process each account in dependency order; allow different accounts to run concurrently.
This provides durable acknowledgement, deduplication, crash recovery, bounded retries, and fenced database mutations. It **does not provide exactly-once external effects**.
This is an independent design assessment based only on the supplied question; no implementation or tests were inspected or executed.
## 1. Requirements and assumptions
### Ordering requires additional information
`eventID`, `accountID`, and an opaque payload are insufficient to reconstruct dependencies when deliveries are reordered. Arrival order is not causal order.
For this design, require the authenticated payload to contain a stable, contiguous **per-source/account sequence number**:
- Sequence `n` depends on successful completion of sequence `n−1`.
- Each account is provisioned with its initial expected sequence.
- An event’s sequence and payload never change.
- Sequence numbers cannot be reused under a different event ID.
- This represents a total dependency order. Independent events in the same account may be delayed unnecessarily.
If the source cannot supply sequence numbers or equivalent dependency metadata, reject any claim that the inbox preserves true dependencies. Arrival-order processing is only a weaker alternative.
### Other assumptions
- Authentication establishes `sourceID` and permission to deliver for `accountID`; request fields cannot override that identity.
- PostgreSQL acknowledgement means commit with `synchronous_commit=on`. Survival of primary loss additionally requires an appropriate synchronous replication/failover policy; local durability alone is insufficient.
- Handlers classify failures as retryable or permanent.
- Handlers use bounded execution time and support lease-loss cancellation where practical.
- Event size, delivery rate, account cardinality, and retention have configured limits.
- External effect duplication is tolerable, or the external destination supports suitable idempotency keys.
## 2. Data model and invariants
### Tables
**`accounts`**
- Primary key: `(source_id, account_id)`
- `next_sequence`
- `status`: `active`, `blocked`, `paused`
- `lease_epoch`: monotonically increasing integer
- `lease_owner`, `lease_until`
- Scheduling and gap-observation timestamps
**`inbox`**
- Primary key: `(source_id, account_id, event_id)`
- Unique constraint: `(source_id, account_id, sequence)`
- Immutable sequence and payload, plus a canonical payload fingerprint
- State: `pending`, `running`, `retry_wait`, `succeeded`, `poison`, `skipped`
- Attempt count, next attempt time, first received time
- Current lease epoch, failure classification, bounded error details
Keep sufficient immutable payload data to verify duplicates; fingerprint equality alone need not be the final comparison.
Optional **`outbox`** records external-effect intents, with stable effect IDs and dispatch state.
### Invariants
1. At most one logical inbox event exists for each source/account/event ID.
2. Reusing an event ID with different content, or a sequence with a different event ID, is a conflict—not a successful duplicate.
3. Only `next_sequence` may be processed for an account.
4. At most one current lease epoch is authorized per account.
5. A stale epoch cannot renew, finalize, advance the account, or commit guarded database effects.
6. Advancing `next_sequence` and recording successful completion occur in one transaction.
7. Poison events and missing predecessors block successors unless an explicit audited resolution authorizes otherwise.
8. A success response means durable acceptance, not successful processing.
Retain deduplication tombstones after payload deletion. Otherwise an old redelivery can be mistaken for a new event. Permanent deduplication requires permanent identity retention; finite retention requires an explicit replay horizon.
## 3. State transitions and transaction boundaries
### A. Receive and acknowledge
Before beginning a transaction:
- Authenticate and authorize.
- Validate envelope, sequence, payload schema, and size.
- Reject malformed or unauthorized requests.
In one short transaction:
1. Create or lock the account row.
2. Look up the event identity and sequence.
3. For an identical existing event, return its acceptance result without allocating another event.
4. For conflicting identity/content/sequence, reject and record an operational signal.
5. Enforce durable capacity limits for new events.
6. Insert the immutable event as `pending`; update scheduling information.
7. Commit.
Only after successful commit return `202 Accepted`, or the agreed successful duplicate response.
If the commit outcome is unknown because the connection failed, do not assert rejection or success. Return a retriable failure when possible; the source retries using the same identity.
Identical duplicates remain accepted even if processing later becomes poison. A duplicate acknowledgement must not imply processing success.
### B. Claim work
Workers scan eligible accounts using row locking, such as `FOR UPDATE SKIP LOCKED`. Claiming is a short transaction:
1. Lock an active account whose lease is absent or expired.
2. Locate its `next_sequence`.
3. Require that event to be pending, due for retry, or recoverable from an expired running lease.
4. If retry/time limits are exhausted, mark it poison and block the account instead.
5. Increment `lease_epoch`.
6. Set owner and expiry using the database clock.
7. Mark the event `running`, copy the epoch, and increment attempts.
8. Commit and return payload plus the fencing token.
No predecessor means no claim. Record a gap timer and alert after a configured threshold. Later arrivals do not bypass the gap.
Use scheduling indexes and fair rotation so one hot account does not monopolize workers.
### C. Renew
A short transaction renews only when:
- Owner and epoch match.
- Account and event remain in the expected states.
- The lease has not expired.
An expired lease cannot be revived. The worker must stop after failed renewal, but cancellation alone is not a correctness mechanism.
### D. Complete
For effects wholly inside the same PostgreSQL database:
1. Lock the account.
2. Validate owner, epoch, event state, expected sequence, and unexpired lease using the database clock.
3. Apply business mutations.
4. Mark the event `succeeded`, advance `next_sequence`, and clear the lease.
5. Commit atomically.
Perform business mutations **only after** acquiring and validating the fence. Avoid network calls in this transaction.
The locked, validated completion transaction is the serialization point. Wall-clock lease expiry is not asynchronous cancellation of an already-authorized transaction. Keep these transactions short and enforce statement, lock, and idle-transaction timeouts.
For external effects, use the separate protocol below.
### E. Fail or lose a worker
A current worker reports failure in a fenced transaction:
- Retryable failure within budget → `retry_wait`, with capped exponential backoff and jitter; release the lease.
- Permanent failure or exhausted budget → `poison`; block the account and release the lease.
Configure both:
- Maximum claim attempts, including crash-abandoned attempts.
- Maximum processing age, so repeated delays cannot extend retries indefinitely.
After a crash, lease expiry makes the event reclaimable under a strictly newer epoch. No heartbeat is treated as proof of success.
### F. Resolve poison or gaps
Operator actions require authorization, an audit record, and the account lock.
- **Repair/retry:** preserve the original event; associate a versioned remediation and explicitly grant a new retry budget.
- **Skip:** mark `skipped` and advance atomically, acknowledging that the original dependency requirement is waived.
- **Compensate:** run an application-defined resolution before advancing.
A missing sequence cannot safely be skipped merely because a timeout elapsed. Require source confirmation or explicit operator authorization.
## 4. External effects and fencing limits
A PostgreSQL fencing token protects only operations that validate it. It cannot stop a stalled worker from sending an external request after losing its lease.
For a direct external request:
- Use a stable idempotency key derived from source/account/event ID and effect name—not from the attempt or lease epoch.
- Record success only under a valid fence.
- On timeout or crash, retry or reconcile using that same key.
- Without destination idempotency or queryable operation status, duplicate effects remain possible.
An outbox improves durability:
- Atomically insert an effect intent alongside database changes.
- Dispatch intents with their own leases and stable idempotency keys.
- Retrying dispatch still does not create exactly-once external execution.
Define dependency completion carefully:
- If successors depend only on durable intent creation, advancing with outbox insertion is valid.
- If successors require the external effect to have completed, do **not** advance then. Hold the account until confirmed external completion is durably recorded.
If an external destination supports fencing, it must atomically reject stale tokens in the relevant scope. Idempotency prevents duplicate logical effects; fencing prevents stale authorization. They are different guarantees.
## 5. Backpressure and operations
- Enforce per-source/account and global limits on unresolved event count and payload bytes.
- Maintain quota counters transactionally; avoid unsynchronized count-then-insert admission.
- Bound request size, worker concurrency, database connections, handler duration, and retry scheduling.
- Return `429` with retry guidance for policy/quota saturation and `503` for unavailable storage.
- Never return success for a new event that was not committed.
- Reserve capacity for duplicate acknowledgements, renewals, completion, and operator recovery.
- Include poison and gap-blocked payloads in storage accounting.
- Archive completed payloads according to policy without prematurely removing deduplication identity.
Monitor queue age, oldest gap, blocked accounts, lease expirations, stale-fence rejections, retry distribution, poison rate, database contention, and retained bytes. Set workload-specific thresholds before acceptance testing.
## 6. Measurable acceptance checks
These are proposed pass/fail checks, **not executed results**.
| Case | Pass condition |
|---|---|
| Concurrent identical deliveries | Exactly one inbox identity is stored; every successful response occurs after a durable commit. |
| Conflicting duplicates | Changed payload or reused sequence is rejected; original data remains unchanged. |
| Reordering | Deliver `3, 1, 2`; committed processing order is `1, 2, 3`. |
| Missing predecessor | Sequence `2` never executes while `1` is missing; gap alert occurs within the configured bound. |
| Account isolation | A blocked account does not prevent eligible accounts from progressing within the agreed scheduling bound. |
| Receive crash | Crash before commit leaves no accepted event; crash after commit/before response is recovered by deduplicated retry. |
| Lease takeover | After expiry, a newer epoch can claim; the old worker cannot renew, finalize, or commit guarded database mutations. |
| Simultaneous completion/takeover | Row-lock serialization yields one authoritative outcome; no double advancement occurs. |
| Database-effect crash | Business mutations, success state, and sequence advance are either all committed or all absent. |
| External-effect ambiguity | Inject a crash after remote success but before local recording; destination idempotency yields one logical effect, or duplicate risk is explicitly demonstrated and documented. |
| Retry exhaustion | No additional automatic claim occurs after configured attempt/age limits; the event becomes poison and successors remain blocked. |
| Capacity saturation | Admission cannot exceed configured durable quotas; rejected new events receive no success response. |
| Retention/replay | Redelivery within the promised deduplication horizon does not reprocess the event. |
| Database failover | Every acknowledged event survives failures covered by the declared replication policy. |
| Operator resolution | Skip/repair is authorized and audited; account advancement remains atomic. |
## Alternatives and remaining dependencies
Explicit predecessor IDs are preferable to sequence numbers when dependencies form a partial order, but require missing-parent handling, cycle detection, and a more complex scheduler. Arrival FIFO is simpler but cannot solve reordered causal dependencies. Advisory locks alone are insufficient durable lease/fencing state.
Confidence is high in the transaction and fencing structure, conditional on the stated assumptions. The unresolved decisions are source ordering metadata, external destination capabilities, durability/failover policy, retention horizon, and workload limits.
**Next action:** agree those contracts and numeric limits, then implement the schema and run the failure-injection checks above.
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
Prefer B clearly: its ordering contract and gap-blocking scheduler address a central correctness requirement that acceptance-assigned ordering cannot establish. This is a supported material design difference, not merely a forced preference for more detail. Neither answer supplies implementation evidence, and B's guarantee remains conditional on obtaining valid dependency metadata.
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_89fa4f4b1297b2e6a41b3a41cfda04c7b6f9ca0055c6d5bc2912fbd108a10d3c. A separate independent review is required before calling a concern a verified factual defect. Judge disagreement is not recorded here.