console: hold the payment cursor on a movement its charge read lacks
After a window's charges are read, every charge, refund and refund failure movement it listed must be recorded; one that is not (charge not found, not captured, or a read without the refund) fails the window, leaving the cursor and reconciled time. Movements of a charge skipped for the other mode stay excused, logged. The webhook keeps 204 for not found and not captured. The money pass test now seeds a cursor and checks MoneyMovements was asked.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3 files changed,
+113
−14
internal/console/billingmoneypass.go+41 −9internal/console/billingmoneypass_test.go+71 −4internal/console/jobs_test.go+1 −1
CI passed — run details
diff --git a/internal/console/billingmoneypass.go b/internal/console/billingmoneypass.go| index 40b1eb410..db930de3e 100644 |
| --- a/internal/console/billingmoneypass.go |
| +++ b/internal/console/billingmoneypass.go |
| @@ -45,7 +45,9 @@ func (s *Server) billingMoneyPass(ctx context.Context, now time.Time) { |
| // billingMoneyMinWindow. Each charge, refund or refund failure not yet |
| // recorded has its charge read once (recordCharge records every movement |
| // of it); a fee is recorded from the movement; anything else is logged. |
| -// The cursor moves to a window's end only once all of the window is |
| +// A charge-kind movement still unrecorded after its charge's read (not |
| +// found, not captured, or a read that lacks it) fails the window, unless |
| +// its charge was skipped for being in the other mode. The cursor moves to a window's end only once all of the window is |
| // recorded, so it never passes a movement that was not. Only a run that |
| // reaches now with no error is a success (SetPaymentsReconciled). |
| func (s *Server) reconcilePayments(ctx context.Context, now time.Time) error { |
| @@ -84,6 +86,7 @@ func (s *Server) reconcilePayments(ctx context.Context, now time.Time) error { |
| return fmt.Errorf("balance movements from %s: %w", from.Format(time.RFC3339), err) |
| } |
| var charges []string |
| + var pending []billing.Movement // charge-kind movements to be recorded by their charge's read |
| inSet := map[string]bool{} |
| for _, m := range moves { |
| seen, err := s.store.HasPayment(m.ID) |
| @@ -95,6 +98,7 @@ func (s *Server) reconcilePayments(ctx context.Context, now time.Time) error { |
| } |
| switch m.Kind { |
| case billing.MovementCharge, billing.MovementRefund, billing.MovementRefundFailure: |
| + pending = append(pending, m) |
| if !inSet[m.Charge] { |
| inSet[m.Charge] = true |
| charges = append(charges, m.Charge) |
| @@ -110,10 +114,30 @@ func (s *Server) reconcilePayments(ctx context.Context, now time.Time) error { |
| } |
| } |
| } |
| + otherMode := map[string]bool{} |
| for _, ch := range charges { |
| - if err := s.recordCharge(ctx, ch, now); err != nil { |
| + other, err := s.recordChargeMovements(ctx, ch, now) |
| + if err != nil { |
| return fmt.Errorf("charge %s: %w", ch, err) |
| } |
| + otherMode[ch] = other |
| + } |
| + // Every listed movement must now be recorded, but those of a charge |
| + // skipped for being in the other mode: a charge read that is not |
| + // found, not captured, or lacks a listed refund holds the cursor |
| + // here, and the next run reads the window again. |
| + for _, m := range pending { |
| + if otherMode[m.Charge] { |
| + continue |
| + } |
| + seen, err := s.store.HasPayment(m.ID) |
| + if err != nil { |
| + return err |
| + } |
| + if !seen { |
| + return fmt.Errorf("balance movement %s (%s of charge %s) is not in the charge's read; window from %s held", |
| + m.ID, m.Kind, m.Charge, from.Format(time.RFC3339)) |
| + } |
| } |
| if err := s.store.SetPaymentCursor(to); err != nil { |
| return err |
| @@ -133,28 +157,36 @@ func (s *Server) reconcilePayments(ctx context.Context, now time.Time) error { |
| // logged and skipped. Recording is once per movement, so the webhook and |
| // the reconcile may both call it. |
| func (s *Server) recordCharge(ctx context.Context, charge string, now time.Time) error { |
| + _, err := s.recordChargeMovements(ctx, charge, now) |
| + return err |
| +} |
| + |
| +// recordChargeMovements is recordCharge, also saying whether the charge |
| +// was skipped for being in the other mode (the reconcile excuses only |
| +// those movements from being recorded). |
| +func (s *Server) recordChargeMovements(ctx context.Context, charge string, now time.Time) (otherMode bool, err error) { |
| cfg := s.billing.cfg |
| rec, err := cfg.Provider.ChargePayments(ctx, charge) |
| if errors.Is(err, billing.ErrNotFound) { |
| - return nil |
| + return false, nil |
| } |
| if err != nil { |
| - return err |
| + return false, err |
| } |
| if !rec.Captured { |
| - return nil |
| + return false, nil |
| } |
| if rec.Charge.LiveMode != cfg.LiveMode { |
| log.Printf("console: billing money pass: charge %s is in the other mode; not recorded", charge) |
| - return nil |
| + return true, nil |
| } |
| if _, err := s.store.RecordPayment(rec.Charge, now); err != nil { |
| - return err |
| + return false, err |
| } |
| for _, p := range rec.Refunds { |
| if _, err := s.store.RecordPayment(p, now); err != nil { |
| - return err |
| + return false, err |
| } |
| } |
| - return nil |
| + return false, nil |
| } |
diff --git a/internal/console/billingmoneypass_test.go b/internal/console/billingmoneypass_test.go| index 089f94f05..932045ad7 100644 |
| --- a/internal/console/billingmoneypass_test.go |
| +++ b/internal/console/billingmoneypass_test.go |
| @@ -396,6 +396,8 @@ func TestMoneyPassFailureDoesNotStopSync(t *testing.T) { |
| if err := bf.st.PutBillingState(billingAccount{AccountID: bf.acct.ID, Subscription: "sub_1", State: "pending", PaidPacks: map[string]int{}}); err != nil { |
| t.Fatal(err) |
| } |
| + cursor := billingNow.Add(-2 * time.Hour) |
| + setCursor(t, bf.st, cursor) |
| bf.fake.Lock() |
| bf.fake.MoneyErr = errors.New("permission denied") |
| bf.fake.Unlock() |
| @@ -418,15 +420,18 @@ func TestMoneyPassFailureDoesNotStopSync(t *testing.T) { |
| if st := job(); st.State != JobFailed || !strings.Contains(st.Err, "permission denied") { |
| t.Fatalf("job = %+v; want failed with the money read's error", st) |
| } |
| - wantReconciled(t, bf.st, time.Time{}) |
| - if _, ok, _ := bf.st.PaymentCursor(); ok { |
| - t.Fatal("cursor set by a failed backfill") |
| + bf.fake.Lock() |
| + listed := bf.fake.CallsBy["MoneyMovements"] |
| + bf.fake.Unlock() |
| + if listed != 1 { |
| + t.Fatalf("MoneyMovements called %d times, want the one failed list", listed) |
| } |
| + wantReconciled(t, bf.st, time.Time{}) |
| + wantCursor(t, bf.st, cursor) |
| // With the money reads back, the same round succeeds. |
| bf.fake.Lock() |
| bf.fake.MoneyErr = nil |
| - bf.fake.AccountOpened = billingNow.Add(-24 * time.Hour) |
| bf.fake.Unlock() |
| if err := bf.srv.jobs.Run(context.Background(), "StartBillingSyncPass", func(ctx context.Context) error { |
| return bf.srv.billingRound(ctx, billingNow.Add(time.Minute)) |
| @@ -438,3 +443,65 @@ func TestMoneyPassFailureDoesNotStopSync(t *testing.T) { |
| } |
| wantReconciled(t, bf.st, billingNow.Add(time.Minute)) |
| } |
| + |
| +func TestReconcileHoldsUnrecordedChargeMovement(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + now := billingNow |
| + cursor := now.Add(-2 * time.Hour) |
| + before := now.Add(-48 * time.Hour) |
| + setCursor(t, bf.st, cursor) |
| + if err := bf.st.SetPaymentsReconciled(before); err != nil { |
| + t.Fatal(err) |
| + } |
| + // ch_1's movement is listed, but its charge read is not found yet. |
| + m, rec := testChargeRecord("ch_1", now.Add(-90*time.Minute), 1200) |
| + bf.seedMovement(m) |
| + if err := bf.srv.reconcilePayments(context.Background(), now); err == nil || !strings.Contains(err.Error(), "mv_ch_1") { |
| + t.Fatalf("err = %v; want the unrecorded movement named", err) |
| + } |
| + wantCursor(t, bf.st, cursor) |
| + wantReconciled(t, bf.st, before) |
| + |
| + // The charge is found, but its read lacks a listed refund. |
| + refundAt := now.Add(-80 * time.Minute) |
| + bf.setCharge("ch_1", rec) |
| + bf.seedMovement(billing.Movement{ID: "mv_re_1", Kind: billing.MovementRefund, Source: "re_1", Charge: "ch_1", |
| + Amount: -600, Currency: "eur", At: refundAt}) |
| + if err := bf.srv.reconcilePayments(context.Background(), now); err == nil || !strings.Contains(err.Error(), "mv_re_1") { |
| + t.Fatalf("err = %v; want the refund missing from the read named", err) |
| + } |
| + wantCursor(t, bf.st, cursor) |
| + wantReconciled(t, bf.st, before) |
| + if _, ok := paymentRows(t, bf.st)["mv_ch_1"]; !ok { |
| + t.Fatal("the charge itself was not recorded") |
| + } |
| + |
| + // The provider's read catches up: the next run records it and moves on. |
| + rec.Refunds = []billing.Payment{{Movement: "mv_re_1", Source: "re_1", Kind: billing.PaymentRefund, Reason: billing.ReasonOther, |
| + Charge: "ch_1", Amount: -600, Currency: "eur", Settled: -600, SettledCurrency: "eur", At: refundAt}} |
| + bf.setCharge("ch_1", rec) |
| + later := now.Add(time.Hour) |
| + if err := bf.srv.reconcilePayments(context.Background(), later); err != nil { |
| + t.Fatal(err) |
| + } |
| + if rows := paymentRows(t, bf.st); len(rows) != 2 { |
| + t.Fatalf("rows = %v; want the charge and its refund", rows) |
| + } |
| + wantCursor(t, bf.st, later) |
| + wantReconciled(t, bf.st, later) |
| +} |
| + |
| +func TestReconcileHoldsUncapturedChargeMovement(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + now := billingNow |
| + cursor := now.Add(-2 * time.Hour) |
| + setCursor(t, bf.st, cursor) |
| + rec := bf.seedCharge("ch_1", now.Add(-30*time.Minute), 1200) |
| + rec.Captured = false |
| + bf.setCharge("ch_1", rec) |
| + if err := bf.srv.reconcilePayments(context.Background(), now); err == nil { |
| + t.Fatal("a listed movement whose charge reads as not captured passed") |
| + } |
| + wantCursor(t, bf.st, cursor) |
| + wantReconciled(t, bf.st, time.Time{}) |
| +} |
diff --git a/internal/console/jobs_test.go b/internal/console/jobs_test.go| index c83cb72e5..43f73344a 100644 |
| --- a/internal/console/jobs_test.go |
| +++ b/internal/console/jobs_test.go |
| @@ -51,7 +51,7 @@ var jobPassFuncs = map[string][]string{ |
| "StartPlanGracePass": {"planGracePass", "planGraceAccountLocked", "notifyPlanOwners", |
| "convergeStoreDeny", "dropStaleLapseItem", "resumeStaleCapPause"}, |
| "StartDomainPurchasePass": {"domainPurchasePass", "advancePurchase", "advancePurchaseStep", "advancePurchaseEffects", "reconcileRegisteringPurchase", "purchaseMutation", "purchaseCheckout", "purchaseCheckoutStep", "registerPurchase", "registeredPurchase", "failPurchase", "purchaseAlert", "purchaseOwnerNotice"}, |
| - "StartBillingSyncPass": {"billingSyncPass", "billingDiscoveryPass", "discoverCustomer", "transitionAccountPlan", "billingMoneyPass", "reconcilePayments", "recordCharge"}, |
| + "StartBillingSyncPass": {"billingSyncPass", "billingDiscoveryPass", "discoverCustomer", "transitionAccountPlan", "billingMoneyPass", "reconcilePayments", "recordCharge", "recordChargeMovements"}, |
| "PublishPlansMarker": {"publishPlansMarkerOnce"}, |
| "StartRunSweep": {"runSweepPass", "sweepExpireQueued", "sweepLostRun", "sweepTerminalRun", "sweepOrphanRuns", |
| "orphanCandidates", "orphanConfirmed", "orphanRunEnd", "auditRunEnd", |