Skip to content
Recommended solution · HC-5 · Python

Payments On-Call

Three incidents in Forkful's orders service: restaurants credited twice, payments stuck in the wrong state, and a nightly payout that paid twice. Each one is a write that is not safe to repeat, and each fix makes the database, not the process, the thing that decides.

On this page

The codebase

Forkful is a food-ordering marketplace. Customers pay through Paybridge, Paybridge tells the service what happened to each payment by webhook, and every night a job pays each restaurant its balance.

Two API processes (api-1 and api-2) and two job hosts (jobs-1 and jobs-2) share one SQLite database. That detail is the key to all three incidents: anything kept in memory is invisible to the other process.

You do not need to read the whole service. Every incident lives on one of two paths: the webhook path that turns Paybridge's events into ledger entries, or the payout path that turns ledger balances into transfers.

The webhook path and the payout path, both writing to one shared SQLite databaseWebhook path · stages 1 and 2 · runs on api-1 and api-2Paybridgewebhook deliveryroutes/webhooks.pysignature checkservices/webhooks.pyhandle_deliveryservices/payments.pyapply_eventservices/ledger.pycredit · refund debitOne SQLite database, shared by all four processesone writer at a time · with_for_update() ignored · transaction() is the unit of workPayout path · stage 3 · runs on jobs-1 and jobs-2Scheduler02:00 every nightjobs/run_payouts.pyrun_payout_jobservices/payouts.pypay_out_periodpaybridge/client.pytransfers.createPaybridgetransfers API
Stages 1 and 2 live on the webhook path, stage 3 on the payout path. Every process writes to the same database, so a fix that lives in one process's memory does not hold.

Where things live

app/api/routes/webhooks.pyPOST /webhooks/paybridge: checks the signature and hands the delivery to the webhook service.
app/services/webhooks.pyhandle_delivery: decides whether a delivery is new, applies its event and records it.
app/services/payments.pyapply_event: sets the payment's and the order's status, and posts credits and refunds.
app/services/ledger.pyThe restaurants' ledger: capture credits, refund debits and payout debits.
app/services/payouts.pypay_out_period: works out who is due and asks Paybridge for each transfer.
app/jobs/run_payouts.pyrun_payout_job: the nightly entry point the scheduler calls. Its signature is fixed.
app/providers/paybridge/Paybridge's client: payments, transfers (with an optional Idempotency-Key) and signatures.
app/db/session.py's transaction(), the models, and repositories that flush but never commit.
incidents/One evidence file per incident: timeline, logs and Paybridge's documentation. Read it first.
candidate_tests/test_candidate.pyYour tests. conftest.py's fixtures (seed, checkout, make_event, deliver, paybridge) work here.

Rules that shape every fix

  • Keep the HTTP API, Paybridge's webhook contract (signature check, a 2xx for every delivery Paybridge need not resend) and run_payout_job's signature.
  • Add tables, columns and constraints freely. Keep the existing columns.
  • SQLite allows one writer at a time and ignores with_for_update(), so locks have to come from constraints and transactions.
  • tests/, conftest.py and the dependencies are locked.

How to work each incident

  1. Diagnose from the evidence before asking for code. Name the cause in your own words and quote the log lines that show it.
  2. Ask for failing tests before the fix, and name the cases they must cover, including the hard one: two processes at once, or a failure partway.
  3. Press Test and watch them fail. Then say what failed, with the value you saw.
  4. List what the fix must survive, then describe the design yourself: the constraint, the transaction, the answer Paybridge gets.
  5. Press Test again after the last change. If it is still red, name the failing test and the value it showed, ask for the fix, and press Test again before you move on.
Stage 1 · INC-1182

Restaurants paid twice

What the ticket asks

After Paybridge's 40-minute outage it resent its webhook deliveries, and 61 payments now have two capture credits: $1,247.80 Forkful never received.

Find why a capture credits twice, reproduce it in a test, and fix it so each capture credits its restaurant once, however and whenever Paybridge delivers it.

Where to look

