carlos / platform Public

plans 6a: Astra round 3. The discovery marker is written before any candidate syncs (skip the customer if it cannot be), cleared only when every candidate succeeds; 24 failed passes in a row open a discovery_failing problem that a successful pass resolves; request budget line

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev a8961a7f118e7b7546eed8f1ae955c29da916b9b parent 0a9b202
6 files changed, +258 −29
  • docs/site/plans.md +1 −0
  • docs/superpowers/plans/2026-10-25-plans-6a-checkout.md +1 −0
  • docs/superpowers/specs/CODEX-FINDINGS-PLANS-6A-CODE-R3.md +66 −0
  • internal/console/billingpass.go +56 −18
  • internal/console/billingrecovery_test.go +110 −0
  • internal/console/billingstore.go +24 −11
diff --git a/docs/site/plans.md b/docs/site/plans.md
index e4fcda0dc..ff44de685 100644
--- a/docs/site/plans.md
+++ b/docs/site/plans.md
@@ -174,4 +174,5 @@ The console can't close a problem while Stripe can still charge the subscription
| `unknown_customer` | A subscription on a Stripe customer the console never created. | Find out where it came from, then refund and cancel. |
| `account_mismatch` | The subscription's metadata names a different account from its customer's. | Check both accounts, then refund and cancel. |
| `mode_mismatch` | A test-mode subscription reached a live console, or the other way round. | Check the webhook endpoints in each mode. |
+| `discovery_failing` | For a day, the console has failed to read the subscriptions of a customer whose purchase it may have missed. It keeps trying every hour, and closes the problem itself once a read succeeds. | Check the customer in Stripe. If a subscription is paid, find out why the console can't read it. |
| `subscription_missing` | Stripe has no record of the account's current subscription. The account keeps its paid limits while the problem is open. | Find out what happened to it. Closing the problem while Stripe still has no such subscription ends it in the console and moves the account to the default plan. |
diff --git a/docs/superpowers/plans/2026-10-25-plans-6a-checkout.md b/docs/superpowers/plans/2026-10-25-plans-6a-checkout.md
index dd8469ec9..7f710dc3d 100644
--- a/docs/superpowers/plans/2026-10-25-plans-6a-checkout.md
+++ b/docs/superpowers/plans/2026-10-25-plans-6a-checkout.md
@@ -94,6 +94,7 @@ Each has a recommendation. Decisions 1 to 8 and 15 are the old `DECISIONS-FOR-PA
- Stripe, as built (Astra finding 7 reconciled, 2026-10-25):
- per sync (an event, or one live subscription in the hourly pass): two `GET /v1/subscriptions/{id}`, one to learn the customer and one fresh read under the account's lock, plus a third only when another subscription of the account is recorded as live (finding 1);
- per hourly pass, additionally one `GET /v1/subscriptions?customer=…&status=all&limit=10` for each customer bound in the last seven days with no subscription recorded (finding 3), then a sync per subscription it names;
+ - so up to 31 requests per discovery customer per pass (one list and ten three-read syncs), and a customer whose discovery left a candidate unsynced is retried every pass beyond the seven-day cohort until every candidate succeeds (Astra rounds 2 and 3); after 24 failed passes in a row a `discovery_failing` problem tells an operator;
- per readiness check, until it passes: one account read, one read per price in the book (18 with the example book) and one per distinct product (6), so 25 for the example book: at most 1 + 2 × the price count.
- S3: nothing new. A plan change is the existing single limits-record PUT.
- **No product name** in code, tests, copy or example data. Examples use neutral names (shop, example.com).
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-PLANS-6A-CODE-R3.md b/docs/superpowers/specs/CODEX-FINDINGS-PLANS-6A-CODE-R3.md
new file mode 100644
index 000000000..cfc0bfc44
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-FINDINGS-PLANS-6A-CODE-R3.md
@@ -0,0 +1,66 @@
+**Verdict: changes required** at `0a9b202aab4027e2059d50b63ca6bebee138c933`.
+
+One Important finding remains in the new retry implementation. No Critical findings. Review was read-only, with no network calls.
+
+| Round 2 item | Disposition | Evidence |
+|---|---|---|
+| Failed discovery candidate lost | **Partly fixed** | [billingpass.go:127](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingpass.go:127) accumulates candidate failures; [billingstore.go:379](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:379) retains flagged accounts regardless of subscription or age. `TestDiscoveryKeepsAFailedCandidate` covers recovery on the next pass. Persisting the flag can still fail after discovery eligibility has been removed; see below. |
+| Pending replacement preserves canceled entitlement | **Fixed** | [billingsync.go:100](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingsync.go:100) selects the default plan when adopting pending B after ended A. [SaveBillingSync:332](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:332) commits adoption, plan and lapse together. `TestPendingReplacementAppliesTheOldEnd` checks the default plan, lapse, late cancellation of A and subsequent payment of B. B’s payment follows the shared transition. |
+| Missing-subscription close overwrites newer sync | **Fixed** | [apibilling.go:177](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/apibilling.go:177) acquires the billing lock before rechecking the problem and making the decisive provider read. `TestCloseMissingRacingASyncKeepsTheSync` covers the reported interleaving. The resulting transition retains billing → lapse → store lock order. |
+| Deadlock test omits operator writes | **Fixed** | [billinglapse_test.go:132](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billinglapse_test.go:132) now drives `applyAccountPlan` concurrently with sync, discovery and grace. No reverse lock acquisition found. |
+
+**Important — discovery commits can remove recovery eligibility before the retry marker is durable.**
+
+At [billingpass.go:134](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingpass.go:134), `SetBillingDiscoveryRetry` runs only after all candidate syncs. Its failure is logged without preserving another recovery path.
+
+Concrete scenario: all purchase webhooks were missed. Reading paid subscription B times out; syncing older ended subscription A succeeds and commits A. The console then restarts before saving `discover_retry`, or that update fails. The persisted row names ended A with `discover_retry=0`. It qualifies for neither live sync nor discovery, so B continues charging while the account stays free.
+
+An in-memory SQLite reproduction using the actual schema and selection predicates confirmed that both lists exclude this state after an injected retry-update failure. Setting the flag successfully restores discovery eligibility. This was a SQL reproduction, not an executed Go regression test.
+
+Persist outstanding discovery **before processing candidates**, and stop processing that customer if persistence fails. Clear the marker only after all candidates succeed. Add interruption and retry-write-failure regressions alongside the existing transient-provider-error test.
+
+Discovery otherwise advances its account cursor, so a failing customer does not loop within one pass or prevent later customers from being visited. A permanently failing candidate remains eligible indefinitely, with no backoff or expiry. The Stripe implementation costs at most one list plus ten three-read syncs: **31 requests per discovery customer per pass**, plus two if that customer also appears in live sync. There is no global pass budget; retained retries extend the documented seven-day discovery cohort.
+
+**Census verdicts**
+
+These approve the recorded read/authority boundaries, independently of the functional finding.
+
+| Changed unit or envelope | Verdict and evidence |
+|---|---|
+| [Store.DiscoverableBillingAccounts:379](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:379) | **Approve.** Fixed console-owned query; account, deletion and pagination constraints remain. |
+| [Store.migrateBillingAccounts:64](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:64) | **Approve.** Adds a fixed column to the console-owned schema; no tenant-selected resource or path. |
+| [Store.ResolveBillingProblem:403](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:403) | **Approve.** Parameterized update constrained by account, subscription, reason and open status. |
+| [Store.SetBillingDiscoveryRetry:414](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:414) | **Approve.** Parameterized update of one account’s bookkeeping flag. |
+| `internal/console` envelope | **Approve.** Reviewed changed discovery, decision, sync and closure functions and their transition/store calls. Operator gating, plan ownership guards and lock order remain intact; no new privileged filesystem input. |
+| `internal/billing/billingtest` envelope | **Approve.** The subscription hook runs outside the fake’s mutex; changes affect test support, not production authority. |
+
+The other eighteen units in the 22-unit overlay and the other six envelope hashes are unchanged from round 2.
+
+Direct recomputation matched all **28 declaration digests**, legacy fingerprints, **eight package envelopes**, and both cumulative seals:
+
+- `plans-6a-units`: `ff9bed97d0d1a1bdafba39ff84eb0180c24288c6069222e00bad80d14f8245fc`
+- `plans-6-checkout`: `d15a9e830b9165c0b246160c33962fa86fdb85a8ba1ac1be94363048f312bf41`
+
+The typed census scanner and targeted Go regressions could not run: Go’s build-directory creation was refused by the read-only sandbox. Test references above describe inspected coverage, not passing executions. No verdict was posted to #280.
+
+Neither named CI failure has an identified causal path from this billing branch. `internal/instancectl` is identical to main `96564cf3`. The branch’s own changes do not touch edge code, and the awake-throttle test and implementation are unchanged against that main. I could not independently reproduce either failure or establish that the edge failure is flaky.
+
+---
+
+**FIRST PROMPT:**
+“Follow the brief docs/superpowers/specs/CODEX-REVIEW-BRIEF-PLANS-6A-CODE-R3.md exactly, at the branch's current HEAD.”
+
+**WHAT:**
+Review the round 3 fixes and census.
+
+**STATUS:**
+Complete: changes required for discovery retry durability. Census hashes match; Go execution blocked.
+
+**NEEDED:**
+Nothing to complete this review.
+
+**RECOMMENDED:**
+Persist discovery work before candidate commits, add failure 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/console/billingpass.go b/internal/console/billingpass.go
index 710dbb6cd..195b7b799 100644
--- a/internal/console/billingpass.go
+++ b/internal/console/billingpass.go
@@ -2,6 +2,7 @@ package console
import (
"context"
+ "fmt"
"log"
"time"
)
@@ -19,6 +20,10 @@ const (
// than the provider's three days of webhook retries.
const billingDiscoveryWindow = 7 * 24 * time.Hour
+// billingDiscoveryProblemAfter is how many consecutive failed discovery
+// passes open a discovery_failing problem: a day of hourly passes.
+const billingDiscoveryProblemAfter = 24
+
// billingSyncBatch is the hourly pass's page size; a test shrinks it.
var billingSyncBatch = 200
@@ -116,27 +121,60 @@ func (s *Server) billingDiscoveryPass(ctx context.Context, now time.Time) {
}
for _, b := range page {
after = b.AccountID
- ids, err := s.billing.cfg.Provider.CustomerSubscriptions(ctx, b.Customer)
- if err != nil {
- 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)
- }
+ s.discoverCustomer(ctx, b, now)
}
if len(page) < billingSyncBatch {
return
}
}
}
+
+// discoverCustomer is one discovery pass over one customer. The marker
+// goes down first (Store.MarkBillingDiscovery), so no candidate commits
+// without it, and a customer whose marker cannot be written is skipped
+// this pass. Every candidate is then synced; one failure keeps the
+// discovery outstanding for the next pass, whatever the others recorded
+// (Astra rounds 2 and 3). Only a pass in which every candidate succeeds
+// clears the marker. After billingDiscoveryProblemAfter consecutive failed
+// passes a discovery_failing problem tells an operator, and retries carry
+// on hourly; a pass that succeeds resolves it.
+func (s *Server) discoverCustomer(ctx context.Context, b billingAccount, now time.Time) {
+ if err := s.store.MarkBillingDiscovery(b.AccountID); err != nil {
+ log.Printf("console: billing discovery: account %d: marking: %v; skipped this pass", b.AccountID, err)
+ return
+ }
+ failed := false
+ ids, err := s.billing.cfg.Provider.CustomerSubscriptions(ctx, b.Customer)
+ if err != nil {
+ failed = true
+ log.Printf("console: billing discovery: account %d: %v", b.AccountID, err)
+ }
+ 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)
+ }
+ }
+ n, err := s.store.EndBillingDiscovery(b.AccountID, failed)
+ if err != nil {
+ // The marker stays down: the next pass tries again.
+ log.Printf("console: billing discovery: account %d: %v", b.AccountID, err)
+ return
+ }
+ sqid := ""
+ if a, err := s.store.AccountByID(b.AccountID); err == nil && a != nil {
+ sqid = a.Sqid
+ }
+ if !failed {
+ if err := s.store.ResolveBillingProblem(b.AccountID, "", problemDiscoveryFailing, "discovery succeeded", now); err != nil {
+ log.Printf("console: billing discovery: account %d: %v", b.AccountID, err)
+ }
+ return
+ }
+ if n >= billingDiscoveryProblemAfter {
+ if err := s.openBillingProblem(b.AccountID, sqid, "", problemDiscoveryFailing,
+ fmt.Sprintf("discovery of customer %s's subscriptions has failed %d passes in a row; it is retried every hour", b.Customer, n), now); err != nil {
+ log.Printf("console: billing discovery: account %d: %v", b.AccountID, err)
+ }
+ }
+}
diff --git a/internal/console/billingrecovery_test.go b/internal/console/billingrecovery_test.go
index 6698b366b..df3511b60 100644
--- a/internal/console/billingrecovery_test.go
+++ b/internal/console/billingrecovery_test.go
@@ -304,3 +304,113 @@ func TestCloseMissingRacingASyncKeepsTheSync(t *testing.T) {
t.Fatalf("problem closed by the operator as missing: %+v", p)
}
}
+
+// Astra round 3: the discovery marker is durable before any candidate
+// commits. At the moment the second candidate is read (the first, an ended
+// subscription, already committed), a console that stopped there would
+// still find the customer on the discovery list.
+func TestDiscoveryMarkerIsDurableBeforeACandidateCommits(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))
+ pass := billingNow.Add(time.Hour)
+ var checked bool
+ bf.fake.Lock()
+ bf.fake.BeforeSubscription = func(id string) error {
+ if id != "sub_b" || checked {
+ return nil
+ }
+ b, _ := bf.st.BillingAccount(bf.acct.ID)
+ if b == nil || b.Subscription != "sub_a" {
+ return nil // sub_a has not committed yet
+ }
+ checked = true
+ list, err := bf.st.DiscoverableBillingAccounts(pass.Add(-billingDiscoveryWindow), 0, 10)
+ if err != nil {
+ t.Error(err)
+ }
+ found := false
+ for _, x := range list {
+ found = found || x.AccountID == bf.acct.ID
+ }
+ if !found {
+ t.Error("after sub_a committed, a console stopping now would never discover the customer again")
+ }
+ return errors.New("console stops here")
+ }
+ bf.fake.Unlock()
+ bf.srv.billingSyncPass(context.Background(), pass)
+ if !checked {
+ t.Fatal("the interruption point was never reached")
+ }
+ bf.fake.Lock()
+ bf.fake.BeforeSubscription = nil
+ bf.fake.Unlock()
+ bf.srv.billingSyncPass(context.Background(), pass.Add(time.Hour))
+ if p := bf.plan(t); p != "personal" {
+ t.Fatalf("the next pass did not recover: plan %q", p)
+ }
+}
+
+// The marker cannot be written: the customer is skipped this pass, so no
+// candidate commits without it, and the next pass finds the purchase.
+func TestDiscoverySkipsACustomerWhoseMarkerCannotBeWritten(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))
+ if _, err := bf.st.db.Exec(`CREATE TRIGGER fail_mark BEFORE UPDATE OF discover_retry ON billing_accounts
+ WHEN NEW.discover_retry = 1 BEGIN SELECT RAISE(ABORT, 'injected'); END`); err != nil {
+ t.Fatal(err)
+ }
+ bf.fake.CustomerCalls = 0
+ bf.srv.billingSyncPass(context.Background(), billingNow.Add(time.Hour))
+ if bf.fake.CustomerCalls != 0 {
+ t.Fatalf("discovery listed the customer's subscriptions without its marker: %d calls", bf.fake.CustomerCalls)
+ }
+ if b, _ := bf.st.BillingAccount(bf.acct.ID); b.Subscription != "" {
+ t.Fatalf("a candidate committed without the marker: %+v", b)
+ }
+ if _, err := bf.st.db.Exec(`DROP TRIGGER fail_mark`); err != nil {
+ t.Fatal(err)
+ }
+ bf.srv.billingSyncPass(context.Background(), billingNow.Add(2*time.Hour))
+ if p := bf.plan(t); p != "personal" {
+ t.Fatalf("the next pass did not find the purchase: plan %q", p)
+ }
+}
+
+// A candidate that keeps failing is retried every pass and, after
+// billingDiscoveryProblemAfter consecutive failed passes, opens one
+// discovery_failing problem; a pass that succeeds resolves it.
+func TestPersistentDiscoveryFailureOpensAProblem(t *testing.T) {
+ bf := newBillingFixture(t)
+ bf.ready(t)
+ bf.put(bf.personalSub("sub_b", "active", nil))
+ bf.fake.SubErr = map[string]error{"sub_b": errors.New("timeout")}
+ pass := billingNow
+ for i := 1; i < billingDiscoveryProblemAfter; i++ {
+ pass = pass.Add(time.Hour)
+ bf.srv.billingSyncPass(context.Background(), pass)
+ }
+ if open, _ := bf.st.BillingProblems(false); len(open) != 0 {
+ t.Fatalf("problem opened after %d failed passes: %+v", billingDiscoveryProblemAfter-1, open)
+ }
+ for i := 0; i < 2; i++ {
+ pass = pass.Add(time.Hour)
+ bf.srv.billingSyncPass(context.Background(), pass)
+ }
+ open, _ := bf.st.BillingProblems(false)
+ if len(open) != 1 || open[0].Reason != problemDiscoveryFailing || open[0].AccountID != bf.acct.ID {
+ t.Fatalf("problems = %+v", open)
+ }
+ bf.fake.SubErr = nil
+ bf.srv.billingSyncPass(context.Background(), pass.Add(time.Hour))
+ if p := bf.plan(t); p != "personal" {
+ t.Fatalf("recovery: plan %q", p)
+ }
+ if open, _ := bf.st.BillingProblems(false); len(open) != 0 {
+ t.Fatalf("discovery_failing not resolved: %+v", open)
+ }
+}
diff --git a/internal/console/billingstore.go b/internal/console/billingstore.go
index 146fb771a..d5bbff43c 100644
--- a/internal/console/billingstore.go
+++ b/internal/console/billingstore.go
@@ -59,6 +59,7 @@ const (
problemUnrecognised = "unrecognised"
problemNotBillingOwned = "not_billing_owned"
problemSubscriptionMissing = "subscription_missing"
+ problemDiscoveryFailing = "discovery_failing"
)
func (s *Store) migrateBillingAccounts() error {
@@ -76,7 +77,8 @@ func (s *Store) migrateBillingAccounts() error {
paid_period_end INTEGER NOT NULL DEFAULT 0,
synced_at INTEGER NOT NULL DEFAULT 0,
bound_at INTEGER NOT NULL DEFAULT 0,
- discover_retry INTEGER NOT NULL DEFAULT 0
+ discover_retry INTEGER NOT NULL DEFAULT 0,
+ discover_failures 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 != '';
@@ -407,15 +409,26 @@ func (s *Store) ResolveBillingProblem(accountID int64, subscription, reason, not
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)
+// MarkBillingDiscovery records, before discovery syncs any of the
+// account's candidate subscriptions, that its discovery has outstanding
+// work (Astra round 3): a candidate that commits and a pass that stops
+// before finishing still leave the account on the discovery list,
+// whatever subscription it records and however long ago it was bound.
+func (s *Store) MarkBillingDiscovery(accountID int64) error {
+ _, err := s.db.Exec(`UPDATE billing_accounts SET discover_retry = 1 WHERE account_id = ?`, accountID)
return err
}
+
+// EndBillingDiscovery records the outcome of one discovery pass over the
+// account. Success clears the marker and the failure count; a failure keeps
+// the marker and returns the number of consecutive failed passes.
+func (s *Store) EndBillingDiscovery(accountID int64, failed bool) (int, error) {
+ if !failed {
+ _, err := s.db.Exec(`UPDATE billing_accounts SET discover_retry = 0, discover_failures = 0 WHERE account_id = ?`, accountID)
+ return 0, err
+ }
+ var n int
+ err := s.db.QueryRow(`UPDATE billing_accounts SET discover_failures = discover_failures + 1 WHERE account_id = ?
+ RETURNING discover_failures`, accountID).Scan(&n)
+ return n, err
+}