console: plans 6b task 7 review fixes: a late restore is explained only by an op that started at or below the baseline; restore first sends refused inside the margin; obligations stall even when the period never moves or the subscription is gone; restore pass pages; no forged hold; evidence on missing-subscription closes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+504
−80
internal/console/apibilling.go+62 −12internal/console/billinghold.go+7 −8internal/console/billinglate.go+67 −19internal/console/billinglate_test.go+178 −12internal/console/billinglint_test.go+47 −0internal/console/billingops.go+19 −5internal/console/billingops_test.go+78 −3internal/console/billingpass.go+27 −19internal/console/billingstore.go+10 −2internal/console/billingsync.go+9 −0
diff --git a/internal/console/apibilling.go b/internal/console/apibilling.go| index 0efe13c23..c2d6916bb 100644 |
| --- a/internal/console/apibilling.go |
| +++ b/internal/console/apibilling.go |
| @@ -161,7 +161,8 @@ func (s *Server) handleAPIBillingProblemClose(w http.ResponseWriter, r *http.Req |
| // closeBillingProblem closes problem p under its account's billing hold, the |
| // hold every sync of that account takes: it looks the account up, takes the |
| // hold and runs closeBillingProblemLocked. A problem with no account (an |
| -// unknown customer) is closed without a hold. |
| +// unknown customer, or an account since deleted) has no account state to |
| +// protect and is closed by closeOrphanBillingProblem, without a hold. |
| func (s *Server) closeBillingProblem(ctx context.Context, p *billingProblem, addr, note string, now time.Time) (int, string) { |
| if p.AccountID != 0 { |
| acct, err := s.store.AccountByID(p.AccountID) |
| @@ -175,7 +176,49 @@ func (s *Server) closeBillingProblem(ctx context.Context, p *billingProblem, add |
| return s.closeBillingProblemLocked(h, ctx, p, addr, note, now) |
| } |
| } |
| - return s.closeBillingProblemLocked(billingHold{}, ctx, p, addr, note, now) |
| + return s.closeOrphanBillingProblem(ctx, p, addr, note, now) |
| +} |
| + |
| +// closeOrphanBillingProblem closes a problem that belongs to no account: |
| +// the problem is re-read, the subscription read decides as for any 6a |
| +// reason, and nothing is written but the close. An operation_unresolved |
| +// problem always has an account, so one without is refused rather than |
| +// decided without the hold. |
| +func (s *Server) closeOrphanBillingProblem(ctx context.Context, p *billingProblem, addr, note string, now time.Time) (int, string) { |
| + cur, err := s.store.BillingProblem(p.ID) |
| + if err != nil { |
| + log.Printf("console: api billing close %d: %v", p.ID, err) |
| + return http.StatusInternalServerError, billingCopyFailed |
| + } |
| + if cur == nil { |
| + return http.StatusNotFound, billingCopyClosed |
| + } |
| + if !cur.ClosedAt.IsZero() { |
| + return http.StatusConflict, billingCopyClosed |
| + } |
| + if cur.Reason == problemOperationUnresolved { |
| + log.Printf("console: api billing close %d: an operation_unresolved problem with no account; refused", p.ID) |
| + return http.StatusInternalServerError, billingCopyFailed |
| + } |
| + if cur.Subscription != "" && !problemClosableWhileLive(cur.Reason) { |
| + sub, err := s.billing.cfg.Provider.Subscription(ctx, cur.Subscription) |
| + switch { |
| + case errors.Is(err, billing.ErrNotFound): |
| + case err != nil: |
| + log.Printf("console: api billing close %d: reading subscription: %v", p.ID, err) |
| + return http.StatusServiceUnavailable, billingCopyProviderDown |
| + case sub.Live: |
| + return http.StatusConflict, billingCopyStillLive |
| + } |
| + } |
| + if err := s.store.CloseBillingProblem(p.ID, addr, note, now); err != nil { |
| + if errors.Is(err, errBillingProblemClosed) { |
| + return http.StatusConflict, billingCopyClosed |
| + } |
| + log.Printf("console: api billing close %d: %v", p.ID, err) |
| + return http.StatusInternalServerError, billingCopyFailed |
| + } |
| + return http.StatusOK, "" |
| } |
| // closeBillingProblemLocked closes problem p under its account's billing |
| @@ -220,11 +263,17 @@ func (s *Server) closeBillingProblemLocked(h billingHold, ctx context.Context, p |
| return http.StatusInternalServerError, billingCopyFailed |
| } |
| } |
| + if cur.Reason == problemOperationUnresolved { |
| + // No read can show the target: the operator's note decides. |
| + if status, msg := s.closeUnresolvedOpLocked(h, acct, cur.Subscription, nil, note, now); status != http.StatusOK { |
| + return status, msg |
| + } |
| + } |
| case err != nil: |
| log.Printf("console: api billing close %d: reading subscription: %v", p.ID, err) |
| return http.StatusServiceUnavailable, billingCopyProviderDown |
| case cur.Reason == problemOperationUnresolved: |
| - if status, msg := s.closeUnresolvedOpLocked(h, acct, sub, note, now); status != http.StatusOK { |
| + if status, msg := s.closeUnresolvedOpLocked(h, acct, cur.Subscription, sub, note, now); status != http.StatusOK { |
| return status, msg |
| } |
| case sub.Live && !problemClosableWhileLive(cur.Reason): |
| @@ -242,22 +291,23 @@ func (s *Server) closeBillingProblemLocked(h billingHold, ctx context.Context, p |
| } |
| // closeUnresolvedOpLocked is the operation_unresolved close's evidence check |
| -// (Call 17), under the hold and after a fresh read of the subscription: the |
| -// target visible settles the operation applied and the close goes ahead; |
| -// otherwise the note must start with what the Dashboard request log shows, |
| -// "executed" (a 409 while the target is not visible: the subscription must |
| -// be put right first) or "not-executed" (the operation is abandoned). |
| -func (s *Server) closeUnresolvedOpLocked(h billingHold, acct *Account, sub *billing.Subscription, note string, now time.Time) (int, string) { |
| +// (Call 17), under the hold and after a fresh read of the subscription (sub, |
| +// nil when the provider no longer has it): the target visible settles the |
| +// operation applied and the close goes ahead; otherwise the note must start |
| +// with what the Dashboard request log shows, "executed" (a 409 while the |
| +// target is not visible: the subscription must be put right first) or |
| +// "not-executed" (the operation is abandoned). |
| +func (s *Server) closeUnresolvedOpLocked(h billingHold, acct *Account, subscription string, sub *billing.Subscription, note string, now time.Time) (int, string) { |
| _, _ = h, acct |
| - op, err := s.store.OutstandingOp(sub.ID) |
| + op, err := s.store.OutstandingOp(subscription) |
| if err != nil { |
| - log.Printf("console: api billing close: operation of %s: %v", sub.ID, err) |
| + log.Printf("console: api billing close: operation of %s: %v", subscription, err) |
| return http.StatusInternalServerError, billingCopyFailed |
| } |
| if op == nil || (op.State != opSending && op.State != opUnresolved) { |
| return http.StatusOK, "" // settled meanwhile: nothing left to decide |
| } |
| - if targetMet(op.Target, sub) { |
| + if sub != nil && targetMet(op.Target, sub) { |
| if err := s.store.MarkOpApplied(op.ID, sub.PeriodEnd, now); err != nil { |
| log.Printf("console: api billing close: applying %s: %v", op.ID, err) |
| return http.StatusInternalServerError, billingCopyFailed |
diff --git a/internal/console/billinghold.go b/internal/console/billinghold.go| index e392c9e37..8b8649a5d 100644 |
| --- a/internal/console/billinghold.go |
| +++ b/internal/console/billinghold.go |
| @@ -2,7 +2,6 @@ package console |
| import ( |
| "context" |
| - "errors" |
| "fmt" |
| "time" |
| @@ -129,10 +128,10 @@ func (s *Server) waitBackoff(ctx context.Context, d time.Duration) { |
| } |
| } |
| -// errNoProviderTimeRefusal is the refusal a request answers when a decision |
| -// needed provider time and none was available. |
| -var errNoProviderTimeRefusal = billingRefusal{Key: "change.clock"} |
| - |
| -// isNoProviderTime reports whether err is the missing-provider-time |
| -// condition, from the recorder or a failed probe. |
| -func isNoProviderTime(err error) bool { return errors.Is(err, billing.ErrNoProviderTime) } |
| +// The refusals every billing request shares: no provider time for a |
| +// decision that needs it, and a restore inside the renewal margin |
| +// (Invariant 4). Handlers map them to their copy keys. |
| +var ( |
| + errNoProviderTimeRefusal = billingRefusal{Key: "change.clock"} |
| + errRestoreNearRenewal = billingRefusal{Key: "change.near_renewal"} |
| +) |
diff --git a/internal/console/billinglate.go b/internal/console/billinglate.go| index 26e24bef2..c122a22ae 100644 |
| --- a/internal/console/billinglate.go |
| +++ b/internal/console/billinglate.go |
| @@ -106,11 +106,14 @@ func (s *Store) OpenRestoreChecks(subscription string) ([]restoreCheck, error) { |
| return s.restoreChecksWhere(`subscription = ? AND state = ? ORDER BY created_at, op_id`, subscription, restoreOpen) |
| } |
| -// OpenRestoreChecksAll is up to limit open obligations across every |
| -// subscription, oldest first: the pass selects open rows directly, so a |
| -// renewal the console saved and then crashed on is still checked. |
| -func (s *Store) OpenRestoreChecksAll(limit int) ([]restoreCheck, error) { |
| - return s.restoreChecksWhere(`state = ? ORDER BY created_at, op_id LIMIT ?`, restoreOpen, limit) |
| +// OpenRestoreChecksAll pages the open obligations across every |
| +// subscription, oldest first, after (afterCreated, afterID): the pass |
| +// selects open rows directly, so a renewal the console saved and then |
| +// crashed on is still checked. |
| +func (s *Store) OpenRestoreChecksAll(afterCreated time.Time, afterID string, limit int) ([]restoreCheck, error) { |
| + after := unixOrZero(afterCreated) |
| + return s.restoreChecksWhere(`state = ? AND (created_at > ? OR (created_at = ? AND op_id > ?)) ORDER BY created_at, op_id LIMIT ?`, |
| + restoreOpen, after, after, afterID, limit) |
| } |
| // PutRestoreCheck writes an obligation's progress: its baseline, attempts, |
| @@ -160,11 +163,12 @@ func (s *Store) FlagRestoreCheck(opID, detail string, now time.Time) error { |
| } |
| // StallRestoreCheck records when an open obligation was first found past its |
| -// deadline (providerNow, a provider time) and opens restore_check_stalled, |
| +// deadline (providerNow, a provider time, as stalled_at) and opens |
| +// restore_check_stalled (opened at the console's now, as every problem is), |
| // in one transaction, leaving the obligation open so it is still retried. A |
| // stall already recorded does nothing more: the problem was opened with it, |
| // and an operator who closed it is not asked again. |
| -func (s *Store) StallRestoreCheck(opID string, providerNow time.Time) error { |
| +func (s *Store) StallRestoreCheck(opID string, providerNow, now time.Time) error { |
| tx, err := s.db.Begin() |
| if err != nil { |
| return err |
| @@ -183,7 +187,7 @@ func (s *Store) StallRestoreCheck(opID string, providerNow time.Time) error { |
| } |
| detail := fmt.Sprintf("restore %s has not been verified %s after the renewal of %s", opID, |
| restoreStallAfter.String(), time.Unix(periodEnd, 0).UTC().Format(time.RFC3339)) |
| - if _, err := openBillingProblemTx(tx, accountID, subscription, problemRestoreCheckStalled, detail, providerNow); err != nil { |
| + if _, err := openBillingProblemTx(tx, accountID, subscription, problemRestoreCheckStalled, detail, now); err != nil { |
| return err |
| } |
| return tx.Commit() |
| @@ -195,12 +199,15 @@ func (s *Store) StallRestoreCheck(opID string, providerNow time.Time) error { |
| // 1. the restore's operation terminal and proved in its own period |
| // (applied with the obligation's period end), or proved never executed |
| // (failed, abandoned): clear; |
| -// 2. the read's period end still the obligation's: nothing yet; |
| +// 2. the read's period end still the obligation's: nothing yet, but the |
| +// stall deadline (step 5) still applies, so an obligation on a |
| +// subscription that ended at its period end does not stay open for ever; |
| // 3. no baseline stored: read the renewal invoice for the period starting |
| // at the obligation's period end, once; a failure counts an attempt and |
| // leaves the obligation open; |
| // 4. with a baseline: the item's quantity above it, not explained by an |
| -// applied operation first sent in the new period, is flagged, together |
| +// applied operation first sent in the new period that started at or |
| +// below the baseline and reaches the quantity, is flagged, together |
| // with its problem; otherwise a terminal operation clears, a live one |
| // stays open; |
| // 5. an obligation still open past PeriodEnd + restoreStallAfter in provider |
| @@ -232,6 +239,9 @@ func (s *Server) restoreCheckLocked(h billingHold, ctx context.Context, acct *Ac |
| continue |
| } |
| if sub.PeriodEnd.Equal(c.PeriodEnd) { |
| + if err := s.stallIfDue(ctx, c, now); err != nil { |
| + return err |
| + } |
| continue |
| } |
| if c.Baseline == nil { |
| @@ -243,7 +253,7 @@ func (s *Server) restoreCheckLocked(h billingHold, ctx context.Context, acct *Ac |
| if err := s.store.PutRestoreCheck(c); err != nil { |
| return err |
| } |
| - if err := s.stallIfDue(ctx, c); err != nil { |
| + if err := s.stallIfDue(ctx, c, now); err != nil { |
| return err |
| } |
| continue |
| @@ -268,7 +278,7 @@ func (s *Server) restoreCheckLocked(h billingHold, ctx context.Context, acct *Ac |
| } |
| billed := c.Baseline[c.Price] |
| if current > billed { |
| - explained, err := s.raiseExplained(sub.ID, c.Price, c.PeriodEnd, current) |
| + explained, err := s.raiseExplained(sub.ID, c.Price, c.PeriodEnd, billed, current) |
| if err != nil { |
| return err |
| } |
| @@ -291,7 +301,42 @@ func (s *Server) restoreCheckLocked(h billingHold, ctx context.Context, acct *Ac |
| if err := s.store.PutRestoreCheck(c); err != nil { |
| return err |
| } |
| - if err := s.stallIfDue(ctx, c); err != nil { |
| + if err := s.stallIfDue(ctx, c, now); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// restoreStallsForMissing is restoreStallsForMissingLocked for a caller |
| +// that does not hold the account's billing hold: a sync whose first lookup |
| +// already found the subscription gone never reaches the locked read, so it |
| +// takes the hold of the obligations' account here. |
| +func (s *Server) restoreStallsForMissing(ctx context.Context, subscription string, now time.Time) error { |
| + open, err := s.store.OpenRestoreChecks(subscription) |
| + if err != nil || len(open) == 0 { |
| + return err |
| + } |
| + acct, err := s.store.AccountByID(open[0].AccountID) |
| + if err != nil || acct == nil { |
| + return err |
| + } |
| + h, release := s.holdBilling(acct.Sqid) |
| + defer release() |
| + return s.restoreStallsForMissingLocked(h, ctx, subscription, now) |
| +} |
| + |
| +// restoreStallsForMissingLocked is the stall deadline for the open |
| +// obligations of a subscription the provider no longer has: nothing else |
| +// can be decided about them, but R1's deadline is unconditional. |
| +func (s *Server) restoreStallsForMissingLocked(h billingHold, ctx context.Context, subscription string, now time.Time) error { |
| + _ = h |
| + open, err := s.store.OpenRestoreChecks(subscription) |
| + if err != nil { |
| + return err |
| + } |
| + for _, c := range open { |
| + if err := s.stallIfDue(ctx, c, now); err != nil { |
| return err |
| } |
| } |
| @@ -299,15 +344,18 @@ func (s *Server) restoreCheckLocked(h billingHold, ctx context.Context, acct *Ac |
| } |
| // raiseExplained reports whether a quantity above the renewal's baseline is |
| -// accounted for by an applied operation first sent in the new period whose |
| -// target reaches it. |
| -func (s *Server) raiseExplained(subscription, price string, periodEnd time.Time, current int64) (bool, error) { |
| +// accounted for by an applied operation first sent in the new period that |
| +// started at or below the baseline and whose target reaches the quantity. |
| +// A charge built on top of a late-restored quantity starts above the |
| +// baseline and explains nothing, so the late restore under it is still |
| +// flagged. |
| +func (s *Server) raiseExplained(subscription, price string, periodEnd time.Time, baseline, current int64) (bool, error) { |
| ops, err := s.store.AppliedOpsSince(subscription, periodEnd) |
| if err != nil { |
| return false, err |
| } |
| for _, op := range ops { |
| - if q, ok := op.Target.Quantities[price]; ok && q >= current { |
| + if q, ok := op.Target.Quantities[price]; ok && q >= current && op.StartQuantity <= baseline { |
| return true, nil |
| } |
| } |
| @@ -317,7 +365,7 @@ func (s *Server) raiseExplained(subscription, price string, periodEnd time.Time, |
| // stallIfDue stalls an obligation still open once provider time is past its |
| // deadline. The decision needs provider time: the recorder's observation, or |
| // one probe; with none it waits for the next observation. |
| -func (s *Server) stallIfDue(ctx context.Context, c restoreCheck) error { |
| +func (s *Server) stallIfDue(ctx context.Context, c restoreCheck, now time.Time) error { |
| pnow, err := s.providerNow(ctx) |
| if err != nil { |
| log.Printf("console: billing: restore %s: no provider time for the stall deadline; decided at the next observation", c.OpID) |
| @@ -326,5 +374,5 @@ func (s *Server) stallIfDue(ctx context.Context, c restoreCheck) error { |
| if !pnow.After(c.PeriodEnd.Add(restoreStallAfter)) { |
| return nil |
| } |
| - return s.store.StallRestoreCheck(c.OpID, pnow) |
| + return s.store.StallRestoreCheck(c.OpID, pnow, now) |
| } |
diff --git a/internal/console/billinglate_test.go b/internal/console/billinglate_test.go| index 5d6c4e4e5..8c9535b73 100644 |
| --- a/internal/console/billinglate_test.go |
| +++ b/internal/console/billinglate_test.go |
| @@ -2,6 +2,7 @@ package console |
| import ( |
| "context" |
| + "errors" |
| "fmt" |
| "net/http" |
| "slices" |
| @@ -270,28 +271,35 @@ func TestRestoreCheckBaselineIgnoresLaterInvoices(t *testing.T) { |
| } |
| }) |
| t.Run("explained_by_a_new_period_op", func(t *testing.T) { |
| + // The restore lands late (1 -> 3, the renewal billed 1) and the |
| + // baseline read fails at that observation, so the obligation stays |
| + // open with the operation applied in the new period. The owner then |
| + // reduces to 1 and buys 4: the charge started at the baseline and |
| + // reaches the quantity, so it explains the raise and nothing is free. |
| o := newRestoreFixture(t) |
| - op := o.restoreOp(t, "op_1", "sub_1") |
| - o.unresolved(t, op) |
| + o.heldRestore(t, "op_1", "sub_1") |
| if err := o.fake.Renew("sub_1"); err != nil { |
| t.Fatal(err) |
| } |
| + o.fake.InvoiceReadFails(1) |
| o.pass(billingNow) |
| - if c := o.check(t, "op_1"); c.State != restoreOpen { |
| - t.Fatalf("%+v", c) |
| - } |
| - // The operator finds it never executed; then a charged add in the |
| - // new period raises the quantity. |
| - if err := o.st.PutBillingOpState("op_1", opAbandoned, false, billingNow); err != nil { |
| - t.Fatal(err) |
| + if c := o.check(t, "op_1"); c.State != restoreOpen || c.Attempts != 1 || o.op(t, "op_1").State != opApplied { |
| + t.Fatalf("after the failed baseline read: %+v op %+v", c, o.op(t, "op_1")) |
| } |
| o.fresh() |
| o.observe() |
| - if out, _, err := o.send(t, o.packOp(t, "op_2", "sub_1", "apps", 4, billing.ProrateNow, opPack)); err != nil || out.State != opApplied { |
| - t.Fatalf("outcome = %+v %v", out, err) |
| + if out, _, err := o.send(t, o.packOp(t, "op_2", "sub_1", "apps", 1, billing.ProrateNone, opPack)); err != nil || out.State != opApplied { |
| + t.Fatalf("reduction = %+v %v", out, err) |
| + } |
| + o.observe() |
| + if out, _, err := o.send(t, o.packOp(t, "op_3", "sub_1", "apps", 4, billing.ProrateNow, opPack)); err != nil || out.State != opApplied { |
| + t.Fatalf("charge = %+v %v", out, err) |
| + } |
| + if row := o.op(t, "op_3"); row.StartQuantity != 1 { |
| + t.Fatalf("op_3 started at %d, want 1", row.StartQuantity) |
| } |
| o.pass(billingNow.Add(time.Hour)) |
| - if c := o.check(t, "op_1"); c.State != restoreClear { |
| + if c := o.check(t, "op_1"); c.State != restoreClear || c.Baseline[c.Price] != 1 { |
| t.Fatalf("explained raise flagged: %+v", c) |
| } |
| if got := o.openProblems(t); slices.Contains(got, problemRestoreAfterRenewal) { |
| @@ -300,6 +308,164 @@ func TestRestoreCheckBaselineIgnoresLaterInvoices(t *testing.T) { |
| }) |
| } |
| +// The reviewer's sequence: the restore lands late (1 -> 3) after the |
| +// renewal billed 1, the baseline read fails at that observation, and the |
| +// owner then buys one more (3 -> 4). The charge started above the baseline, |
| +// so it explains only its own step: the late restore under it is flagged. |
| +func TestLateRestoreThenChargeStillFlags(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + o.heldRestore(t, "op_1", "sub_1") |
| + if err := o.fake.Renew("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.fake.InvoiceReadFails(1) |
| + o.pass(billingNow) |
| + if c := o.check(t, "op_1"); c.State != restoreOpen || c.Attempts != 1 { |
| + t.Fatalf("after the failed baseline read: %+v", c) |
| + } |
| + o.fresh() |
| + o.observe() |
| + if out, _, err := o.send(t, o.packOp(t, "op_2", "sub_1", "apps", 4, billing.ProrateNow, opPack)); err != nil || out.State != opApplied { |
| + t.Fatalf("charge = %+v %v", out, err) |
| + } |
| + if row := o.op(t, "op_2"); row.StartQuantity != 3 { |
| + t.Fatalf("op_2 started at %d, want 3", row.StartQuantity) |
| + } |
| + o.pass(billingNow.Add(time.Hour)) |
| + c := o.check(t, "op_1") |
| + if c.State != restoreFlagged || c.Baseline[c.Price] != 1 { |
| + t.Fatalf("obligation = %+v", c) |
| + } |
| + open, _ := o.st.BillingProblems(false) |
| + want := fmt.Sprintf("item %s is at 4, the renewal billed 1", o.packItem(t, "sub_1", "apps").ItemID) |
| + found := false |
| + for _, p := range open { |
| + found = found || (p.Reason == problemRestoreAfterRenewal && p.Detail == want) |
| + } |
| + if !found { |
| + t.Fatalf("problems = %+v, want %q", open, want) |
| + } |
| +} |
| + |
| +// Invariant 4's backstop: sendOpLocked refuses a restore's first send inside |
| +// the margin, writing and sending nothing. |
| +func TestRestoreRefusedNearRenewalInSend(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + s := o.sub("sub_1") |
| + s.PeriodEnd = o.providerClock().Add(restoreMargin - time.Hour) |
| + o.put(s) |
| + if err := o.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.reset() |
| + o.observe() |
| + op := o.restoreOp(t, "op_1", "sub_1") |
| + var refusal billingRefusal |
| + _, _, err := o.send(t, op) |
| + if !errors.As(err, &refusal) || refusal.Key != "change.near_renewal" { |
| + t.Fatalf("err = %v, want the change.near_renewal refusal", err) |
| + } |
| + if row, err := o.st.BillingOp("op_1"); err != nil || row != nil { |
| + t.Fatalf("an op was written: %+v %v", row, err) |
| + } |
| + if len(o.counts()) != 0 { |
| + t.Fatalf("calls = %v, want none", o.counts()) |
| + } |
| + // Just outside the margin it goes. |
| + s.PeriodEnd = o.providerClock().Add(restoreMargin + time.Hour) |
| + o.put(s) |
| + if err := o.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.observe() |
| + if out, _, err := o.send(t, o.restoreOp(t, "op_2", "sub_1")); err != nil || out.State != opApplied { |
| + t.Fatalf("outside the margin: %+v %v", out, err) |
| + } |
| +} |
| + |
| +// R1's deadline is unconditional: an obligation whose period never moves |
| +// (the subscription ended at its period end) still stalls. |
| +func TestRestoreStallsWhenPeriodNeverMoves(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + o.unresolved(t, o.restoreOp(t, "op_1", "sub_1")) |
| + s := o.sub("sub_1") |
| + s.CancelAtPeriodEnd = true |
| + o.put(s) |
| + if err := o.fake.Renew("sub_1"); err != nil { // ends instead of renewing |
| + t.Fatal(err) |
| + } |
| + o.pass(billingNow) |
| + if p := o.plan(t); p != "free" { |
| + t.Fatalf("plan after the end = %q", p) |
| + } |
| + if c := o.check(t, "op_1"); c.State != restoreOpen || !c.StalledAt.IsZero() { |
| + t.Fatalf("stalled early: %+v", c) |
| + } |
| + o.fake.AdvanceProvider(restoreStallAfter + time.Minute) |
| + o.pass(billingNow.Add(time.Hour)) |
| + if got := o.openProblems(t); !slices.Contains(got, problemRestoreCheckStalled) { |
| + t.Fatalf("problems = %v", got) |
| + } |
| + if c := o.check(t, "op_1"); c.State != restoreOpen || !c.StalledAt.Equal(o.providerClock()) { |
| + t.Fatalf("obligation = %+v, want stalled_at at provider time %v", c, o.providerClock()) |
| + } |
| + // The problem is stamped with the console's clock, as every problem is; |
| + // only stalled_at carries provider time. |
| + all, _ := o.st.BillingProblems(false) |
| + for _, p := range all { |
| + if p.Reason == problemRestoreCheckStalled && !p.OpenedAt.Equal(billingNow.Add(time.Hour)) { |
| + t.Fatalf("stall problem opened_at = %v, want the console's %v", p.OpenedAt, billingNow.Add(time.Hour)) |
| + } |
| + } |
| + if o.fake.Writes() != 0 { |
| + t.Fatalf("writes = %d", o.fake.Writes()) |
| + } |
| +} |
| + |
| +// And one whose subscription the provider no longer has. |
| +func TestRestoreStallsWhenSubscriptionMissing(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + o.unresolved(t, o.restoreOp(t, "op_1", "sub_1")) |
| + o.fake.Lock() |
| + delete(o.fake.Subs, "sub_1") |
| + o.fake.Unlock() |
| + o.fake.SetProviderClock(periodEnd.Add(restoreStallAfter - time.Hour)) |
| + o.pass(billingNow) |
| + got := o.openProblems(t) |
| + if !slices.Contains(got, problemSubscriptionMissing) || slices.Contains(got, problemRestoreCheckStalled) { |
| + t.Fatalf("problems = %v", got) |
| + } |
| + o.fake.SetProviderClock(periodEnd.Add(restoreStallAfter + time.Minute)) |
| + o.pass(billingNow.Add(time.Hour)) |
| + if got := o.openProblems(t); !slices.Contains(got, problemRestoreCheckStalled) { |
| + t.Fatalf("problems = %v", got) |
| + } |
| + if c := o.check(t, "op_1"); c.State != restoreOpen || !c.StalledAt.Equal(o.providerClock()) { |
| + t.Fatalf("obligation = %+v", c) |
| + } |
| +} |
| + |
| +// The restore pass pages its obligations. |
| +func TestRestorePassPagesObligations(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + o.secondAccount(t) |
| + old := billingSyncBatch |
| + billingSyncBatch = 1 |
| + t.Cleanup(func() { billingSyncBatch = old }) |
| + for _, id := range []string{"sub_1", "sub_2"} { |
| + o.unresolved(t, o.restoreOp(t, "op_"+id, id)) |
| + if err := o.fake.Renew(id); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + o.srv.billingRestorePass(o.srv.billingClock(context.Background()), billingNow, map[string]bool{}) |
| + for _, id := range []string{"op_sub_1", "op_sub_2"} { |
| + if c := o.check(t, id); c.Baseline == nil { |
| + t.Fatalf("%s not checked: %+v", id, c) |
| + } |
| + } |
| +} |
| + |
| func TestRestoreCheckStalls(t *testing.T) { |
| o := newRestoreFixture(t) |
| o.heldRestore(t, "op_1", "sub_1") |
diff --git a/internal/console/billinglint_test.go b/internal/console/billinglint_test.go| index 089cd6151..7d65f6e6e 100644 |
| --- a/internal/console/billinglint_test.go |
| +++ b/internal/console/billinglint_test.go |
| @@ -183,6 +183,47 @@ func (m *mailer) ensureLocked() {} |
| } |
| } |
| +// billingHoldMintFindings reports every billingHold composite literal outside |
| +// holdBilling: a hold built anywhere else is a hold nobody took. |
| +func billingHoldMintFindings(fset *token.FileSet, files map[string]*ast.File) []string { |
| + var findings []string |
| + for _, f := range files { |
| + for _, d := range f.Decls { |
| + fd, ok := d.(*ast.FuncDecl) |
| + if !ok || fd.Body == nil || fd.Name.Name == "holdBilling" { |
| + continue |
| + } |
| + ast.Inspect(fd.Body, func(n ast.Node) bool { |
| + if lit, ok := n.(*ast.CompositeLit); ok { |
| + if id, ok := lit.Type.(*ast.Ident); ok && id.Name == "billingHold" { |
| + findings = append(findings, fset.Position(lit.Pos()).String()+": "+fd.Name.Name+" builds a billingHold") |
| + } |
| + } |
| + return true |
| + }) |
| + } |
| + } |
| + sort.Strings(findings) |
| + return findings |
| +} |
| + |
| +// TestBillingHoldMintedOnlyByHoldBilling: only holdBilling makes a |
| +// billingHold, so every function that has one was handed a lock someone |
| +// took (no forged billingHold{} for a deleted account). |
| +func TestBillingHoldMintedOnlyByHoldBilling(t *testing.T) { |
| + fset, files := parsePackageSources(t) |
| + for _, f := range billingHoldMintFindings(fset, files) { |
| + t.Error(f) |
| + } |
| + planted := parsePlanted(t, fset, "billingplanted.go", ` |
| +func (s *Server) holdBilling(sqid string) (billingHold, func()) { return billingHold{sqid: sqid}, func() {} } |
| +func (s *Server) forge() { s.closeBillingProblemLocked(billingHold{}, nil, nil, "", "", 0) } |
| +`) |
| + if got := billingHoldMintFindings(fset, planted); len(got) != 1 || !strings.Contains(got[0], "forge") { |
| + t.Fatalf("planted findings = %v, want forge only", got) |
| + } |
| +} |
| + |
| // providerStatusWords are the provider's own status words, which stay inside |
| // the adapter (Global Constraints: provider neutrality). |
| var providerStatusWords = regexp.MustCompile(`\b(active|trialing|past_due|incomplete|incomplete_expired|unpaid|canceled|paused)\b`) |
| @@ -298,6 +339,12 @@ func sendGateFindings(fset *token.FileSet, files map[string]*ast.File) []string |
| return findings |
| } |
| +// TestRecoveryEligibleIsTheOnlyGate is a structural proxy: it proves no |
| +// billing function sends without calling the gate, and that each has one |
| +// Send site, not that the gate's answer is honoured. The behavioural tests |
| +// prove that (TestNoResendAfterKeyLifetime, TestNoResendAfterPeriodMargin, |
| +// TestFirstSendUnderSkewThenLateRecoveryRefused, TestFailedProbeSendsNothing, |
| +// TestNoProviderTimeNoSend); a gate whose result is ignored fails them. |
| func TestRecoveryEligibleIsTheOnlyGate(t *testing.T) { |
| fset, files := parsePackageSources(t) |
| for _, f := range sendGateFindings(fset, files) { |
diff --git a/internal/console/billingops.go b/internal/console/billingops.go| index b5f16c58c..ddbced289 100644 |
| --- a/internal/console/billingops.go |
| +++ b/internal/console/billingops.go |
| @@ -106,6 +106,11 @@ type billingOp struct { |
| FirstSentAt, LastSentAt, SettledAt time.Time |
| AppliedPeriodEnd time.Time |
| CreatedAt time.Time |
| + // StartQuantity is the changed item's quantity before the change, |
| + // recorded when the request is prepared (0 for a new item). A charge |
| + // explains a quantity above a renewal's baseline only when it started at |
| + // or below that baseline (Risk R1). |
| + StartQuantity int64 |
| } |
| // resendUntil is the end of the operation's resend window in provider time: |
| @@ -123,7 +128,7 @@ func (op billingOp) resendUntil() time.Time { |
| var ErrOpOutstanding = errors.New("billing: an operation is outstanding on the subscription") |
| const billingOpColumns = `id, account_id, subscription, kind, period_end, target, prepared, invite_token, authorised_by, |
| - state, indeterminate, first_sent_at, last_sent_at, settled_at, applied_period_end, created_at` |
| + state, indeterminate, first_sent_at, last_sent_at, settled_at, applied_period_end, created_at, start_quantity` |
| func scanBillingOp(sc interface{ Scan(...any) error }) (*billingOp, error) { |
| var op billingOp |
| @@ -131,7 +136,7 @@ func scanBillingOp(sc interface{ Scan(...any) error }) (*billingOp, error) { |
| var periodEnd, firstSent, lastSent, settled, applied, created int64 |
| var indeterminate int |
| if err := sc.Scan(&op.ID, &op.AccountID, &op.Subscription, &op.Kind, &periodEnd, &target, &prepared, &op.InviteToken, &op.AuthorisedBy, |
| - &op.State, &indeterminate, &firstSent, &lastSent, &settled, &applied, &created); err != nil { |
| + &op.State, &indeterminate, &firstSent, &lastSent, &settled, &applied, &created, &op.StartQuantity); err != nil { |
| return nil, err |
| } |
| if err := json.Unmarshal(target, &op.Target); err != nil { |
| @@ -204,10 +209,10 @@ func (s *Store) BeginBillingOp(op billingOp) error { |
| if n > 0 { |
| return ErrOpOutstanding |
| } |
| - if _, err := tx.Exec(`INSERT INTO billing_operations (`+billingOpColumns+`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, |
| + if _, err := tx.Exec(`INSERT INTO billing_operations (`+billingOpColumns+`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, |
| op.ID, op.AccountID, op.Subscription, op.Kind, unixOrZero(op.PeriodEnd), target, prepared, op.InviteToken, op.AuthorisedBy, |
| op.State, boolInt(op.Indeterminate), unixOrZero(op.FirstSentAt), unixOrZero(op.LastSentAt), unixOrZero(op.SettledAt), |
| - unixOrZero(op.AppliedPeriodEnd), unixOrZero(op.CreatedAt)); err != nil { |
| + unixOrZero(op.AppliedPeriodEnd), unixOrZero(op.CreatedAt), op.StartQuantity); err != nil { |
| return err |
| } |
| if op.Kind == opRestore { |
| @@ -509,7 +514,10 @@ func (s *Server) recordSendOutcome(op *billingOp, res billing.Result, err error, |
| // read of the subscription, which settles on positive evidence; the same |
| // bytes are resent only while recoveryEligible. The outcome is recorded as |
| // recordSendOutcome says. With no provider time nothing is written or sent |
| -// and the request is refused with change.clock. |
| +// and the request is refused with change.clock. A restore inside |
| +// restoreMargin of the period end (Invariant 4) is refused the same way |
| +// with errRestoreNearRenewal: the handlers check it first, and this is the |
| +// backstop. |
| func (s *Server) sendOpLocked(h billingHold, ctx context.Context, op billingOp, now time.Time) (opOutcome, *billing.Subscription, error) { |
| _ = h |
| cfg := s.billing.cfg |
| @@ -517,6 +525,9 @@ func (s *Server) sendOpLocked(h billingHold, ctx context.Context, op billingOp, |
| if err != nil { |
| return opOutcome{}, nil, errNoProviderTimeRefusal |
| } |
| + if op.Kind == opRestore && op.PeriodEnd.Sub(pnow) <= restoreMargin { |
| + return opOutcome{}, nil, errRestoreNearRenewal |
| + } |
| op.FirstSentAt, op.LastSentAt, op.State, op.Indeterminate, op.CreatedAt = pnow, pnow, opSending, false, now |
| if err := s.store.BeginBillingOp(op); err != nil { |
| return opOutcome{}, nil, err |
| @@ -569,6 +580,9 @@ func (s *Server) finishOpLocked(h billingHold, ctx context.Context, acct *Accoun |
| } |
| sub, err := cfg.Provider.Subscription(ctx, op.Subscription) |
| if errors.Is(err, billing.ErrNotFound) { |
| + if err := s.restoreStallsForMissingLocked(h, ctx, op.Subscription, now); err != nil { |
| + return opOutcome{}, err |
| + } |
| return opOutcome{State: opUnresolved, Indeterminate: op.Indeterminate}, s.subscriptionMissing(op.Subscription, now) |
| } |
| if err != nil { |
diff --git a/internal/console/billingops_test.go b/internal/console/billingops_test.go| index 02c92946a..591ba8819 100644 |
| --- a/internal/console/billingops_test.go |
| +++ b/internal/console/billingops_test.go |
| @@ -145,7 +145,7 @@ func (o *opsFixture) packOp(t *testing.T, id, subID, name string, qty int64, pr |
| } |
| sub := o.sub(subID) |
| return billingOp{ID: id, Subscription: subID, Kind: kind, AccountID: o.accountOf(t, subID), PeriodEnd: sub.PeriodEnd, |
| - Target: opTarget{Quantities: map[string]int64{it.PriceID: qty}}, Prepared: p} |
| + Target: opTarget{Quantities: map[string]int64{it.PriceID: qty}}, Prepared: p, StartQuantity: it.Quantity} |
| } |
| func (o *opsFixture) accountOf(t *testing.T, subID string) int64 { |
| @@ -845,8 +845,83 @@ func TestCrashBeforeSendRecovered(t *testing.T) { |
| if row := o.op(t, "op_1"); row.State != opApplied { |
| t.Fatalf("row = %+v", row) |
| } |
| - if o.fake.Writes() != 1 || o.counts()["Subscription"] < 1 { |
| - t.Fatalf("calls = %v", o.counts()) |
| + // Confirm now's budget for an unresolved op: F (a read, then one resend) |
| + // + S (the refresh's read). |
| + wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1}) |
| +} |
| + |
| +// A problem whose account is gone is closed without a hold, and nothing is |
| +// decided about an operation there: an operation_unresolved close with no |
| +// account is refused and the operation is left as it is. Other reasons |
| +// still close. |
| +func TestOperatorCloseWithNoAccount(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.unresolved(t, o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack)) |
| + const gone = 999999 |
| + if _, err := o.st.OpenBillingProblem(gone, "sub_1", problemOperationUnresolved, "test", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := o.st.OpenBillingProblem(0, "sub_unknown", problemUnknownCustomer, "test", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + open, err := o.st.BillingProblems(false) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, p := range open { |
| + status, msg := o.srv.closeBillingProblem(context.Background(), &p, "ops@keymail.dev", "not-executed", billingNow) |
| + switch p.Reason { |
| + case problemOperationUnresolved: |
| + if status != http.StatusInternalServerError || msg != billingCopyFailed { |
| + t.Fatalf("operation_unresolved with no account: %d %q", status, msg) |
| + } |
| + case problemUnknownCustomer: |
| + if status != http.StatusOK { |
| + t.Fatalf("unknown_customer with no account: %d %q", status, msg) |
| + } |
| + } |
| + } |
| + if row := o.op(t, "op_1"); row.State != opUnresolved { |
| + t.Fatalf("row = %+v", row) |
| + } |
| + got := o.openProblems(t) |
| + if !slices.Contains(got, problemOperationUnresolved) || slices.Contains(got, problemUnknownCustomer) { |
| + t.Fatalf("problems = %v", got) |
| + } |
| +} |
| + |
| +// The provider no longer has the subscription: no read can show the target, |
| +// so the operation_unresolved close still needs the operator's evidence. |
| +func TestOperatorCloseOfMissingSubscriptionNeedsEvidence(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.unresolved(t, op) |
| + o.fake.Lock() |
| + delete(o.fake.Subs, "sub_1") |
| + o.fake.Unlock() |
| + if _, err := o.st.OpenBillingProblem(o.acct.ID, "sub_1", problemOperationUnresolved, "test", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + open, _ := o.st.BillingProblems(false) |
| + operator := planOperatorToken(t, o.consoleFixture, "ops@keymail.dev", "code-billing-missing-evidence") |
| + closeURL := billingCloseURL(o.consoleFixture, open[0].ID) |
| + if status, out := postJSON(t, closeURL, map[string]any{"note": "checked"}, operator); status != http.StatusConflict || out["error"] != billingCopyOpEvidence { |
| + t.Fatalf("no evidence: %d %v", status, out) |
| + } |
| + if status, out := postJSON(t, closeURL, map[string]any{"note": "executed"}, operator); status != http.StatusConflict || out["error"] != billingCopyOpExecutedUnseen { |
| + t.Fatalf("executed, nothing to show it: %d %v", status, out) |
| + } |
| + if row := o.op(t, "op_1"); row.State != opUnresolved { |
| + t.Fatalf("row = %+v", row) |
| + } |
| + if status, _ := postJSON(t, closeURL, map[string]any{"note": "not-executed"}, operator); status != http.StatusOK { |
| + t.Fatalf("not-executed: %d", status) |
| + } |
| + if row := o.op(t, "op_1"); row.State != opAbandoned { |
| + t.Fatalf("row = %+v", row) |
| + } |
| + if got := o.openProblems(t); slices.Contains(got, problemOperationUnresolved) { |
| + t.Fatalf("problems = %v", got) |
| } |
| } |
diff --git a/internal/console/billingpass.go b/internal/console/billingpass.go| index 452e57eaa..efe53abda 100644 |
| --- a/internal/console/billingpass.go |
| +++ b/internal/console/billingpass.go |
| @@ -205,28 +205,36 @@ func (s *Server) observeOp(ctx context.Context, op billingOp, now time.Time, syn |
| // runs restoreCheckLocked, so an obligation whose renewal was saved before a |
| // crash is still checked. Reads and problems only: 0 writes. |
| func (s *Server) billingRestorePass(ctx context.Context, now time.Time, synced map[string]bool) { |
| - open, err := s.store.OpenRestoreChecksAll(billingSyncBatch) |
| - if err != nil { |
| - log.Printf("console: billing restore pass: %v", err) |
| - return |
| - } |
| - for _, c := range open { |
| - if ctx.Err() != nil || synced[c.Subscription] { |
| - continue |
| + var afterCreated time.Time |
| + afterID := "" |
| + for ctx.Err() == nil { |
| + page, err := s.store.OpenRestoreChecksAll(afterCreated, afterID, billingSyncBatch) |
| + if err != nil { |
| + log.Printf("console: billing restore pass: %v", err) |
| + return |
| } |
| - acct, err := s.store.AccountByID(c.AccountID) |
| - if err != nil || acct == nil { |
| - log.Printf("console: billing restore pass: obligation %s: account %d: %v", c.OpID, c.AccountID, err) |
| - continue |
| + for _, c := range page { |
| + afterCreated, afterID = c.CreatedAt, c.OpID |
| + if synced[c.Subscription] { |
| + continue |
| + } |
| + acct, err := s.store.AccountByID(c.AccountID) |
| + if err != nil || acct == nil { |
| + log.Printf("console: billing restore pass: obligation %s: account %d: %v", c.OpID, c.AccountID, err) |
| + continue |
| + } |
| + h, release := s.holdBilling(acct.Sqid) |
| + err = s.syncSubscriptionLocked(h, ctx, acct, c.Subscription, now) |
| + release() |
| + if err != nil { |
| + log.Printf("console: billing restore pass: obligation %s: %v", c.OpID, err) |
| + continue |
| + } |
| + synced[c.Subscription] = true |
| } |
| - h, release := s.holdBilling(acct.Sqid) |
| - err = s.syncSubscriptionLocked(h, ctx, acct, c.Subscription, now) |
| - release() |
| - if err != nil { |
| - log.Printf("console: billing restore pass: obligation %s: %v", c.OpID, err) |
| - continue |
| + if len(page) < billingSyncBatch { |
| + return |
| } |
| - synced[c.Subscription] = true |
| } |
| } |
diff --git a/internal/console/billingstore.go b/internal/console/billingstore.go| index ee606451d..a0634d38b 100644 |
| --- a/internal/console/billingstore.go |
| +++ b/internal/console/billingstore.go |
| @@ -224,11 +224,19 @@ func (s *Store) migrateBillingOperations() error { |
| last_sent_at INTEGER NOT NULL DEFAULT 0, |
| settled_at INTEGER NOT NULL DEFAULT 0, |
| applied_period_end INTEGER NOT NULL DEFAULT 0, |
| - created_at INTEGER NOT NULL |
| + created_at INTEGER NOT NULL, |
| + start_quantity INTEGER NOT NULL DEFAULT 0 |
| ); |
| CREATE UNIQUE INDEX IF NOT EXISTS billing_operations_outstanding ON billing_operations(subscription) WHERE state IN ('sending', 'unresolved', 'pending'); |
| CREATE INDEX IF NOT EXISTS billing_operations_invite ON billing_operations(invite_token) WHERE invite_token != '';`) |
| - return err |
| + if err != nil { |
| + return err |
| + } |
| + // Additive, for a store created before the column existed. |
| + if _, err := s.db.Exec(`ALTER TABLE billing_operations ADD COLUMN start_quantity INTEGER NOT NULL DEFAULT 0`); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| + return err |
| + } |
| + return nil |
| } |
| // billingAccount is one account's billing state. |
diff --git a/internal/console/billingsync.go b/internal/console/billingsync.go| index 0534d2ee5..5354bf694 100644 |
| --- a/internal/console/billingsync.go |
| +++ b/internal/console/billingsync.go |
| @@ -177,6 +177,9 @@ func (s *Server) syncSubscription(ctx context.Context, subscriptionID string, no |
| cfg := s.billing.cfg |
| first, err := cfg.Provider.Subscription(ctx, subscriptionID) |
| if errors.Is(err, billing.ErrNotFound) { |
| + if err := s.restoreStallsForMissing(ctx, subscriptionID, now); err != nil { |
| + return err |
| + } |
| return s.subscriptionMissing(subscriptionID, now) |
| } |
| if err != nil { |
| @@ -222,6 +225,9 @@ func (s *Server) syncSubscriptionLocked(h billingHold, ctx context.Context, acct |
| ctx = s.billingClock(ctx) |
| sub, err := cfg.Provider.Subscription(ctx, subscriptionID) |
| if errors.Is(err, billing.ErrNotFound) { |
| + if err := s.restoreStallsForMissingLocked(h, ctx, subscriptionID, now); err != nil { |
| + return err |
| + } |
| return s.subscriptionMissing(subscriptionID, now) |
| } |
| if err != nil { |
| @@ -277,6 +283,9 @@ func (s *Server) refreshLocked(h billingHold, ctx context.Context, acct *Account |
| cfg := s.billing.cfg |
| sub, err := cfg.Provider.Subscription(ctx, prev.Subscription) |
| if errors.Is(err, billing.ErrNotFound) { |
| + if err := s.restoreStallsForMissingLocked(h, ctx, prev.Subscription, now); err != nil { |
| + return nil, nil, err |
| + } |
| return prev, nil, s.subscriptionMissing(prev.Subscription, now) |
| } |
| if err != nil { |