incidents/01-paid-twice.mdThe three restaurants' logs each show a different way the same event lands twice.
app/services/webhooks.pyhandle_delivery's dedupe check is the bug. Look at what it keys on and how many transactions it opens.
app/services/payments.pyapply_event opens its own transaction, so the credit commits before the delivery is recorded.
app/db/models/webhook.pyThe record that should make a repeat impossible. Its event_id is indexed but not unique.
app/db/repositories/menus.pyadd_item shows the codebase's pattern: flush, catch IntegrityError, raise a named ConflictError.

What the evidence shows

Casa Oaxacaevt_Gu7mhmWXCb4k5KNAarfLdv2G arrives at 14:06 and again at 14:43 with a new delivery id. Both credit 2875.
Bombay Spiceevt_e0Hw3tTSN2dzOGUeB9O4dnWx reaches api-1 and api-2 4 ms apart. Both pass the check.
Green Fork SaladsCredited, then recording the delivery fails with 'database is locked' (500), so Paybridge retries and it is credited again.
Paybridge's retry pageA retry carries the same event id and a new delivery id.

The cause

  • The dedupe keys on the delivery id, which every retry changes, so it never catches a retry.
  • The check, the credit and the record are three separate transactions, so two overlapping deliveries both pass the check.
  • The credit commits before the record, so a failure in between leaves a credit with no record, and the retry credits again.
Before: two deliveries of one event both credit. After: the second fails on the unique event id and is answered 200.Beforeevt_Gu7… dlv_mCd6…first delivery, 14:06evt_Gu7… dlv_9M7R…Paybridge's retry, 14:43seen delivery id?no → applyseen delivery id?no: the id is new → applycredit 2875own transactioncredit 2875 againown transactionbalance 5750should be 2875Afterevt_Gu7… any deliveryfirst, retry or overlapone transaction()record evt (unique) + apply + creditfirst delivery commitscredited once · 200any repeat fails on the constraintrolled back · 200, duplicate: true
A retry carries a new delivery id, so the old check lets it through. With the event id unique, a repeat cannot be recorded, so it rolls back and Paybridge gets a 200.

The fix

  1. Make the event id unique in the database, so a second delivery of an event cannot be recorded, on any process.
  2. Record the delivery and apply its event in one transaction, so both land or neither does.
  3. Answer a duplicate with 200 and duplicate: true, not 409, because Paybridge stops resending only on a 2xx.
  4. Catch only that duplicate error. Every other failure still returns 500, so Paybridge retries it.
app/db/models/webhook.pyOne row per event: the event id gets a unique constraint.
 class WebhookDelivery(Base):     __tablename__ = "webhook_deliveries"+    __table_args__ = (UniqueConstraint("event_id"),)      delivery_id: Mapped[str] = mapped_column(String(64), primary_key=True)-    event_id: Mapped[str] = mapped_column(String(64), index=True)+    event_id: Mapped[str] = mapped_column(String(64))
app/db/repositories/webhooks.pyThe insert turns the constraint violation into a named error, as menus.add_item does. The dead delivery-id lookup goes.
-def get_delivery(session: Session, delivery_id: str) -> WebhookDelivery | None:-    return session.get(WebhookDelivery, delivery_id)+class EventAlreadyHandled(ConflictError):+    default_code = "event_already_handled"  def record_delivery(session, *, delivery_id, event_id, ...) -> WebhookDelivery:     session.add(delivery)-    session.flush()+    try:+        session.flush()+    except IntegrityError as error:+        raise EventAlreadyHandled(f"Paybridge event {event_id} has been handled already") from error
app/services/webhooks.pyRecord first, then apply, in one transaction. A duplicate rolls back and is answered as a duplicate.
-    with transaction(session_factory) as session:-        seen = webhooks.get_delivery(session, delivery.delivery_id)-    if seen is not None:-        return DeliveryOutcome.DUPLICATE-    payments.apply_event(session_factory, event, clock=clock, outbox=outbox)-    with transaction(session_factory) as session:-        webhooks.record_delivery(session, ...)+    try:+        with transaction(session_factory) as session:+            webhooks.record_delivery(session, delivery_id=..., event_id=event.id, ...)+            applied = payments.apply_event(session, event, now=received_at) if is_payment_event(event.type) else None+    except EventAlreadyHandled:+        return DeliveryOutcome.DUPLICATE+    if applied is not None:+        payments.announce(outbox, applied, now=received_at)
app/services/payments.pyapply_event works in the caller's session, and notifications move to announce(), called after the commit.
-def apply_event(session_factory, event, *, clock, outbox) -> AppliedEvent:-    with transaction(session_factory) as session:-        ...+def apply_event(session: Session, event: PaybridgeEvent, *, now: datetime) -> AppliedEvent:+    ...++def announce(outbox: Outbox, result: AppliedEvent, *, now: datetime) -> None:+    """Call it after the commit, so nobody hears of a change that was rolled back."""

