Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Unreleased

- **Withdrawal progress ownership** — Preserve newer Stripe withdrawal payment/refund state when a delayed submission response arrives. Compare progress atomically, recognize an already-applied retry, and ask clients to check history after a concurrent update instead of overwriting it.

## Release candidate v0.9.2 — Gemma QAT caching, adaptive MTP and Nemotron Lightning (not shipped; 2026-09-10)

Source changes since `v0.9.1`. Provider changes require a new signed bundle.
Expand Down
8 changes: 8 additions & 0 deletions coordinator/api/stripe_payouts_fixes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,14 @@ func (f *flakyPayoutStore) UpdateStripeWithdrawal(wd *store.StripeWithdrawal) er
return f.MemoryStore.UpdateStripeWithdrawal(wd)
}

// Production updates compare their lookup/submission snapshot atomically.
func (f *flakyPayoutStore) CompareAndSwapStripeWithdrawal(previous, next *store.StripeWithdrawal) (bool, error) {
if f.failUpdates {
return false, errors.New("connection reset by peer")
}
return f.MemoryStore.CompareAndSwapStripeWithdrawal(previous, next)
}

// newFlakyPayoutServer wires a Server + billing around a flakyPayoutStore.
func newFlakyPayoutServer(t *testing.T, fakeStripe *httptest.Server) (*Server, *flakyPayoutStore) {
t.Helper()
Expand Down
10 changes: 6 additions & 4 deletions coordinator/api/stripe_payouts_webhooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,9 @@ func (s *Server) handlePayoutTerminal(event *billing.WebhookEvent, connectedAcct
// Legacy row already refunded under the old semantics — leave it
// terminal so we never double-account.
if wd.Status != "failed" {
wd.Status = "failed"
if err := s.billing.Store().UpdateStripeWithdrawal(wd); err != nil {
next := *wd
next.Status = "failed"
if _, err := s.billing.Store().CompareAndSwapStripeWithdrawal(wd, &next); err != nil {
s.logger.Error("stripe connect webhook: status flip failed", "error", err)
return err
}
Expand Down Expand Up @@ -498,8 +499,9 @@ func (s *Server) handleTransferFailed(event *billing.WebhookEvent) error {
// sweep reconciliation — if it fails, return the error so Stripe
// redelivers rather than leaving a refunded row claimable.
if wd.Status != "failed" {
wd.Status = "failed"
if err := s.billing.Store().UpdateStripeWithdrawal(wd); err != nil {
next := *wd
next.Status = "failed"
if _, err := s.billing.Store().CompareAndSwapStripeWithdrawal(wd, &next); err != nil {
s.logger.Error("stripe connect webhook: refunded-row status flip failed",
"error", err, "withdrawal_id", wd.ID)
return err
Expand Down
68 changes: 59 additions & 9 deletions coordinator/api/stripe_withdraw.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,17 @@ func (s *Server) handleStripeWithdraw(w http.ResponseWriter, r *http.Request) {
return
}

// Keep the last acknowledged state across external Stripe calls so a
// webhook transition cannot be overwritten by our older local copy.
persisted := *wd
persistUpdate := func(stage string) error {
err := s.persistWithdrawalUpdate(&persisted, wd, stage)
if err == nil {
persisted = *wd
}
return err
}

// markFailedRefund refunds the ledger and marks the row failed
// (best-effort — neither store call has rollback). Returns whether the
// refund credit is durably applied; the Refunded flag prevents webhook
Expand All @@ -230,7 +241,7 @@ func (s *Server) handleStripeWithdraw(w http.ResponseWriter, r *http.Request) {
}
wd.Status = "failed"
wd.FailureReason = reason
if uerr := s.persistWithdrawalUpdate(wd, "failure"); uerr != nil {
if uerr := persistUpdate("failure"); uerr != nil {
s.logger.Error("stripe payout: mark failed failed", "error", uerr, "withdrawal_id", withdrawalID)
}
return refunded
Expand All @@ -257,7 +268,12 @@ func (s *Server) handleStripeWithdraw(w http.ResponseWriter, r *http.Request) {
// alert and completes the row from the Stripe dashboard via the
// idempotency key; if it didn't, the same alert drives the refund.
wd.FailureReason = "transfer_create_unconfirmed: " + err.Error()
if uerr := s.persistWithdrawalUpdate(wd, "ambiguous transfer"); uerr != nil {
if uerr := persistUpdate("ambiguous transfer"); uerr != nil {
if errors.Is(uerr, errWithdrawalStateChanged) {
s.writeWithdrawalStateChanged(w, withdrawalID)
return
}

s.logger.Error("stripe payout: persist ambiguous-transfer state failed",
"error", uerr, "withdrawal_id", withdrawalID)
}
Expand Down Expand Up @@ -299,7 +315,12 @@ func (s *Server) handleStripeWithdraw(w http.ResponseWriter, r *http.Request) {
}
wd.TransferID = transfer.ID
wd.Status = "transferred"
if err := s.persistWithdrawalUpdate(wd, "transfer_id"); err != nil {
if err := persistUpdate("transfer_id"); err != nil {
if errors.Is(err, errWithdrawalStateChanged) {
s.writeWithdrawalStateChanged(w, withdrawalID)
return
}

// Transfer succeeded but we lost track of it: the row is stuck
// "pending" with no transfer_id, invisible to the webhook matcher and
// sweep reconciler. Money is in the connected account and the daily
Expand Down Expand Up @@ -363,7 +384,12 @@ func (s *Server) handleStripeWithdraw(w http.ResponseWriter, r *http.Request) {
// idempotency key. If it didn't land, the daily sweep delivers and
// completes the row; ops refunds the fee from the same alert trail.
wd.FailureReason = "instant_payout_unconfirmed: " + err.Error()
if uerr := s.persistWithdrawalUpdate(wd, "ambiguous payout"); uerr != nil {
if uerr := persistUpdate("ambiguous payout"); uerr != nil {
if errors.Is(uerr, errWithdrawalStateChanged) {
s.writeWithdrawalStateChanged(w, withdrawalID)
return
}

s.logger.Error("stripe payout: persist ambiguous-payout state failed",
"error", uerr, "withdrawal_id", withdrawalID)
}
Expand Down Expand Up @@ -399,7 +425,12 @@ func (s *Server) handleStripeWithdraw(w http.ResponseWriter, r *http.Request) {
wd.FeeRefunded = true
wd.FailureReason += " (instant fee refunded)"
}
if uerr := s.persistWithdrawalUpdate(wd, "payout failure"); uerr != nil {
if uerr := persistUpdate("payout failure"); uerr != nil {
if errors.Is(uerr, errWithdrawalStateChanged) {
s.writeWithdrawalStateChanged(w, withdrawalID)
return
}

s.logger.Error("stripe payout: persist payout failure failed",
"error", uerr, "withdrawal_id", withdrawalID)
}
Expand All @@ -423,7 +454,12 @@ func (s *Server) handleStripeWithdraw(w http.ResponseWriter, r *http.Request) {
return
}
wd.PayoutID = payout.ID
if err := s.persistWithdrawalUpdate(wd, "payout_id"); err != nil {
if err := persistUpdate("payout_id"); err != nil {
if errors.Is(err, errWithdrawalStateChanged) {
s.writeWithdrawalStateChanged(w, withdrawalID)
return
}

// Payout succeeded but we couldn't persist the ID. Webhook will
// arrive with the payout ID — without the index entry the sweep
// matcher will still reconcile it by connected account. Log loudly
Expand Down Expand Up @@ -498,24 +534,38 @@ func (s *Server) creditRefundOnceWithRetry(accountID string, amountMicroUSD int6
return false
}

// persistWithdrawalUpdate retries a withdrawal-row update with short backoff.
// persistWithdrawalUpdate retries transient errors with the same expected state.
// A changed row returns immediately; retrying it must not overwrite a webhook.
// Used after money has moved (transfer/payout created): losing the update
// strands the row in a state the webhook matcher and sweep reconciler don't
// look at, so it's worth riding out a transient store blip in-request. Like
// creditRefundOnceWithRetry, it deliberately ignores request-context
// cancellation (bounded at 600ms total backoff) — abandoning the persist on
// client disconnect is exactly how rows get orphaned.
func (s *Server) persistWithdrawalUpdate(wd *store.StripeWithdrawal, stage string) error {
func (s *Server) persistWithdrawalUpdate(previous, wd *store.StripeWithdrawal, stage string) error {
var err error
for attempt := 0; attempt < 3; attempt++ {
if attempt > 0 {
time.Sleep(time.Duration(attempt) * 200 * time.Millisecond)
}
if err = s.billing.Store().UpdateStripeWithdrawal(wd); err == nil {
var applied bool
applied, err = s.billing.Store().CompareAndSwapStripeWithdrawal(previous, wd)
if err == nil {
if !applied {
return errWithdrawalStateChanged
}
return nil
}
s.logger.Warn("stripe payout: persist "+stage+" attempt failed",
"attempt", attempt+1, "error", err, "withdrawal_id", wd.ID)
}
return err
}

var errWithdrawalStateChanged = errors.New("withdrawal state changed during submission")

func (s *Server) writeWithdrawalStateChanged(w http.ResponseWriter, withdrawalID string) {
s.logger.Warn("stripe payout: submission state changed; preserving webhook state", "withdrawal_id", withdrawalID)
writeJSON(w, http.StatusConflict, errorResponse("withdrawal_state_changed",
"your withdrawal was updated while it was being submitted — check its status before retrying"))
}
93 changes: 93 additions & 0 deletions coordinator/api/stripe_withdrawal_progress_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package api

import (
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"

"github.com/eigeninference/d-inference/coordinator/store"
)

// A webhook can settle or refund the transfer while the HTTP withdrawal
// handler is still awaiting payouts.create. Its later progress write must not
// overwrite that newer terminal state with the handler's old transferred row.
func TestStripeWithdrawalProgressPreservesConcurrentTerminal(t *testing.T) {
for _, terminal := range []string{"paid", "refunded"} {
t.Run(terminal, func(t *testing.T) {
var srv *Server
var st *store.MemoryStore
snapshots := make(chan store.StripeWithdrawal, 1)
callbackErrors := make(chan error, 1)
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/v1/accounts/"):
_, _ = w.Write([]byte(healthyAccountJSON(strings.TrimPrefix(r.URL.Path, "/v1/accounts/"), "US", "full", true)))
case r.Method == http.MethodPost && r.URL.Path == "/v1/transfers":
_, _ = w.Write([]byte(`{"id":"tr_progress","amount":450,"currency":"usd"}`))
case r.Method == http.MethodPost && r.URL.Path == "/v1/payouts":
row, err := st.GetStripeWithdrawalByTransferID("tr_progress")
if err == nil {
if terminal == "paid" {
var applied bool
applied, err = st.MarkStripeWithdrawalPaid(row.ID, "", "po_sweep")
if err == nil && !applied {
err = fmt.Errorf("paid transition not applied")
}
} else {
result := deliverConnectWebhook(t, srv, transferReversedPayload("tr_progress"))
if result.Code != http.StatusOK {
err = fmt.Errorf("reversal status%d: %s", result.Code, result.Body.String())
}
}
}
if err == nil {
row, err = st.GetStripeWithdrawal(row.ID)
}
if err != nil {
callbackErrors <- err
http.Error(w, "fixture failed", 500)
return
}
snapshots <- *row
_, _ = w.Write([]byte(`{"id":"po_progress","amount":450,"status":"pending","method":"instant"}`))
default:
http.Error(w, "unexpected path "+r.URL.Path, 500)
}
}))
defer fake.Close()
srv, st = stripePayoutsTestServer(t, false, fake)
defer srv.Close()
user := readyUser(t, st, "progress-user", "progress@example.com", true)
if err := st.CreditWithdrawable(user.AccountID, 10_000_000, store.LedgerPayout, "progress-funding"); err != nil {
t.Fatal(err)
}
req := withPrivyUser(httptest.NewRequest(http.MethodPost, "/v1/billing/withdraw/stripe", strings.NewReader(`{"amount_usd":"5.00","method":"instant"}`)), user)
w := httptest.NewRecorder()
srv.handleStripeWithdraw(w, req)
select {
case err := <-callbackErrors:
t.Fatal(err)
default:
}
var want store.StripeWithdrawal
select {
case want = <-snapshots:
default:
t.Fatalf("payout callback did not run: status%d %s", w.Code, w.Body.String())
}
got, err := st.GetStripeWithdrawal(want.ID)
if err != nil {
t.Fatal(err)
}
if w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), "withdrawal_state_changed") {
t.Fatalf("concurrent update response=%d %s", w.Code, w.Body.String())
}
if !reflect.DeepEqual(*got, want) {
t.Fatalf("late progress replaced terminal row: got%+v want%+v", *got, want)
}
})
}
}
10 changes: 9 additions & 1 deletion coordinator/store/interface_domains.go
Original file line number Diff line number Diff line change
Expand Up @@ -369,9 +369,17 @@ type BillingStore interface {
// ID (tr_…). Used in transfer.failed webhook handlers.
GetStripeWithdrawalByTransferID(transferID string) (*StripeWithdrawal, error)

// UpdateStripeWithdrawal persists status/transfer/payout/fail-reason changes.
// UpdateStripeWithdrawal is an unconditional legacy update. New production
// read-modify-write paths must use CompareAndSwapStripeWithdrawal or a
// purpose-specific atomic transition.
UpdateStripeWithdrawal(withdrawal *StripeWithdrawal) error

// CompareAndSwapStripeWithdrawal changes mutable progress only while it
// matches previous. An exact next state is an idempotent success. Missing
// or concurrently changed rows return false; immutable money/account fields
// are preserved. Use this for submission and legacy status-only updates.
CompareAndSwapStripeWithdrawal(previous, next *StripeWithdrawal) (bool, error)

// MarkStripeWithdrawalPaid atomically flips a withdrawal to "paid" —
// but only from a non-terminal, non-refunded state ("pending" or
// "transferred" with Refunded=false) AND only while the row's PayoutID
Expand Down
93 changes: 93 additions & 0 deletions coordinator/store/stripe_withdrawal_progress.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package store

import (
"context"
"errors"
"fmt"
"time"
)

// withdrawalProgress is the mutable state shared by submission and webhook
// writers. Account, amounts, method and creation time are never progress fields.
type withdrawalProgress struct {
TransferID, PayoutID, SweepPayoutID, Status, FailureReason string
Refunded, FeeRefunded bool
}

func progressOf(w *StripeWithdrawal) withdrawalProgress {
return withdrawalProgress{w.TransferID, w.PayoutID, w.SweepPayoutID, w.Status, w.FailureReason, w.Refunded, w.FeeRefunded}
}

func validWithdrawalUpdate(previous, next *StripeWithdrawal) error {
if previous == nil || next == nil || next.ID == "" || previous.ID != next.ID {
return errors.New("matching stripe withdrawal ids are required")
}
return nil
}

func (s *MemoryStore) CompareAndSwapStripeWithdrawal(previous, next *StripeWithdrawal) (bool, error) {
if err := validWithdrawalUpdate(previous, next); err != nil {
return false, err
}
s.mu.Lock()
defer s.mu.Unlock()
current := s.stripeWithdrawalsByID[next.ID]
if current == nil {
return false, nil
}
currentState, nextState := progressOf(current), progressOf(next)
if currentState == nextState {
return true, nil
}
if currentState != progressOf(previous) {
return false, nil
}
if current.TransferID != next.TransferID {
delete(s.stripeWithdrawalsByTransferID, current.TransferID)
if next.TransferID != "" {
s.stripeWithdrawalsByTransferID[next.TransferID] = next.ID
}
}
if current.PayoutID != next.PayoutID {
delete(s.stripeWithdrawalsByPayoutID, current.PayoutID)
if next.PayoutID != "" {
s.stripeWithdrawalsByPayoutID[next.PayoutID] = next.ID
}
}
current.TransferID = next.TransferID
current.PayoutID = next.PayoutID
current.SweepPayoutID = next.SweepPayoutID
current.Status = next.Status
current.FailureReason = next.FailureReason
current.Refunded = next.Refunded
current.FeeRefunded = next.FeeRefunded
current.UpdatedAt = time.Now()
return true, nil
}

func (s *PostgresStore) CompareAndSwapStripeWithdrawal(previous, next *StripeWithdrawal) (bool, error) {
if err := validWithdrawalUpdate(previous, next); err != nil {
return false, err
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// The desired-state arm recognizes a successful write whose acknowledgement
// was lost. Only the expected-state arm changes fields or the timestamp.
tag, err := s.pool.Exec(ctx, `UPDATE stripe_withdrawals SET
transfer_id=$2,payout_id=$3,sweep_payout_id=$4,status=$5,
failure_reason=$6,refunded=$7,fee_refunded=$8,
updated_at=CASE WHEN ROW(transfer_id,payout_id,sweep_payout_id,status,failure_reason,refunded,fee_refunded)
IS NOT DISTINCT FROM ROW($2::text,$3::text,$4::text,$5::text,$6::text,$7::boolean,$8::boolean)
THEN updated_at ELSE NOW() END
WHERE id=$1 AND (
ROW(transfer_id,payout_id,sweep_payout_id,status,failure_reason,refunded,fee_refunded)
IS NOT DISTINCT FROM ROW($9::text,$10::text,$11::text,$12::text,$13::text,$14::boolean,$15::boolean)
OR ROW(transfer_id,payout_id,sweep_payout_id,status,failure_reason,refunded,fee_refunded)
IS NOT DISTINCT FROM ROW($2::text,$3::text,$4::text,$5::text,$6::text,$7::boolean,$8::boolean))`,
next.ID, next.TransferID, next.PayoutID, next.SweepPayoutID, next.Status, next.FailureReason, next.Refunded, next.FeeRefunded,
previous.TransferID, previous.PayoutID, previous.SweepPayoutID, previous.Status, previous.FailureReason, previous.Refunded, previous.FeeRefunded)
if err != nil {
return false, fmt.Errorf("store: compare stripe withdrawal progress: %w", err)
}
return tag.RowsAffected() > 0, nil
}
Loading
Loading