plans 6a: Astra round 2 fixes. Discovery keeps a customer outstanding until every candidate syncs; adopting a replacement that grants no entitlement applies the old subscription's end (default plan, lapse) in the same commit; closing a missing-subscription problem decides under the billing lock and a sync that finds the subscription resolves the problem; the deadlock test drives the operator door too. Example catalog: Free awake hours 90 a month (Paul)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+417
−40
docs/superpowers/specs/CODEX-FINDINGS-PLANS-6A-CODE-R2.md+117 −0internal/billing/billingtest/fake.go+15 −0internal/console/apibilling.go+63 −15internal/console/billinglapse_test.go+13 −3internal/console/billingpass.go+11 −2internal/console/billingrecovery_test.go+134 −0internal/console/billingstore.go+32 −5internal/console/billingsync.go+29 −12internal/plans/testdata/example-catalog.json+1 −1internal/plans/testdata/example-public-pricebook.json+2 −2
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-PLANS-6A-CODE-R2.md b/docs/superpowers/specs/CODEX-FINDINGS-PLANS-6A-CODE-R2.md| new file mode 100644 |
| index 000000000..d1253ddf1 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/CODEX-FINDINGS-PLANS-6A-CODE-R2.md |
| @@ -0,0 +1,117 @@ |
| +**Verdict: changes required** at `05b28473491179ea6829019aba97265cb5b80cda`. |
| + |
| +Three new **Important** findings. No Critical findings. Review was read-only, with no network calls. Targeted Go tests could not start because the sandbox refused creation of Go’s build directory; test references below describe coverage inspected, not tests passed. |
| + |
| +Round 1 dispositions: |
| + |
| +| # | Disposition | Evidence | |
| +|---|---|---| |
| +| 1. Replacement rejected using stale state | **Partly fixed** | [billingsync.go:195](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingsync.go:195) rereads the previous subscription and returns transient errors for retry. `TestReplacementSubscriptionBeforeOldCancellation` and `TestReplacementWaitsForTheOldRead` cover this. A pending replacement introduces finding 2 below. | |
| +| 2. Billing state committed before the plan | **Fixed** | [billingstore.go:331](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:331) commits billing state, guarded plan change, lapse mark and grace resets together. `TestSyncFailureBetweenWritesIsRetried` injects a failed plan write and checks rollback and recovery. | |
| +| 3. Missed first purchase never discovered | **Partly fixed** | [billingpass.go:108](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingpass.go:108) discovers subscriptions for recently bound customers. `TestSyncPassDiscoversAMissedFirstPurchase` covers one successful candidate, but discovery can lose outstanding work: finding 1 below. | |
| +| 4. Missing subscription has no actionable problem | **Partly fixed** | [billingsync.go:247](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingsync.go:247) opens a deduplicated problem; closing it can end entitlement. `TestMissingSubscriptionOpensAProblemThenCloses` covers the sequential path. Closure has the race in finding 3. | |
| +| 5. Billing bypasses lapse lifecycle | **Fixed** | [planlapse.go:106](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/planlapse.go:106) shares `transitionAccountPlan` with the operator path. `TestBillingCancellationStartsALapse`, `TestBillingPackReductionAtRenewalStartsALapse` and `TestBillingRepaymentTurnsThingsBackOn` cover the intended integration. | |
| +| 6. `unpaid` problem closes prematurely | **Fixed** | [adapter.go:102](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/billingstripe/adapter.go:102) separates settlement (`Live`) from entitlement (`State`). Closure checks `Live`. `TestLiveOf` and `TestCloseRefusedWhileUnpaid` cover unpaid losing limits while closure remains refused. | |
| +| 7. Provider-request budget understated | **Fixed** | [plan:93](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/docs/superpowers/plans/2026-10-25-plans-6a-checkout.md:93) now documents two subscription reads, a conditional third, discovery lists and readiness’s price/product reads. This reconciles the budget rather than reducing requests; no regression test was added. | |
| + |
| +The new findings are: |
| + |
| +1. **Important — discovery can permanently discard a failed paid-subscription sync.** |
| + |
| + [billingpass.go:123](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingpass.go:123) logs a candidate’s sync failure and continues processing other subscriptions for the same customer. |
| + |
| + Concrete scenario: a recently bound customer has an older `incomplete_expired` subscription A and a successful purchase B; all purchase webhooks were missed. Discovery lists B first, but reading B times out. It then successfully syncs A, recording A as ended. Subsequent discovery excludes the customer because its subscription is no longer empty, and the live pass excludes it because its state is ended. B keeps charging while the account remains free, with no retry or billing problem. |
| + |
| + Preserve outstanding discovery work independently of the selected subscription until every candidate has been resolved. Add a regression with two candidates and a transient failure, followed by another hourly pass. |
| + |
| +2. **Important — adopting a pending replacement preserves the canceled subscription’s paid limits.** |
| + |
| + [billingsync.go:204](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingsync.go:204) updates the previous subscription’s state in memory without applying its ended entitlement. The pending branch at [billingsync.go:98](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingsync.go:98) then adopts the replacement without changing the plan. |
| + |
| + Concrete scenario: A is stored as paid, but has been canceled at the provider. B’s `incomplete` event arrives before A’s cancellation. The new reread sees A canceled and permits adoption of B. The billing row now names pending B, while the plan retains A’s paid plan and packs. A’s later cancellation is ignored as an old subscription. Repeated syncs of pending B preserve those limits and never start A’s lapse. |
| + |
| + Apply the old subscription’s ended entitlement when replacing it with a subscription that grants no recognized entitlement. Keep that transition and adoption atomic. Extend the replacement regression to pending B and verify the default plan, lapse mark and late cancellation behavior. |
| + |
| +3. **Important — closing a missing-subscription problem can overwrite a newer successful sync.** |
| + |
| + [apibilling.go:130](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/apibilling.go:130) reads the provider before acquiring the billing account lock. [billingsync.go:274](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingsync.go:274) acquires that lock later, checks only the subscription ID, and synthesizes an ended subscription without rereading the provider. |
| + |
| + Concrete interleaving: closure receives a temporary not-found response; a concurrent sync subsequently reads the same subscription successfully as active and commits paid state; closure then acquires the lock and overwrites that newer result with ended/free. It also closes the problem. The account is now excluded from both hourly recovery lists despite its active purchase. |
| + |
| + Make the decisive provider read under the same billing lock as the resulting transition. Recheck that the problem remains open there. Add a coordinated close-versus-sync regression. |
| + |
| +The shared transition otherwise preserves the intended behavior: the transactional source guard protects operator/sponsored rows; unchanged billing assignments preserve revisions and throttle; lapse marking and grace resets roll back with the plan write. I found no path taking the billing and lapse locks in reverse order. |
| + |
| +`TestOnlyApplyAccountPlanSetsAccountPlans` still holds **in substance at this HEAD**: production billing writes reach `SaveBillingSync` only through `applyBillingPlan` and the shared transition. Its string-based check does not itself enforce that new route. Also, `TestBillingSyncGracePassAndOperatorDoNotDeadlock` exercises two billing paths and grace, but never an operator write. |
| + |
| +The remaining Review Focus checks retain their implementations and regression coverage: unchanged sync, protected ownership, stale events for the same subscription, pack reductions at renewal, and startup readiness returning 503 before recovery. Discovery’s request bound is per customer—one list followed by at most ten syncs—not a fixed budget for the whole pass. The seven-day window and first-ten limit restrict recovery coverage. |
| + |
| +**Census verdicts:** approve the following units for their recorded read/authority dispositions. These approvals do not waive the functional findings above. |
| + |
| +| Card unit | Verdict and evidence | |
| +|---|---| |
| +| [serve, main.go:304](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/cmd/console/main.go:304) | **Approve.** Explicit operator configuration, console-store bookkeeping and worker wiring; existing data-path reads preserved. | |
| +| [Store.SetAccountPlan:109](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/accountplans.go:109) | **Approve.** Same parameterized upsert through shared SQL and arguments. | |
| +| [Store.MarkLapse:333](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/accountplans.go:333) | **Approve.** Existing statement moved to `markLapseSQL`; account binding unchanged. | |
| +| [Store.DeleteCapState:95](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/plangrace_store.go:95) | **Approve.** Existing statement moved to `deleteCapStateSQL`; account/cap binding unchanged. | |
| +| [NewServer:1396](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/server.go:1396) | **Approve.** Billing configuration and route wiring add no privileged filesystem reader. | |
| +| [Store.migrate:138](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/store.go:138) | **Approve.** Adds fixed console-owned billing schema after the lapse migration. | |
| + |
| +All twenty handwritten overlay units: |
| + |
| +| Unit | Verdict and evidence | |
| +|---|---| |
| +| [Client.do:175](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/billingstripe/client.go:175) | **Approve.** Bounded API response; redirects refused; no new filesystem input. | |
| +| [billingSetPlan:220](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/accountplans.go:220) | **Approve.** Existing plan upsert, fixed billing source, within the guarded transaction. | |
| +| [setBillingPlanTx:175](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/accountplans.go:175) | **Approve.** Live-account check, ownership guard and unchanged-write suppression share the transaction. | |
| +| [Server.handleAPIBillingProblems:72](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/apibilling.go:72) | **Approve.** Operator gate precedes listing; `URL.Query` is not a filesystem read. | |
| +| [Store.BillingProblem:296](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:296) | **Approve.** Parameterized lookup in the console-owned table. | |
| +| [Store.BillingProblems:274](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:274) | **Approve.** Fixed query variants over that table. | |
| +| [Store.CloseBillingProblem:309](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:309) | **Approve.** Parameterized update restricted to an open problem. | |
| +| [Store.DiscoverableBillingAccounts:377](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:377) | **Approve.** Fixed account/billing query with bound paging and time parameters. | |
| +| [Store.LiveBillingAccounts:219](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:219) | **Approve.** Existing console-owned query and account scope. | |
| +| [Store.NotePriceBook:34](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:34) | **Approve.** Parameterized version/digest bookkeeping. | |
| +| [Store.OpenBillingProblem:261](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:261) | **Approve.** Parameterized, deduplicated insertion. | |
| +| [Store.SaveBillingSync:331](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:331) | **Approve.** Console-owned transaction; fixed lapse/grace SQL; production caller holds the lapse lock. | |
| +| [Store.SetBillingCustomer:161](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:161) | **Approve.** Adds bound time without weakening customer uniqueness or reassignment refusal. | |
| +| [Store.billingAccountWhere:136](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:136) | **Approve.** Callers supply fixed predicates and bound values, including subscription lookup. | |
| +| [Store.migrateBilling:17](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:17) | **Approve.** Fixed console-owned schema. | |
| +| [Store.migrateBillingAccounts:64](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:64) | **Approve.** Adds `bound_at`; fixed tables and indexes remain console-owned. | |
| +| [putBillingState:195](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:195) | **Approve.** Parameterized upsert usable inside the transaction; customer binding untouched. | |
| +| [type sqlExecer:191](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:191) | **Approve.** Interface declaration, not an executed read. | |
| +| [Server.handleBillingWebhook:29](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingwebhook.go:29) | **Approve.** Bounded body, signature verification and provider reread; no tenant-selected filesystem path. | |
| +| [LoadPriceBook:59](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/plans/pricebook.go:59) | **Approve.** Operator-configured input, unchanged from round 1. | |
| + |
| +Removed census readers: |
| + |
| +- **`Store.SetBillingPlan`: approve removal.** Replaced by the transaction-aware path above. |
| +- **`Store.PutBillingState`: approve removal as a direct reader.** The method still exists at [billingstore.go:186](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:186), forwarding to separately inventoried `putBillingState`. |
| + |
| +Each of the eight envelope re-pins is **approved**: `.`, `cmd/console`, `cmd/pricebook-export`, `internal/billing`, `internal/billing/billingtest`, `internal/billingstripe`, `internal/console`, and `internal/plans`. The changes preserve the recorded boundaries: operator-selected local files, authenticated provider input, console-owned SQL and the existing limits-publication path. |
| + |
| +Direct recomputation matched all **26 unit source digests**, legacy fingerprints, **eight package envelopes**, and **three record-write digests**. Both cumulative seals match: |
| + |
| +- `plans-6a-units`: `d206d109846b6656385256cc44a75a9a866d8b5d0b4cad742140107880a54d38` |
| +- `plans-6-checkout`: `a7d4bb220e3274151c522bd913eacadc6da1645f35b42b6d33116d050609c0ff` |
| + |
| +These hash checks do not substitute for executing the full census scanner. No verdict was posted to #280; the handwritten classifications still need the owner’s decision record. |
| + |
| +--- |
| + |
| +**FIRST PROMPT:** |
| +“Follow the brief docs/superpowers/specs/CODEX-REVIEW-BRIEF-PLANS-6A-CODE-R2.md exactly, at the branch's current HEAD.” |
| + |
| +**WHAT:** |
| +Review the Plans 6a fixes, Plan 4d integration and census. |
| + |
| +**STATUS:** |
| +Review complete: changes required. Three Important findings. Census hashes match; Go tests blocked by filesystem permissions. |
| + |
| +**NEEDED:** |
| +Owner decision record for the handwritten census classifications. |
| + |
| +**RECOMMENDED:** |
| +Fix the three recovery cases, add focused regressions, then rerun tests and review. |
| + |
| +**SESSION:** |
| +Safe to close. HEAD, index and working tree unchanged; no files created or processes left running. |
| \ No newline at end of file |
diff --git a/internal/billing/billingtest/fake.go b/internal/billing/billingtest/fake.go| index c161f311e..54e39b55f 100644 |
| --- a/internal/billing/billingtest/fake.go |
| +++ b/internal/billing/billingtest/fake.go |
| @@ -27,6 +27,10 @@ type Fake struct { |
| SubErr map[string]error |
| // CustomerCalls counts CustomerSubscriptions calls. |
| CustomerCalls int |
| + // BeforeSubscription, when set, runs at the start of every |
| + // Subscription call, outside the Fake's lock (so it may call back into |
| + // the code under test); a non-nil error is returned as the read's. |
| + BeforeSubscription func(id string) error |
| } |
| // New is an empty Fake. |
| @@ -64,6 +68,17 @@ func (f *Fake) ParseEvent(raw []byte, header http.Header, _ time.Time) (billing. |
| // Subscription returns a copy of Subs[id], or billing.ErrNotFound. |
| func (f *Fake) Subscription(_ context.Context, id string) (*billing.Subscription, error) { |
| + f.mu.Lock() |
| + hook := f.BeforeSubscription |
| + f.mu.Unlock() |
| + if hook != nil { |
| + if err := hook(id); err != nil { |
| + f.mu.Lock() |
| + f.Calls++ |
| + f.mu.Unlock() |
| + return nil, err |
| + } |
| + } |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| f.Calls++ |
diff --git a/internal/console/apibilling.go b/internal/console/apibilling.go| index 47b6fb9dd..95a1082ca 100644 |
| --- a/internal/console/apibilling.go |
| +++ b/internal/console/apibilling.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "errors" |
| "log" |
| "net/http" |
| @@ -126,18 +127,13 @@ func (s *Server) handleAPIBillingProblemClose(w http.ResponseWriter, r *http.Req |
| return |
| } |
| now := time.Now() |
| + // A quick refusal outside the lock while the subscription is live. The |
| + // deciding read is made again under the account's billing lock, with |
| + // the problem re-checked there (Astra round 2 finding 3). |
| if p.Subscription != "" { |
| sub, err := s.billing.cfg.Provider.Subscription(r.Context(), p.Subscription) |
| switch { |
| case errors.Is(err, billing.ErrNotFound): |
| - if p.Reason == problemSubscriptionMissing { |
| - // The resolution: still unknown to the provider, so it ends here. |
| - if err := s.endMissingSubscription(r.Context(), p.AccountID, p.Subscription, now); err != nil { |
| - log.Printf("console: api billing close %d: ending the missing subscription: %v", id, err) |
| - jsonError(w, http.StatusInternalServerError, billingCopyFailed) |
| - return |
| - } |
| - } |
| case err != nil: |
| log.Printf("console: api billing close %d: reading subscription: %v", id, err) |
| jsonError(w, http.StatusServiceUnavailable, billingCopyProviderDown) |
| @@ -147,13 +143,8 @@ func (s *Server) handleAPIBillingProblemClose(w http.ResponseWriter, r *http.Req |
| return |
| } |
| } |
| - if err := s.store.CloseBillingProblem(id, addr, note, now); err != nil { |
| - if errors.Is(err, errBillingProblemClosed) { |
| - jsonError(w, http.StatusConflict, billingCopyClosed) |
| - return |
| - } |
| - log.Printf("console: api billing close %d: %v", id, err) |
| - jsonError(w, http.StatusInternalServerError, billingCopyFailed) |
| + if status, msg := s.closeBillingProblemLocked(r.Context(), p, addr, note, now); status != http.StatusOK { |
| + jsonError(w, status, msg) |
| return |
| } |
| log.Printf("console: billing problem %d closed by %s", id, addr) |
| @@ -165,3 +156,60 @@ func (s *Server) handleAPIBillingProblemClose(w http.ResponseWriter, r *http.Req |
| } |
| writeJSON(w, http.StatusOK, s.billingProblemReplyFor(*closed)) |
| } |
| + |
| +// closeBillingProblemLocked closes problem p under its account's billing |
| +// lock, the lock every sync of that account holds: it re-reads the problem |
| +// (a sync may have resolved it), makes the deciding provider read there, |
| +// refuses while the subscription is live, and for a missing subscription |
| +// the provider still has no record of, ends it in the same critical |
| +// section. It answers the HTTP status and, for a refusal, the door copy. |
| +func (s *Server) closeBillingProblemLocked(ctx context.Context, p *billingProblem, addr, note string, now time.Time) (int, string) { |
| + var acct *Account |
| + if p.AccountID != 0 { |
| + a, err := s.store.AccountByID(p.AccountID) |
| + if err != nil { |
| + log.Printf("console: api billing close %d: account: %v", p.ID, err) |
| + return http.StatusInternalServerError, billingCopyFailed |
| + } |
| + acct = a |
| + } |
| + if acct != nil { |
| + defer s.billing.locks.lock(acct.Sqid)() |
| + } |
| + 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.Subscription != "" { |
| + sub, err := s.billing.cfg.Provider.Subscription(ctx, cur.Subscription) |
| + switch { |
| + case errors.Is(err, billing.ErrNotFound): |
| + if cur.Reason == problemSubscriptionMissing && acct != nil { |
| + if err := s.endMissingSubscriptionLocked(ctx, acct, cur.Subscription, now); err != nil { |
| + log.Printf("console: api billing close %d: ending the missing subscription: %v", p.ID, err) |
| + return http.StatusInternalServerError, billingCopyFailed |
| + } |
| + } |
| + 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, "" |
| +} |
diff --git a/internal/console/billinglapse_test.go b/internal/console/billinglapse_test.go| index 3e5421e5c..db45d8703 100644 |
| --- a/internal/console/billinglapse_test.go |
| +++ b/internal/console/billinglapse_test.go |
| @@ -107,15 +107,16 @@ func TestBillingRepaymentTurnsThingsBackOn(t *testing.T) { |
| } |
| // The billing sync (account lock, then the lapse lock, then its store |
| -// transaction), the grace pass (lapse lock) and the operator door (lapse |
| -// lock) on one account never wait on each other in a cycle. |
| +// transaction), the billing pass, the grace pass (lapse lock) and the |
| +// operator door (lapse lock, through applyAccountPlan) on one account |
| +// never wait on each other in a cycle. |
| func TestBillingSyncGracePassAndOperatorDoNotDeadlock(t *testing.T) { |
| bf, _ := billingLapseFixture(t) |
| done := make(chan struct{}) |
| go func() { |
| defer close(done) |
| var wg sync.WaitGroup |
| - for g := 0; g < 3; g++ { |
| + for g := 0; g < 4; g++ { |
| wg.Add(1) |
| go func(g int) { |
| defer wg.Done() |
| @@ -128,6 +129,15 @@ func TestBillingSyncGracePassAndOperatorDoNotDeadlock(t *testing.T) { |
| bf.srv.planGracePass(context.Background(), now) |
| case 2: |
| bf.srv.billingSyncPass(context.Background(), now) |
| + case 3: |
| + // The operator door: the lapse lock, without the billing lock. |
| + plan := "personal" |
| + if i%2 == 1 { |
| + plan = "free" |
| + } |
| + if err := bf.srv.applyAccountPlan(context.Background(), bf.acct, plan, nil, PlanSourceOperator, nil, "race", "ops@example.com", now); err != nil { |
| + t.Errorf("applyAccountPlan: %v", err) |
| + } |
| } |
| } |
| }(g) |
diff --git a/internal/console/billingpass.go b/internal/console/billingpass.go| index 35ca3d5af..710dbb6cd 100644 |
| --- a/internal/console/billingpass.go |
| +++ b/internal/console/billingpass.go |
| @@ -101,8 +101,9 @@ func (s *Server) billingSyncPass(ctx context.Context, now time.Time) { |
| } |
| // billingDiscoveryPass asks the provider for the subscriptions of each |
| -// customer bound within billingDiscoveryWindow that has none recorded, and |
| -// syncs each one (Astra finding 3): a first purchase whose every event was |
| +// customer bound within billingDiscoveryWindow that has none recorded, or |
| +// whose last discovery left a candidate unsynced, and syncs each one |
| +// (Astra finding 3): a first purchase whose every event was |
| // missed, because billing was not ready while the provider retried, is |
| // still found. One list request per such customer per pass. |
| func (s *Server) billingDiscoveryPass(ctx context.Context, now time.Time) { |
| @@ -120,11 +121,19 @@ func (s *Server) billingDiscoveryPass(ctx context.Context, now time.Time) { |
| log.Printf("console: billing discovery: account %d: %v", b.AccountID, err) |
| continue |
| } |
| + // Every candidate is synced; one failure keeps the customer's |
| + // discovery outstanding for the next pass, whatever the others |
| + // recorded (Astra round 2 finding 1). |
| + failed := false |
| for _, id := range ids { |
| if err := s.syncSubscription(ctx, id, now); err != nil { |
| + failed = true |
| log.Printf("console: billing discovery: account %d: %v", b.AccountID, err) |
| } |
| } |
| + if err := s.store.SetBillingDiscoveryRetry(b.AccountID, failed); err != nil { |
| + log.Printf("console: billing discovery: account %d: %v", b.AccountID, err) |
| + } |
| } |
| if len(page) < billingSyncBatch { |
| return |
diff --git a/internal/console/billingrecovery_test.go b/internal/console/billingrecovery_test.go| index 8489b3256..6698b366b 100644 |
| --- a/internal/console/billingrecovery_test.go |
| +++ b/internal/console/billingrecovery_test.go |
| @@ -3,7 +3,9 @@ package console |
| import ( |
| "context" |
| "errors" |
| + "fmt" |
| "net/http" |
| + "sync" |
| "testing" |
| "time" |
| @@ -170,3 +172,135 @@ func TestMissingSubscriptionOpensAProblemThenCloses(t *testing.T) { |
| t.Fatalf("problems = %+v", open) |
| } |
| } |
| + |
| +// Astra round 2, finding 2: B is pending when the stored A is found to |
| +// have ended. Adopting B must not keep A's paid limits: A's end applies |
| +// (the default plan and a lapse mark) in the same commit as the adoption, |
| +// and A's late cancellation event changes nothing afterwards. |
| +func TestPendingReplacementAppliesTheOldEnd(t *testing.T) { |
| + bf, _ := billingLapseFixture(t) |
| + // More running things than free covers, so the lapse outlives the |
| + // sync's own re-converge. |
| + for i := 0; i < 2; i++ { |
| + lapseApp_(t, bf.consoleFixture, bf.acct, fmt.Sprintf("extra%d", i), at(-80+i)) |
| + } |
| + bf.put(bf.personalSub("sub_1", "canceled", nil)) |
| + bf.put(bf.personalSub("sub_2", "incomplete", nil)) |
| + if err := bf.srv.syncSubscription(context.Background(), "sub_2", planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + b, _ := bf.st.BillingAccount(bf.acct.ID) |
| + row, _ := bf.st.AccountPlan(bf.acct.ID) |
| + if b.Subscription != "sub_2" || b.State != billing.StatePending { |
| + t.Fatalf("billing row = %+v", b) |
| + } |
| + if row.Plan != "free" || len(row.Packs) != 0 || !row.LapseSince.Equal(planNow) { |
| + t.Fatalf("pending replacement kept the old paid limits: plan %q packs %v lapse %v", row.Plan, row.Packs, row.LapseSince) |
| + } |
| + // A's cancellation arrives late: an old subscription ending changes nothing. |
| + if err := bf.srv.syncSubscription(context.Background(), "sub_1", planNow.Add(time.Minute)); err != nil { |
| + t.Fatal(err) |
| + } |
| + after, _ := bf.st.AccountPlan(bf.acct.ID) |
| + b2, _ := bf.st.BillingAccount(bf.acct.ID) |
| + if after.Revision != row.Revision || after.Plan != "free" || !after.LapseSince.Equal(planNow) || b2.Subscription != "sub_2" { |
| + t.Fatalf("late cancellation changed state: plan %+v billing %+v", after, b2) |
| + } |
| + // B is paid later: Personal again, and the lapse ends. |
| + bf.put(bf.personalSub("sub_2", "active", nil)) |
| + if err := bf.srv.syncSubscription(context.Background(), "sub_2", planNow.Add(time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if p := bf.plan(t); p != "personal" { |
| + t.Fatalf("paid replacement: plan %q", p) |
| + } |
| +} |
| + |
| +// Astra round 2, finding 1: one discovery candidate's failure keeps the |
| +// customer's discovery outstanding, even when another candidate syncs and |
| +// records a subscription; the next pass recovers the failed one. |
| +func TestDiscoveryKeepsAFailedCandidate(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.ready(t) |
| + bf.put(bf.personalSub("sub_a", "incomplete_expired", nil)) |
| + bf.put(bf.personalSub("sub_b", "active", nil)) |
| + bf.fake.SubErr = map[string]error{"sub_b": errors.New("timeout")} |
| + bf.srv.billingSyncPass(context.Background(), billingNow.Add(time.Hour)) |
| + if p := bf.plan(t); p == "personal" { |
| + t.Fatal("the failed candidate synced") |
| + } |
| + bf.fake.SubErr = nil |
| + bf.srv.billingSyncPass(context.Background(), billingNow.Add(2*time.Hour)) |
| + if p := bf.plan(t); p != "personal" { |
| + t.Fatalf("second pass did not recover the failed candidate: plan %q", p) |
| + } |
| + b, _ := bf.st.BillingAccount(bf.acct.ID) |
| + if b.Subscription != "sub_b" || b.State != billing.StatePaid { |
| + t.Fatalf("billing row = %+v", b) |
| + } |
| + // Every candidate resolved: the customer is no longer asked about. |
| + bf.fake.CustomerCalls = 0 |
| + bf.srv.billingSyncPass(context.Background(), billingNow.Add(3*time.Hour)) |
| + if bf.fake.CustomerCalls != 0 { |
| + t.Fatalf("resolved customer still in discovery: %d calls", bf.fake.CustomerCalls) |
| + } |
| +} |
| + |
| +// Astra round 2, finding 3: closing a missing-subscription problem races a |
| +// sync. The close's first read says not found; before it acts, a sync reads |
| +// the subscription as active and commits. The close must neither end the |
| +// account nor close the problem as if it were still missing. |
| +func TestCloseMissingRacingASyncKeepsTheSync(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.ready(t) |
| + bf.put(bf.personalSub("sub_1", "active", nil)) |
| + if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + bf.fake.Lock() |
| + delete(bf.fake.Subs, "sub_1") |
| + bf.fake.Unlock() |
| + if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + open, _ := bf.st.BillingProblems(false) |
| + if len(open) != 1 || open[0].Reason != problemSubscriptionMissing { |
| + t.Fatalf("problems = %+v", open) |
| + } |
| + bf.put(bf.personalSub("sub_1", "active", map[string]int64{"apps": 1})) |
| + var once sync.Once |
| + bf.fake.Lock() |
| + bf.fake.BeforeSubscription = func(id string) error { |
| + var fire bool |
| + once.Do(func() { fire = true }) |
| + if !fire { |
| + return nil |
| + } |
| + // The close's first read: a temporary not-found, and meanwhile a |
| + // sync reads the subscription as active and commits. |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + _ = bf.srv.syncSubscription(context.Background(), "sub_1", billingNow.Add(time.Minute)) |
| + }() |
| + select { |
| + case <-done: |
| + case <-time.After(2 * time.Second): |
| + } |
| + return billing.ErrNotFound |
| + } |
| + bf.fake.Unlock() |
| + op := planOperatorToken(t, bf.consoleFixture, "ops@keymail.dev", "code-billing-race") |
| + status, out := postJSON(t, billingCloseURL(bf.consoleFixture, open[0].ID), map[string]any{"note": "gone"}, op) |
| + if status == http.StatusOK { |
| + t.Fatalf("close succeeded over a newer sync: %v", out) |
| + } |
| + row, _ := bf.st.AccountPlan(bf.acct.ID) |
| + b, _ := bf.st.BillingAccount(bf.acct.ID) |
| + if row.Plan != "personal" || row.Packs["apps"] != 1 || b.State != billing.StatePaid { |
| + t.Fatalf("close overwrote the sync: plan %+v billing %+v", row, b) |
| + } |
| + if p, _ := bf.st.BillingProblem(open[0].ID); p.ClosedBy == "ops@keymail.dev" { |
| + t.Fatalf("problem closed by the operator as missing: %+v", p) |
| + } |
| +} |
diff --git a/internal/console/billingstore.go b/internal/console/billingstore.go| index 0bb4a897c..146fb771a 100644 |
| --- a/internal/console/billingstore.go |
| +++ b/internal/console/billingstore.go |
| @@ -75,7 +75,8 @@ func (s *Store) migrateBillingAccounts() error { |
| paid_packs TEXT NOT NULL DEFAULT '{}', |
| paid_period_end INTEGER NOT NULL DEFAULT 0, |
| synced_at INTEGER NOT NULL DEFAULT 0, |
| - bound_at INTEGER NOT NULL DEFAULT 0 |
| + bound_at INTEGER NOT NULL DEFAULT 0, |
| + discover_retry INTEGER NOT NULL DEFAULT 0 |
| ); |
| CREATE UNIQUE INDEX IF NOT EXISTS billing_accounts_customer ON billing_accounts(customer) WHERE customer != ''; |
| CREATE UNIQUE INDEX IF NOT EXISTS billing_accounts_subscription ON billing_accounts(subscription) WHERE subscription != ''; |
| @@ -371,12 +372,14 @@ func (s *Store) BillingAccountBySubscription(id string) (*billingAccount, error) |
| } |
| // DiscoverableBillingAccounts pages, in account order after afterAccountID, |
| -// the live accounts with a bound customer and no subscription recorded, |
| -// bound at or after boundAfter: the pass asks the provider about these, so |
| -// a first purchase whose every event was missed is still found. |
| +// the live accounts with a bound customer and either no subscription |
| +// recorded and bound at or after boundAfter, or outstanding discovery work |
| +// (SetBillingDiscoveryRetry): the pass asks the provider about these, so a |
| +// first purchase whose every event was missed is still found. |
| func (s *Store) DiscoverableBillingAccounts(boundAfter time.Time, afterAccountID int64, limit int) ([]billingAccount, error) { |
| rows, err := s.db.Query(`SELECT `+billingAccountColumns+` FROM billing_accounts b JOIN accounts a ON a.id = b.account_id |
| - WHERE a.deleted_at = 0 AND b.account_id > ? AND b.customer != '' AND b.subscription = '' AND b.bound_at >= ? |
| + WHERE a.deleted_at = 0 AND b.account_id > ? AND b.customer != '' |
| + AND ((b.subscription = '' AND b.bound_at >= ?) OR b.discover_retry = 1) |
| ORDER BY b.account_id LIMIT ?`, afterAccountID, boundAfter.Unix(), limit) |
| if err != nil { |
| return nil, err |
| @@ -392,3 +395,27 @@ func (s *Store) DiscoverableBillingAccounts(boundAfter time.Time, afterAccountID |
| } |
| return out, rows.Err() |
| } |
| + |
| +// ResolveBillingProblem closes the open problem for (account, subscription, |
| +// reason), if there is one, as resolved by billing with note: what a sync |
| +// does when the provider has a subscription a missing-subscription problem |
| +// said it lacked. |
| +func (s *Store) ResolveBillingProblem(accountID int64, subscription, reason, note string, now time.Time) error { |
| + _, err := s.db.Exec(`UPDATE billing_problems SET closed_at = ?, closed_by = ?, note = ? |
| + WHERE account_id = ? AND subscription = ? AND reason = ? AND closed_at = 0`, |
| + now.Unix(), planBilling, note, accountID, subscription, reason) |
| + return err |
| +} |
| + |
| +// SetBillingDiscoveryRetry records whether the account's discovery has |
| +// outstanding work: a candidate subscription whose sync failed (Astra |
| +// round 2 finding 1). While it is set the account stays on the discovery |
| +// list, whatever subscription it records and however long ago it was bound. |
| +func (s *Store) SetBillingDiscoveryRetry(accountID int64, retry bool) error { |
| + v := 0 |
| + if retry { |
| + v = 1 |
| + } |
| + _, err := s.db.Exec(`UPDATE billing_accounts SET discover_retry = ? WHERE account_id = ?`, v, accountID) |
| + return err |
| +} |
diff --git a/internal/console/billingsync.go b/internal/console/billingsync.go| index 782c01ea4..bdd7e30c8 100644 |
| --- a/internal/console/billingsync.go |
| +++ b/internal/console/billingsync.go |
| @@ -93,13 +93,26 @@ func decideBilling(in billingInput) billingDecision { |
| next.PaidPacks, next.PaidPeriodEnd, next.Book = map[string]int{}, time.Time{}, "" |
| } |
| d := billingDecision{Save: true, Next: next} |
| + // Adopting a replacement for a subscription that has ended (a fresh |
| + // read says so; Astra round 2 finding 2): when the replacement grants |
| + // no recognised entitlement yet, the old one's end applies now, in the |
| + // same commit as the adoption, or its paid limits would outlive it. |
| + oldEnded := func() *planChange { |
| + if !other { |
| + return nil |
| + } |
| + return &planChange{Plan: in.DefaultPlan, Reason: fmt.Sprintf("subscription %s ended (%s); %s is %s", |
| + prev.Subscription, prev.ProviderStatus, sub.ID, sub.ProviderStatus)} |
| + } |
| switch sub.State { |
| case billing.StatePending: |
| + d.Plan = oldEnded() |
| return d |
| case billing.StatePaid: |
| if in.Unrecognised != nil { |
| d.Problem = &problemNote{problemUnrecognised, in.Unrecognised.Error()} |
| + d.Plan = oldEnded() |
| return d |
| } |
| d.Next.Book = in.Purchase.Book |
| @@ -184,6 +197,13 @@ func (s *Server) syncSubscription(ctx context.Context, subscriptionID string, no |
| if err != nil { |
| return fmt.Errorf("billing: reading subscription %s: %w", subscriptionID, err) |
| } |
| + // The provider has the subscription: a missing-subscription problem |
| + // for it is resolved (Astra round 2 finding 3), so a close racing this |
| + // sync finds it closed rather than ending a live purchase. |
| + if err := s.store.ResolveBillingProblem(acct.ID, sub.ID, problemSubscriptionMissing, |
| + "the provider has the subscription again", now); err != nil { |
| + return err |
| + } |
| prev, err := s.store.BillingAccount(acct.ID) |
| if err != nil { |
| return err |
| @@ -261,19 +281,16 @@ func (s *Server) subscriptionMissing(subscriptionID string, now time.Time) error |
| "the provider has no such subscription; paid limits are kept until this problem is closed", now) |
| } |
| -// endMissingSubscription is the resolution of a subscription_missing |
| -// problem: the provider still has no such subscription, so the console |
| -// treats it as ended and drops the account to the default plan, through |
| -// the same decision and commit as any ended subscription. A subscription |
| -// the account has since replaced is left alone. |
| -func (s *Server) endMissingSubscription(ctx context.Context, accountID int64, subscriptionID string, now time.Time) error { |
| - acct, err := s.store.AccountByID(accountID) |
| - if err != nil || acct == nil { |
| - return err |
| - } |
| - defer s.billing.locks.lock(acct.Sqid)() |
| +// endMissingSubscriptionLocked is the resolution of a subscription_missing |
| +// problem: the provider still has no such subscription (a read the caller |
| +// made under this account's billing lock), so the console treats it as |
| +// ended and drops the account to the default plan, through the same |
| +// decision and commit as any ended subscription. A subscription the |
| +// account has since replaced, or that a sync has since found ended, is |
| +// left alone. The caller holds the account's billing lock. |
| +func (s *Server) endMissingSubscriptionLocked(ctx context.Context, acct *Account, subscriptionID string, now time.Time) error { |
| prev, err := s.store.BillingAccount(acct.ID) |
| - if err != nil || prev == nil || prev.Subscription != subscriptionID { |
| + if err != nil || prev == nil || prev.Subscription != subscriptionID || !liveState(prev.State) { |
| return err |
| } |
| ended := &billing.Subscription{ID: subscriptionID, Customer: prev.Customer, Account: acct.Sqid, |
diff --git a/internal/plans/testdata/example-catalog.json b/internal/plans/testdata/example-catalog.json| index e89088929..c7a888710 100644 |
| --- a/internal/plans/testdata/example-catalog.json |
| +++ b/internal/plans/testdata/example-catalog.json |
| @@ -10,7 +10,7 @@ |
| "sidecars_per_app": 1, |
| "idle_seconds": 90, |
| "memory_tier": "small", |
| - "awake_hours_month": 100, |
| + "awake_hours_month": 90, |
| "disk_bytes": 1073741824, |
| "storage_bytes": 1073741824, |
| "email_per_day": 50, |
diff --git a/internal/plans/testdata/example-public-pricebook.json b/internal/plans/testdata/example-public-pricebook.json| index 82588ba79..2c806dab3 100644 |
| --- a/internal/plans/testdata/example-public-pricebook.json |
| +++ b/internal/plans/testdata/example-public-pricebook.json |
| @@ -4,7 +4,7 @@ |
| "price_book_id": "example-v1@3be7730d025a", |
| "status": "draft", |
| "catalog_version": "2026-10-20-v1", |
| - "catalog_id": "2026-10-20-v1@4098eb02ee58", |
| + "catalog_id": "2026-10-20-v1@57355d1ce09d", |
| "default_currency": "usd", |
| "currencies": [ |
| { |
| @@ -66,7 +66,7 @@ |
| "sidecars_per_app": 1, |
| "idle_seconds": 90, |
| "memory_tier": "small", |
| - "awake_hours_month": 100, |
| + "awake_hours_month": 90, |
| "disk_bytes": 1073741824, |
| "storage_bytes": 1073741824, |
| "email_per_day": 50, |