Tests that prove it

  • The same capture resent with a new delivery id: one credit of 1549.
  • Two deliveries of one event at once on two app instances, both threads held at a threading.Barrier before their first write: one credit.
  • A delivery that fails right after the credit, then its retry: one credit.

The conversation

Only your side is shown: the assistant reads, writes and runs between your messages. Each chip is a rubric item the step earns.

DirectionPrompt qualityVerificationCorrectnessCode quality

  1. Your message 1

    INC-1182. In incidents/01-paid-twice.md, Casa Oaxaca's capture evt_Gu7mhmWXCb4k5KNAarfLdv2G arrived at 14:06 and again at 14:43 with a new delivery id, and both credited 2875. Paybridge's retry page says a retry keeps the event id and gets a new delivery id. So handle_delivery dedupes on the delivery id, which a retry never repeats. Please confirm by reading app/services/webhooks.py. Don't change anything yet.

    Name the cause yourself, with the log lines that prove it, before the assistant says it.

    • Direction: Diagnosis, 6 points
    • Prompt quality: Gave evidence, 5 points
  2. Your message 2

    Two more holes I see in the log: Bombay Spice's evt_e0Hw3tTSN2dzOGUeB9O4dnWx reached api-1 and api-2 4 ms apart and both passed the check, because the check, apply_event and record_delivery run in separate transactions. And Green Fork Salads was credited, then recording the delivery failed with 'database is locked', so the retry credited again.

    No new points on its own, but these two holes are why a plain event-id check is not enough: they set up the design you ask for later.

  3. Your message 3

    Before any fix, add tests in candidate_tests/test_candidate.py for: the same capture resent with a new delivery id; two deliveries of one event at once on two app instances sharing the database, both threads held at a threading.Barrier before their first write; and a delivery that fails right after the credit, then its retry. Each expects one credit of 1549. Don't fix the code yet.

    You choose the cases. The barrier must come before either thread writes, or SQLite's lock hangs the test.

    • Prompt quality: Named the cases, 3 points
  4. Press Test. The new tests fail on the code as it is: the retry test ends with a balance of 3098.
    • Verification: Reproduced first, 8 points
    • Verification: Hard case tested, 6 points
  5. Your message 4

    The tests fail as expected: the retry with a new delivery id ends with a balance of 3098 instead of 1549. The fix must hold for a retry with a new delivery id, two deliveries at once on api-1 and api-2, a delivery that fails after the credit and is retried, and a restart in between. So no in-memory set, lock or check-then-insert.

    Quote the failing case and its value. Turning down the weak fixes with the reason they fail is part of deciding the design.

    • Prompt quality: Failure follow-up, 3 points
    • Prompt quality: Stated constraints, 5 points
  6. Your message 5

    Fix: make webhook_deliveries.event_id unique. In handle_delivery, record the delivery and apply the event in one transaction(), so both commit or neither does, and notify only after the commit. A duplicate fails on the constraint: turn that IntegrityError into a named error in the repository, as menus.add_item does, and answer 200 with duplicate true, not 409, because Paybridge only stops on a 2xx. Catch only that error. Remove the old delivery-id check and fix the 'Idempotent' docstring.

    The whole design is yours: the constraint, the transaction and the status code. The last two sentences keep the code tidy.

    • Direction: Unique claim, 9 points
    • Direction: One transaction, 7 points
    • Direction: Duplicate answered 2xx, 4 points
    • Prompt quality: Specified fix, 4 points
  7. Press Test. Every test passes after the last change.
    • Verification: Run after last change, 6 points
  8. Continue. The stage closes. Scope, correctness and code quality are judged on the final code.
    • Direction: Scope, 4 points
    • Correctness: Hidden tests, 20 points
    • Code quality: Code quality, 10 points

Where the stage lands

Measured when this conversation was played on the platform. A+ needs 92, S needs 95.

Direction30/30
Prompt quality20/20
Verification20/20
Correctness20/20
Code quality10/10
Stage total 100/100Grade S
Stage 2 · INC-1185

Charged but pending, refunds lost

What the ticket asks

While Paybridge delivered the events its outage held back, 23 customers were charged but their orders still show pending, and nine refunds ($86.45) never came off the restaurants' balances.

Find why, reproduce both problems in tests, and fix it so a payment's status, its order's status and the balance come out right whatever order the events arrive in. A repeated delivery still counts once.

Where to look

incidents/02-out-of-order.mdPho Saigon Corner shows the status problem, Sakura Ramen House the lost refund.
app/services/payments.pyEach handler sets the status from whichever event arrived last. _refunded drops a refund that comes before its capture.
app/db/models/payment.pyWhere the status lives. Nothing records which event set it.
app/providers/paybridge/events.pyEvery event carries a sequence. Today it is only logged.

What the evidence shows

Pho Saigon CornerThe capture (sequence 2) is applied, then its authorization (sequence 1) arrives 18 ms later and moves the order back to pending.
Same secondBoth events were created at 14:21:07, so created cannot order them.
Sakura Ramen HouseThe refund (sequence 3) arrives before its capture, logs refund.ignored_uncaptured, and is still answered 200, so Paybridge never resends it.
Paybridge's events pageEvents can arrive in any order. sequence increases with every event about a payment.

The cause

  • The status comes from whichever event arrived last. sequence, the one field that orders a payment's events, is never used.
  • A refund that arrives before its capture is dropped but acknowledged, so it is lost for good.
The capture (sequence 2) arrives before the authorization (sequence 1). Before, the order goes back to pending. After, the status stays captured.Arrival order at Pho Saigon Corner, both created 14:21:07payment.capturedsequence 2 · arrives firstpayment.authorizedsequence 1 · arrives 18 ms laterBefore: the last arrival winscapturedorder confirmedauthorizedorder back to pendingcharged, food deliveredapp still says pendingAfter: status_sequence decidescaptured, status_sequence 2amount recorded, credit posted1 < 2: status stays capturedauthorized amount still recordedorder confirmedbalance right in any order
Paybridge's sequence orders a payment's events. An older event still records its amount but cannot move the status back.

The fix

  1. The status follows Paybridge's sequence: an event older than the one the status came from leaves the status alone.
  2. Keep that sequence in the database, next to the status, because a payment's events reach both API processes.
  3. Every event still counts, whatever the order: its amount is recorded and its credit or refund debit posted. A refund before its capture still debits.
  4. Work a refund's status out from the amounts: refunded only when 0 < captured ≤ refunded.
app/db/models/payment.pyThe payment remembers which event its status came from.
     status: Mapped[str] = mapped_column(String(24))+    status_sequence: Mapped[int] = mapped_column(default=0)+    """The sequence of the newest event the status comes from; 0 until an event arrives."""
app/services/payments.pyOne function settles the status by sequence. The handlers always apply their amounts and ledger entries.
+def _settle_status(session, payment, order, event, now) -> None:+    if event.sequence > payment.status_sequence:+        newest, sequence = EventType(event.type), event.sequence+    else:+        newest, sequence = EVENT_FOR_STATUS[PaymentStatus(payment.status)], payment.status_sequence+    status = _status_for(newest, payment)+    payments.update_payment(session, payment, status=status, status_sequence=sequence, now=now)+    orders.set_payment_status(session, order, status, ORDER_STATUS_FOR_PAYMENT[status], now=now)
app/services/payments.py (_refunded)The branch that dropped an early refund goes. The refund always debits.
-    if payment.status not in REFUNDABLE_STATUSES:-        log.warning("refund.ignored_uncaptured", ...)-        return False, None-    refunded_cents = payments.add_refund(session, payment, amount_cents, now=now)-    status = PaymentStatus.REFUNDED if refunded_cents >= payment.captured_cents else ...-    _set_status(session, payment, order, status, now)+    payments.add_refund(session, payment, amount_cents, now=now)+    _settle_status(session, payment, order, event, now)     return ledger.debit_refund(session, payment, amount_cents=amount_cents, event_id=event.id, now=now)

Tests that prove it

  • The capture (sequence 2) before the authorization (sequence 1): the order stays confirmed.
  • A refund of 500 before its capture: the balance ends at 1049.
  • Every ordering of one payment's authorized, captured and refunded events: the same final status and balance.

The conversation

Only your side is shown: the assistant reads, writes and runs between your messages. Each chip is a rubric item the step earns.

DirectionPrompt qualityVerificationCorrectnessCode quality

  1. Your message 1

    INC-1185, incidents/02-out-of-order.md. Pho Saigon Corner's capture (sequence 2) was applied, then its authorization (sequence 1) arrived 18 ms later and moved the order back to pending. Both were created at 14:21:07, so created can't order them, and the handlers just use whichever event arrived last. Paybridge's events page says events come in any order and sequence increases per payment.

    Say why created cannot be the answer, so the assistant does not reach for it.

    • Direction: Diagnosis, 7 points
    • Prompt quality: Gave evidence, 5 points
  2. Your message 2

    Second cause: Sakura Ramen House's refund (sequence 3) arrived before its capture. _refunded logged refund.ignored_uncaptured and still answered 200, so Paybridge never resent it and the restaurant kept the money. Please confirm both in app/services/payments.py. No changes yet.

    No new points on its own: the ticket has two symptoms, and the fix needs both causes named.

  3. Your message 3

    Add tests for: the capture (2) arriving before the authorization (1), where the order must stay confirmed; a refund of 500 arriving before its capture, where the balance must end at 1049; and every ordering of one payment's authorized, captured and refunded events. Don't fix yet.

    One test per symptom, plus every ordering, so no pair of events is missed.

    • Prompt quality: Named the cases, 3 points
  4. Press Test. The order is still pending after the capture-first case. The refund-first case ends at 1549.
    • Verification: Reproduced first, 8 points
    • Verification: Both problems tested, 6 points
  5. Your message 4

    They fail as the incident says: after the capture-before-authorization case the order is still pending, and the refund-first case ends at 1549 instead of 1049. The fix must hold for any order of a payment's events, events that share a created second, and events of one payment split across api-1 and api-2. A repeated delivery must still count once.

    • Prompt quality: Failure follow-up, 3 points
    • Prompt quality: Stated constraints, 3 points
  6. Your message 5

    Fix: add a status_sequence column to Payment and one function that moves the status only when an event's sequence is higher; an older event leaves the status alone. Every event still applies its amount and ledger entry whatever the order, so a refund before its capture still debits. Remove the refund-dropping branch and REFUNDABLE_STATUSES, and fix the module docstring that says an early refund can't be applied. A refund status is refunded only when 0 < captured <= refunded.

    Both halves of the fix in one request: the status rule and the ledger rule.

    • Direction: Order by sequence, 9 points
    • Direction: Every event counts, 9 points
    • Prompt quality: Specified fix, 6 points
  7. Press Test. Every test passes after the last change.
    • Verification: Run after last change, 6 points
  8. Continue. The stage closes. Scope, correctness and code quality are judged on the final code.
    • Direction: Scope, 5 points
    • Correctness: Hidden tests, 20 points
    • Code quality: Code quality, 10 points

Where the stage lands

Measured when this conversation was played on the platform. A+ needs 92, S needs 95.

Direction30/30
Prompt quality20/20
Verification20/20
Correctness20/20
Code quality10/10
Stage total 100/100Grade S

The first run left the module docstring saying an early refund cannot be applied, which cost half a tidiness point. The fix message above now asks for it, and the second run scored 100.

Stage 3 · INC-1191

The nightly payout ran twice

What the ticket asks

Twice this week the nightly payout paid restaurants twice: once after a run that failed partway was rerun by hand, once when a deploy started two runs at the same moment.

Find why, reproduce both in tests, and fix it so each restaurant is paid its balance once a day, however a run fails, is rerun or overlaps another. The earlier fixes stay fixed.

Where to look

incidents/03-payout-twice.mdThursday's timeout and rerun, Saturday's two runs, and Paybridge's page on idempotency keys.
app/services/payouts.py_pay asks for the transfer with no key and records the payout only after Paybridge answers.
app/db/models/payout.pyNothing in the schema stops a second payout for the same restaurant and day.
app/providers/paybridge/client.pytransfers.create already accepts an idempotency_key. Nobody passes one.
app/jobs/run_payouts.pyThe entry point the scheduler calls. Keep its signature.

What the evidence shows

Bella NapoliThe transfer request gives up at 10 s, but Paybridge made the transfer and answered at 41.8 s. Nothing is recorded, so the rerun by hand pays $412.75 again.
Smokehouse 52A 503 made no transfer. This is the only case where the runbook's 'a rerun is safe' holds.
Saturday 02:00:00run_payouts for 2026-10-23 starts on jobs-1 and jobs-2 at once. Both read the same balances and both pay.
Paybridge's transfers pageA request repeated with the same Idempotency-Key within 24 hours returns the original transfer.

The cause

  • Each transfer is requested with no idempotency key, and the payout is recorded only after Paybridge answers. A timeout after the transfer was made leaves no record, and the rerun pays again.
  • Nothing stops two runs from reading the same balances and both paying.
A run claims each payout before asking for the transfer, sends it with a stable idempotency key, and records the payout, its debit and the claim together. A rerun resends pending claims with the same key; a second run cannot claim.One restaurant, one day1. claimunique (restaurant, period)committed as pending2. transfers.createIdempotency-Key: payout:rst_…:2026-10-21same key on every request3. one transaction()payout + ledger debit + claim → sentThursday: the answer is lost after Paybridge paidtimeout at 10 sclaim stays pendingrerun: resend pending claims firstsame keyPaybridge returns theoriginal transfer: paid onceSaturday: two runs at 02:00:00jobs-1 claims firstjobs-2: claim fails on the constraintjobs-2 skips it: paid once
The claim stops a second run. The stable key makes a retried request return the transfer Paybridge already made.

The fix

  1. Before asking for a transfer, claim the restaurant's payout for the day in a table with a unique (restaurant, period). A second run cannot claim it.
  2. Send every request for that payout with the same key, payout:{restaurant}:{period}, so a retry or a rerun gets the original transfer.
  3. When Paybridge answers, write the payout, its ledger debit and the claim marked sent in one transaction.
  4. A failure leaves the claim pending. Every run first asks again for pending claims, with the same key, so a rerun finishes what an earlier run started.
app/db/models/payout.pyA claim per restaurant and period, taken before the transfer.
+class PayoutClaim(Base):+    __tablename__ = "payout_claims"+    __table_args__ = (UniqueConstraint("restaurant_id", "period"), ...)++    restaurant_id: Mapped[str] = mapped_column(ForeignKey("restaurants.id"))+    period: Mapped[date]+    amount_cents: Mapped[int]+    idempotency_key: Mapped[str] = mapped_column(String(255))+    status: Mapped[str] = mapped_column(String(16))   # pending | sent+    payout_id: Mapped[str | None] = mapped_column(ForeignKey("payouts.id"))
app/db/repositories/payouts.pyThe stable key, the claim insert with its named error, and a conditional mark-sent.
+def idempotency_key(restaurant_id: str, period: date) -> str:+    return f"payout:{restaurant_id}:{period.isoformat()}"++def claim(session, *, restaurant_id, period, amount_cents, destination, now) -> PayoutClaim:+    session.add(claimed)+    try:+        session.flush()+    except IntegrityError as error:+        raise PayoutAlreadyClaimed(...) from error
app/services/payouts.pyPending claims first, then claim, send with the key, and record together.
-    due = restaurants_due(session_factory)+    attempts = _send_pending(session_factory, transfers, clock=clock)+    still_pending = {attempt.restaurant_id for attempt in attempts if attempt.failed}+    due = [owed for owed in restaurants_due(session_factory) if owed.restaurant_id not in still_pending]     for restaurant in due:-        paid.append(_pay(session_factory, transfers, restaurant, period=period, clock=clock))+        claimed = _claim(session_factory, restaurant, period=period, clock=clock)+        if claimed is not None:+            attempts.append(_send(session_factory, transfers, claimed, clock=clock)) -    transfer = transfers.create(due.destination, due.amount_cents)+    transfer = transfers.create(claimed.destination, claimed.amount_cents, idempotency_key=claimed.idempotency_key) +        with transaction(session_factory) as session:+            payout = payouts.create(session, ...)+            payouts.mark_sent(session, claimed.id, payout_id=payout.id, now=now)+            ledger.debit_payout(session, payout, now=now)

Tests that prove it

  • A transfer whose answer is lost after Paybridge made it, then a rerun: one transfer.
  • A 503 that made no transfer, then a rerun: one transfer.
  • Two runs at once, each held at a threading.Barrier before its first write: one transfer per restaurant.

The conversation

Only your side is shown: the assistant reads, writes and runs between your messages. Each chip is a rubric item the step earns.

DirectionPrompt qualityVerificationCorrectnessCode quality

  1. Your message 1

    INC-1191, incidents/03-payout-twice.md. In app/services/payouts.py, transfers.create is sent with no idempotency key, and the payout is recorded only after Paybridge answers. Bella Napoli's request timed out at 10 s, but Paybridge made the transfer and answered at 41.8 s. Nothing was recorded, so Jonas's rerun by hand paid $412.75 again. Paybridge's transfers page says a repeated Idempotency-Key returns the original transfer for 24 hours.

    The timeout is the trap: the request failed on our side, but the transfer happened on Paybridge's.

    • Direction: Diagnosis, 6 points
    • Prompt quality: Gave evidence, 5 points
  2. Your message 2

    Second cause: nothing stops two runs. On Saturday run_payouts for 2026-10-23 started on jobs-1 and jobs-2 at 02:00:00, and both read the same balances and paid. Please confirm by reading payouts.py and the payout model. No changes yet.

    No new points on its own: the overlap is the second incident, and the fix needs an answer to it.

  3. Your message 3

    Add tests for: a transfer whose answer is lost after Paybridge made it, then a rerun; a 503 that made no transfer, then a rerun; and two runs at once, each held at a threading.Barrier before its first write. Each restaurant must get exactly one transfer. Don't fix yet.

    Cover both incidents: the rerun after a failure, and the overlap.

    • Prompt quality: Named the cases, 3 points
  4. Press Test. After the lost answer and the rerun, Luigi's gets two transfers of 1549. The two-runs test pays twice too.
    • Verification: Reproduced first, 8 points
    • Verification: Both incidents tested, 6 points
  5. Your message 4

    They fail: after the lost answer and the rerun, Luigi's gets two transfers of 1549, and the two-runs test pays twice too. The fix must survive a timeout after the transfer was made, a 503 that made none, a job stopped partway, a rerun by hand in another process, and two runs on jobs-1 and jobs-2.

    • Prompt quality: Failure follow-up, 3 points
    • Prompt quality: Stated constraints, 3 points
  6. Your message 5

    Fix: before asking for a transfer, claim the restaurant's payout for the period in a payout_claims table with a unique (restaurant_id, period), committed as pending. Send every request with the key payout:{restaurant_id}:{period} and the claim's amount. When Paybridge answers, write the payout, its debit and the claim marked sent in one transaction. A failure leaves the claim pending, and every run first resends pending claims with the same key. Keep run_payout_job as it is.

    The key and the claim answer the two incidents. Resending pending claims answers what a rerun should do.

    • Direction: Stable key, 8 points
    • Direction: Overlap guard, 8 points
    • Direction: Rerun finishes, 4 points
    • Prompt quality: Specified fix, 6 points
  7. Press Test. Every test passes after the last change.
    • Verification: Run after last change, 6 points
  8. Submit. The stage closes. Scope, correctness and code quality are judged on the final code.
    • Direction: Scope, 4 points
    • Correctness: Hidden tests, 20 points
    • Code quality: Code quality, 10 points

Where the stage lands

Measured when this conversation was played on the platform. A+ needs 92, S needs 95.

Direction30/30
Prompt quality20/20
Verification20/20
Correctness20/20
Code quality10/10
Stage total 100/100Grade S

A clean run scored 100. An earlier run scored 95, losing Scope and half of Named the cases to scoring variation, not to anything the conversation left out.

Payments On-Call Solution — Python Walkthrough | Hunicode