carlos / platform Public

plans 6b: revision 6 after Astra's round 5. Durable late-restore verification obligations re-checked on every observation and selected by the pass, surviving invoice failures and restarts, with a stored renewal baseline; orphaned sending rows adopted as unresolved, one recoveryEligible gate for every resend, escalation for rows that can never become eligible; per-branch retry costs and invoice and line paging in the budget, asserted against a Stripe-paging fake; Invoices read a pending decision for Paul (Call 18)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev df01e87170234551aa039d0b2fa7f10a699c5c0e parent 51a331c
1 file changed, +110 −47
  • docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md +110 −47

CI passed — run details

diff --git a/docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md b/docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md
index 5a60fa2b5..fb12e7d75 100644
--- a/docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md
+++ b/docs/superpowers/plans/2026-10-25-plans-6b-checkout-flow.md
@@ -12,13 +12,12 @@
A static pricing page links to one stable console URL, which takes a signed-out visitor through sign-in or sign-up first.
-**Revision 5 (2026-10-25)** answers Astra's round 4 (`plans6b-plan-review-r4.md`, at `98fc42c8`), which accepted the idempotency design.
-- The resend unit is now an **opaque prepared request**: the exact bytes the adapter sends, persisted before the first send.
-- One predicate decides "outstanding" everywhere.
-- Admission uses available paid capacity before anything is reduced.
-- Retirement finishes outstanding work before it judges subscriptions.
-- The residual risk of a late restore has detection.
-- This file is **self-contained**: everything earlier revisions bound by reference is inlined.
+**Revision 6 (2026-10-25)** answers Astra's round 5 (`plans6b-plan-review-r5.md`, at `51a331c2`), which accepted round 4's fixes and the R1/R2 framing.
+- R1 detection is a **durable verification obligation** per restore, re-checked on every later observation until it resolves, and surviving failures and restarts.
+- A persisted `sending` row is recovered exactly like `unresolved`, with **one function** (`recoveryEligible`) owning recovery eligibility, as `opOutstanding` owns exclusion.
+- The budget gives each branch its own retry cost, and counts invoice and line pages.
+
+Revision 5 made every write an opaque prepared request, unified the outstanding predicate, made admission use present capacity first, and ordered the retirement gate. This file is **self-contained**: no task points to an earlier revision.
"Review record" maps every finding. Paul's seventeen calls stand as ruled.
@@ -64,17 +63,35 @@ Read with `stripe docs` on 2026-10-25. API v1, which is what the 6a client calls
6. **A terminal intent is history.** Checkout and retirement judge the account's subscriptions from an exhaustive list.
7. **One predicate decides "outstanding".**
- `opOutstanding(state)` is true for `sending`, `unresolved` and `pending`.
- - The partial unique index, revocation, retry eligibility, admission, change refusal and the retirement gate all call it.
+ - The partial unique index, revocation, admission, change refusal and the retirement gate all call it.
- A test asserts the index's state list equals the predicate's.
+8. **One function decides "recoverable".**
+ - `recoveryEligible(r resendState, providerNow, consoleNow time.Time) (bool, reason string)` owns every decision to resend, for operations, customer creates, Checkout creates and expiries. A resend is allowed only when all of these hold:
+ - the state is `sending` or `unresolved` (delivery unknown);
+ - it is not `Indeterminate`;
+ - `providerNow < resendUntil`;
+ - the skew is within 5 minutes;
+ - its context is still current (the invite is still pending; the intent has not expired).
+ - The observation pass escalates exactly the rows that are outstanding, not `pending`, and **permanently ineligible**: indeterminate, or past their window.
+ - **A `sending` row seen by anyone holding the billing hold is orphaned.** The handler that wrote it holds the hold until it records an outcome, so a crash is the only way such a row survives. It is treated exactly as `unresolved`, and converted in the same transaction as the read that finds it.
## Risks
- **R1. A restore first applying after renewal** (inherited finding 2, residual).
- The 25 h margin, the 5-minute skew cap and the `period end − 1 h` resend cut-off bound when restores are **sent**. Nothing documented bounds when Stripe **executes** them.
- Failure direction: a late restore gives the account free packs or seats for the new period, until an operator acts. **It never overcharges.**
- - **Detection:** when any read applied under the hold shows a period change for a subscription that had a restore operation sent in the previous period (any state but `failed`), `lateRestoreCheckLocked` reads the renewal invoice. It compares each item's current quantity with the invoiced quantity for that price. A quantity above the invoiced one, not explained by an `applied` operation in the new period, opens a `restore_after_renewal` billing problem naming the item and both quantities.
- - It writes nothing to the provider. The operator reduces the quantity or bills it in the Dashboard, then closes the problem.
- - It needs Invoices read on the restricted key (6c).
+ - **Detection: a durable verification obligation.**
+ - Every `opRestore` inserts a `billing_restore_checks` row in the same transaction as the operation. The row records the subscription, the restore's period end, the price, the restore target, the operation id and the state `open`.
+ - It closes `clear` when either:
+ - the restore is proven to have applied **in its own period**: a definite response or a read showing the target with `PeriodEnd` equal to the restore's period end, so the renewal billed it;
+ - or it is proven never to have executed: `failed`, or an operator close of `operation_unresolved` with `not-executed`.
+ - Otherwise, once the period has moved, **every later observation** of that subscription runs `restoreCheckLocked`, as do the webhook, Confirm now, any user request and the hourly pass (which selects open obligations directly, so it is not triggered only by a period change). It:
+ - reads the renewal invoice for the period starting at the restore's period end, **once**, and stores its quantities as the obligation's baseline, because a later proration invoice can replace `latest_invoice`;
+ - compares the item's current quantity with the baseline. Above it, the obligation becomes `flagged` and opens `restore_after_renewal` ("item %s is at %d, the renewal billed %d"). At or below it, while the operation is still outstanding, the obligation stays `open`. Once the operation is terminal, it is `clear`.
+ - **The obligation survives failures.** An invoice-read failure or `ErrIncomplete` leaves it `open`, with `attempts` and `last_error` updated. A crash between saving the renewal and checking it leaves it `open`, and the pass finds it, because the trigger is the open row, not the period change.
+ - An obligation still `open` 7 days after the renewal opens `restore_check_stalled` for an operator.
+ - Detection writes nothing to the provider. The operator reduces the quantity or bills it in the Dashboard, then closes the problem.
+ - It needs Invoices read on the restricted key: a **pending decision for Paul** (Call 18).
- **R2. A late Checkout session** after its create was abandoned (Invariant 1's exception).
- The session's URL was never shown, so nobody can pay it. Its `expires_at` is at most an hour after the create, so it is already past or close.
- If one were ever completed anyway, the live-subscription check (Checkout) and discovery would adopt the subscription, and a second purchase is refused.
@@ -187,6 +204,12 @@ Also binding:
- a positive read settles at any time, from any path.
- **Operator:** the pass opens `operation_unresolved` for a cached 5xx (fact 5) or a window that closed with no definite outcome (fact 6). Changes on the account stay refused. Closing it needs a fresh read showing the target, or the operator's note stating what the Dashboard request log shows. A negative read alone never closes it.
- **A known pending payment never escalates.** It follows Stripe's pending-update lifecycle (fact 8).
+18. **Pending, asked of Paul by the coordinator: grant Invoices read to the restricted key** for Risk R1's detection.
+ - **Recommend: grant it.** Astra concurs (round 5): no complete permission-free substitute exists.
+ - The subscription read doesn't expose the renewal invoice's lines.
+ - `latest_invoice` can be replaced by a later proration invoice.
+ - Signed invoice webhooks are not recoverable when a delivery is missed.
+ - **If refused:** R1 stays an undetected residual risk. `billing_restore_checks` is still written and closed `clear` where provable, but the open ones raise `restore_check_stalled` instead of reading invoices, and an operator compares quantities in the Dashboard.
## Global Constraints
@@ -228,37 +251,42 @@ Also binding:
- Notation:
- `L(n)`: an exhaustive list over `n` objects examined in every status, `max(1, ceil(n/100))` requests, at most 10, else `ErrIncomplete`.
- `S`: a subscription sync, 1 read plus 1 when another recorded subscription is live, so 1 to 2.
- - `R`: in-handler retries, 0 to 3, each **a read and a resend**, so 2 requests per retry.
- - `F`: one `finishOpLocked`, 1 read plus at most 1 resend.
+ - Retry costs differ by branch. `N` is the number of in-handler retries, 0 to 3:
+ - **subscription operation:** each retry is 1 subscription read + 1 resend, so `1 + 2N`;
+ - **Checkout create:** each retry is `L(c)`, the customer's sessions since the intent paged exhaustively, + 1 resend, so `1 + N × (L(c) + 1)`;
+ - **customer create:** no read, so `1 + N`;
+ - **expiry:** each retry is 1 session read + 1 resend, so `1 + 2N`.
+ - `F`: one recovery inside a user's request. For an operation or expiry, 1 read + at most 1 resend. For a Checkout create, `L(c)` + at most 1. For a customer create, at most 1.
+ - `I(v, l)`: a renewal-invoice lookup, `L(v)` invoice pages (filtered to the subscription and `billing_reason=subscription_cycle`) + `L(l)` line pages. It is paid once per obligation on success; a failure repeats it at the next observation.
| Operation | Branch | Stripe requests |
| --- | --- | --- |
| Readiness | per attempt | 34 (35 with a house coupon); stops at the first failure. Retries back off 1, 2, 4, 8, 16, then every 30 min. |
| Billing page view | any | 0 |
| Confirm now | unresolved op | `F` + `S` |
- | Checkout start | first purchase | `S` (recorded subscription, if any) + `L(all subs)` + customer (1 + 2R) + create (1 + 2R) |
+ | Checkout start | first purchase | `S` (recorded subscription, if any) + `L(all subs)` + customer (1 + N) + create (1 + N × (L(c) + 1)) |
| | open intent, same request | `S` + `L` + 1 session read |
- | | open intent, Start over | `S` + `L` + 1 session read + expiry (1 + 2R; +1 read if refused) + create (1 + 2R) |
+ | | open intent, Start over | `S` + `L` + 1 session read + expiry (1 + 2N; +1 read if refused) + create (1 + N × (L(c) + 1)) |
| | creating intent | `S` + `L` + `F` on the create, then the branch it resolves to |
| | live subscription found | `S` + `L` + `S` per live id, then a refusal |
| Continue (GET) | open intent | 1 session read |
| Checkout return | any | 1 session read + `S` |
| Pack or plan change | prior op outstanding | `F`; still outstanding means a refusal |
| | no step | `S` |
- | | one step | `S` + (1 + 2R) + `S` |
- | | restore, then charge | `S` + 2 × (1 + 2R) + `S` |
- | Renewal | any | `S` + (1 + 2R) + `S` |
+ | | one step | `S` + (1 + 2N) + `S` |
+ | | restore, then charge | `S` + 2 × (1 + 2N) + `S` |
+ | Renewal | any | `S` + (1 + 2N) + `S` |
| Portal | any | 1 |
| Join, billing team | free seat | `S` |
- | | restore or charge | `S` + (1 + 2R) + `S` |
- | | both | `S` + 2 × (1 + 2R) + `S` |
- | Match seats | drift | `S` + (1 + 2R) + `S` |
- | Deletion gate, per run | `u` outstanding ops, `j` non-terminal intents, `k` live of `n` examined | `u` × `F` + per intent (1 session read + expiry 1 + 2R, or `F`) + `L(n)` + `k` × `S` |
- | Late-restore check | per observed renewal with a prior-period restore | 1 invoice read + `L(invoice lines)` |
- | Hourly pass, per account | any | 6a's sync; discovery `L(n)` per recently bound customer; 1 session read per open intent; 1 read per outstanding op; late-restore checks; **0 writes** |
+ | | restore or charge | `S` + (1 + 2N) + `S` |
+ | | both | `S` + 2 × (1 + 2N) + `S` |
+ | Match seats | drift | `S` + (1 + 2N) + `S` |
+ | Deletion gate, per run | `u` outstanding ops, `j` non-terminal intents, `k` live of `n` examined | `u` × `F` + per intent (1 session read + expiry 1 + 2N, or the create's `F`) + `L(n)` + `k` × `S` |
+ | Restore check | per open obligation, per observation | `S` (shared with the observation) + `I(v, l)` until the baseline is stored, then 0 |
+ | Hourly pass, per account | any | 6a's sync; discovery `L(n)` per recently bound customer; 1 session read per open intent (creating past `ExpiresAt`: `L(c)`); 1 read per outstanding op; per open obligation as above; **0 writes** |
- S3: nothing polled. A limits publication is a GET plus a conditional PUT, with conflict retries. `transitionAccountPlan` adds 4d's inventory reads and convergence writes per change that moves limits.
- - **Call-count assertions:** recovery, Checkout-branch, deletion and pass tests assert `Fake.CallsBy`, reads included. Pass tests assert zero writes.
+ - **Call-count assertions:** recovery, Checkout-branch, deletion, restore-check and pass tests assert `Fake.CallsBy` (each list page counted), reads included, against a fake that **pages like Stripe**: `limit` up to 100, `has_more`, `starting_after`, for subscriptions, sessions, invoices and invoice lines. Pass tests assert zero writes.
- **No product name** in code, tests, copy or example data. **No `Record` in helper or type names.**
- **Copy:** it lives in `internal/console/billingpage_copy.go` (`billingCopy`), `plancaps_copy.go` and `billing_cli_copy.go`. Tests compare against the maps, never literal text. House rules: no em dashes (a full stop and a new sentence), plain words, CLI lower case. Error fragments, diagnostics and JSON keys stay out. The Luna pass replaces every draft.
- **Census:**
@@ -513,7 +541,7 @@ Also binding:
LiveSubscriptions(ctx context.Context, customer string) ([]string, error) // exhaustive
CustomerCheckouts(ctx context.Context, customer string, createdAfter time.Time) ([]CheckoutInfo, error) // exhaustive
Checkout(ctx context.Context, sessionID string) (CheckoutInfo, error)
- RenewalInvoice(ctx context.Context, subscription string, periodStart time.Time) (InvoiceQuantities, error) // exhaustive lines
+ RenewalInvoice(ctx context.Context, subscription string, periodStart time.Time) (InvoiceQuantities, error) // exhaustive invoice pages, then exhaustive line pages
PortalURL(ctx context.Context, customer, returnURL, key string) (string, error)
}
func FindItem(sub *Subscription, prices PriceMap, kind, name string) (Item, bool)
@@ -524,6 +552,8 @@ Also binding:
- It models: `FailPayment`, `DeclineHard`, `PayPending`, `ExpirePending`, `FailBeforeDelivery`, `LoseNextResponse`, `CompleteLater(n)`, `Cached500Before`, `Cached500After`, `InFlight(n)`, `RateLimit`, `PruneKeysOlderThan`, `Replayed`.
- `Renew(sub)` moves the period a year on, keeps the items, drops any pending update, and writes a renewal invoice of the items' quantities.
- `ApplyAfterRenewal(key)` holds a sent request and applies it after the next `Renew`.
+ - **Stripe-faithful paging** for every list (subscriptions, sessions, invoices, invoice lines): `limit` up to 100, `has_more`, `starting_after`, each page counted in `CallsBy`. `InvoiceReadFails(n)` fails the next `n` invoice reads.
+ - **Crash hooks:** `CrashBeforeSend` (the console's send returns an injected crash before the Fake receives anything) and `CrashAfterSend` (the Fake applies, then the console crashes before recording). Tests restart the server on the same store.
- `ProviderClock` and `SkewBy(d)`; `PageSize`; Checkout sessions and races; `CallsBy` per method.
- [ ] **Step 1: Write the failing tests**
@@ -540,6 +570,8 @@ Also binding:
func TestFakeFailBeforeDeliveryAndLostResponse(t *testing.T)
func TestFakeRenewWritesInvoice(t *testing.T)
func TestFakeApplyAfterRenewal(t *testing.T)
+ func TestFakePagesLikeStripe(t *testing.T) // 250 invoices: 3 pages with has_more and starting_after; 0: 1 page
+ func TestFakeCrashHooks(t *testing.T)
func TestFakePagingAndIncomplete(t *testing.T)
func TestFakeCheckoutRaces(t *testing.T)
```
@@ -645,6 +677,7 @@ Also binding:
- `billing_checkout_intents(account_id INTEGER PRIMARY KEY, intent_id TEXT NOT NULL UNIQUE, session TEXT NOT NULL DEFAULT '', url TEXT NOT NULL DEFAULT '', book TEXT NOT NULL, plan TEXT NOT NULL, currency TEXT NOT NULL, seats INTEGER NOT NULL DEFAULT 0, packs TEXT NOT NULL DEFAULT '{}', prepared BLOB NOT NULL, expire_prepared BLOB, state TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, first_sent_at INTEGER NOT NULL DEFAULT 0, returned_at INTEGER NOT NULL DEFAULT 0, resolved_at INTEGER NOT NULL DEFAULT 0)`, with a partial unique index on `session` where non-empty.
- `billing_house(account_id INTEGER PRIMARY KEY, set_by TEXT NOT NULL, note TEXT NOT NULL, set_at INTEGER NOT NULL)`.
- `billing_retirements(account_id INTEGER PRIMARY KEY, started_by TEXT NOT NULL, started_at INTEGER NOT NULL)`.
+ - `billing_restore_checks(op_id TEXT PRIMARY KEY, account_id INTEGER NOT NULL, subscription TEXT NOT NULL, period_end INTEGER NOT NULL, price TEXT NOT NULL, target INTEGER NOT NULL, state TEXT NOT NULL, baseline TEXT NOT NULL DEFAULT '', attempts INTEGER NOT NULL DEFAULT 0, last_error TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, checked_at INTEGER NOT NULL DEFAULT 0)`. State is `open`, `clear` or `flagged`. It is classified `NonApp`: "an account's late-restore verification obligations; names no app".
- `decideBilling`:
- copies the facts;
- paid and recognised: `Next.Plan`, `Next.Seats`;
@@ -675,12 +708,12 @@ Also binding:
- [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'Decide|Sync|BillingWebhook|BillingSyncPass|ClaimSQL'`. Expected: PASS.
- [ ] **Step 5: Commit** `console: billing keeps team seats, provider facts and prepared requests through 6a's one transaction; intents, house and retirement rows (plans 6b)`.
-### Task 7: The billing hold, operations, finality and late-restore detection
+### Task 7: The billing hold, operations, finality, recovery and late-restore obligations
**Files:**
- Create: `internal/console/billinghold.go`, `billingops.go`, `billinglate.go`, their tests, and `billinglint_test.go`.
- Modify:
- - `billingsync.go`: lookup → `holdBilling` → `syncSubscriptionLocked`; after each `applyBillingRead`, `settleOpsLocked`, then `lateRestoreCheckLocked`;
+ - `billingsync.go`: lookup → `holdBilling` → `syncSubscriptionLocked`; after each `applyBillingRead`, `settleOpsLocked` (which first adopts orphaned `sending` rows), then `restoreCheckLocked` for every open obligation of the subscription;
- `billingpass.go`: readiness backoff, and operation observation (reads and problems only);
- `server.go`: `POST /a/{sqid}/billing/confirm`;
- `store_gate.go` (`billing_operations`);
@@ -721,38 +754,46 @@ Also binding:
func (s *Server) sendOpLocked(h billingHold, ctx context.Context, op billingOp, now time.Time) (opOutcome, *billing.Subscription, error)
func (s *Server) finishOpLocked(h billingHold, ctx context.Context, acct *Account, op *billingOp, now time.Time) (opOutcome, error)
func (s *Server) settleOpsLocked(h billingHold, acct *Account, sub *billing.Subscription, now time.Time) error
- func (s *Server) lateRestoreCheckLocked(h billingHold, ctx context.Context, acct *Account, prev *billingAccount, sub *billing.Subscription, now time.Time) error
+ type resendState struct { State string; Indeterminate bool; FirstSent, ResendUntil time.Time; ContextCurrent bool }
+ func recoveryEligible(r resendState, providerNow, consoleNow time.Time) (bool, string) // Invariant 8; the only resend gate
+ func (s *Store) AdoptOrphanedSending(opID string, now time.Time) error // sending -> unresolved, in the read's transaction
+ func (s *Store) OpenRestoreChecks(subscription string) ([]restoreCheck, error)
+ func (s *Store) OpenRestoreChecksAll(limit int) ([]restoreCheck, error)
+ func (s *Store) PutRestoreCheck(c restoreCheck) error
+ func (s *Server) restoreCheckLocked(h billingHold, ctx context.Context, acct *Account, sub *billing.Subscription, now time.Time) error // every open obligation of sub
func (s *Server) handleBillingConfirm(w http.ResponseWriter, r *http.Request)
func billingCheckDelay(failures int) time.Duration
```
- **`sendOpLocked`:**
1. `BeginBillingOp` (`sending`, with `Prepared`).
2. `Send`.
- 3. On `ErrNoResponse`, `ErrInFlight` or `ErrNotExecuted`, up to `handlerRetries` times (backoff 1, 2, 4 s): read the subscription, which settles on positive evidence, then `Send` the same `Prepared` again, only if the op is still `sending` or `unresolved`, `skewOK`, and inside `resendUntil`.
+ 3. On `ErrNoResponse`, `ErrInFlight` or `ErrNotExecuted`, up to `handlerRetries` times (backoff 1, 2, 4 s): read the subscription, which settles on positive evidence, then `Send` the same `Prepared` again, only if `recoveryEligible`.
4. Record the outcome:
- success at the target: `MarkOpApplied`;
- success with `PendingUpdate`: `pending`;
- `ErrPaymentFailed` or `ErrRefused`: `failed`;
- `ErrIndeterminate`: `unresolved` with `Indeterminate` set;
- otherwise: `unresolved`.
-- **`finishOpLocked`** runs only in a user's request, for an `unresolved` op:
+- **`finishOpLocked`** runs only in a user's request, for an op in `sending` or `unresolved` (an orphaned `sending` row is adopted as `unresolved` first):
1. Read, then settle. Target visible: `MarkOpApplied`. `PendingUpdate`: `pending`.
- 2. If the op is `Indeterminate`, past `resendUntil`, has a bad skew, or **belongs to an invite that is no longer pending**: no send.
+ 2. If `recoveryEligible` is false (indeterminate, past the window, skew, or an invite no longer pending): no send.
3. Otherwise send the same `Prepared` once, and record the outcome as above.
- **`settleOpsLocked`** uses positive evidence only:
- target visible: `MarkOpApplied`;
- `PendingUpdate`: `pending`;
- a `pending` op whose `PendingUpdate` is gone and whose target is unmet: `abandoned` (fact 8);
- otherwise unchanged. A negative read never abandons an unresolved op.
-- **`lateRestoreCheckLocked`** (Risks R1): when `sub.PeriodEnd` moved past `prev.PeriodEnd` and an `opRestore` was first sent in the previous period in any state but `failed`:
- 1. `RenewalInvoice(sub, prevPeriodEnd)`.
- 2. For each restored price: if the item's quantity exceeds the invoiced one, and no `applied` op in the new period explains the difference, open `restore_after_renewal` ("item %s is at %d, the renewal billed %d").
- 3. `ErrIncomplete` logs, and retries at the next observation.
+- **`restoreCheckLocked`** (Risks R1), for each open obligation of the subscription:
+ 1. If the restore's operation is terminal and proved in its own period (applied with `PeriodEnd` equal to the obligation's), or proved never executed: `clear`.
+ 2. If the read's `PeriodEnd` still equals the obligation's: nothing to do yet.
+ 3. Otherwise, with no baseline stored: `RenewalInvoice(sub, obligation.PeriodEnd)`. On success, store the baseline. On failure (`ErrIncomplete`, any error), `attempts++` and `last_error`, and stay `open`.
+ 4. With a baseline: an item quantity above it, not explained by an `applied` op sent in the new period, is `flagged` and opens `restore_after_renewal`. Otherwise, if the operation is terminal, `clear`; if not, stay `open`.
+ 5. Open longer than 7 days after the renewal: open `restore_check_stalled`.
It writes nothing to the provider.
- **The observation pass:**
- - for each outstanding op, `holdBilling` and `syncSubscriptionLocked`;
- - opens `operation_unresolved` for an `unresolved` op that is `Indeterminate` or past `resendUntil`;
+ - for each outstanding op, and for each subscription with an open restore obligation (`OpenRestoreChecksAll`): `holdBilling` and `syncSubscriptionLocked`. That adopts orphaned `sending` rows, settles on positive evidence, and runs `restoreCheckLocked`;
+ - opens `operation_unresolved` for an op in `sending` or `unresolved` that `recoveryEligible` says can never become eligible again (indeterminate, or past its window);
- never for `pending`;
- **0 writes.**
- **The `operation_unresolved` close**, under the hold, after a fresh read:
@@ -789,16 +830,26 @@ Also binding:
func TestOperatorCloseNeedsEvidence(t *testing.T)
func TestOneOutstandingPerSubscription(t *testing.T)
func TestReorderedWebhooksSettleOnce(t *testing.T)
- func TestLateRestoreDetected(t *testing.T) // restore sent at P1-25h30m held by ApplyAfterRenewal; Renew; apply; observation: restore_after_renewal opened,
- // CallsBy writes == the original send only
- func TestLateRestoreNotFlaggedWhenBilled(t *testing.T) // restore applied in P1: renewal invoice bills it: no problem
+ func TestRecoveryEligibleIsTheOnlyGate(t *testing.T) // AST: every Send call site for a resend is guarded by recoveryEligible
+ func TestCrashBeforeSendRecovered(t *testing.T) // CrashBeforeSend: row sending, Fake saw nothing; restart; pass: adopted as unresolved, no write;
+ // Confirm now: read, then the same bytes once; applied; CallsBy writes == 1
+ func TestCrashAfterSendRecovered(t *testing.T) // CrashAfterSend: Fake applied, row sending; restart; Confirm now: the read shows the target: applied, no resend
+ func TestOrphanedSendingEscalates(t *testing.T) // CrashBeforeSend, no user returns; past the window: the pass opens operation_unresolved
+ func TestRestoreCheckClearsWhenAppliedInPeriod(t *testing.T) // definite response in P1: obligation clear at once; no invoice read
+ func TestLateRestoreDetected(t *testing.T) // restore held by ApplyAfterRenewal; Renew; observe: quantities match the invoice, obligation open;
+ // delayed apply; observe: flagged, restore_after_renewal; CallsBy: one invoice lookup I(v,l); writes == the original send
+ func TestRestoreCheckSurvivesInvoiceReadFailure(t *testing.T) // InvoiceReadFails(2): open, attempts 2; third observation reads, flags
+ func TestRestoreCheckSurvivesCrashAfterSync(t *testing.T) // crash after applyBillingRead saved P2, before the check; restart; the pass finds the open obligation and checks it
+ func TestRestoreCheckBaselineIgnoresLaterInvoices(t *testing.T) // a proration invoice after the renewal: the stored baseline is used
+ func TestRestoreCheckStalls(t *testing.T) // failures for 7 days: restore_check_stalled
+ func TestLateRestoreNotFlaggedWhenBilled(t *testing.T) // restore applied in P1: renewal invoice bills it: clear
func TestPassesNeverWrite(t *testing.T)
func TestReadinessBackoff(t *testing.T)
```
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'BillingLockedHelpers|ConsoleBillingHasNo|OpOutstanding|SyncSubscriptionLocked|Refresh|Allowance|QuantityPlan|PreparedPersisted|HandlerRetry|TimeoutStillProcessing|InFlight|RateLimit|Cached500|WindowCloses|NoResend|Pending(Never|Expiry)|OperatorClose|OneOutstanding|ReorderedWebhooks|LateRestore|PassesNeverWrite|ReadinessBackoff'`. Expected: FAIL.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'BillingLockedHelpers|ConsoleBillingHasNo|OpOutstanding|RecoveryEligible|Crash(Before|After)Send|OrphanedSending|RestoreCheck|SyncSubscriptionLocked|Refresh|Allowance|QuantityPlan|PreparedPersisted|HandlerRetry|TimeoutStillProcessing|InFlight|RateLimit|Cached500|WindowCloses|NoResend|Pending(Never|Expiry)|OperatorClose|OneOutstanding|ReorderedWebhooks|LateRestore|PassesNeverWrite|ReadinessBackoff'`. Expected: FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4: Run** again, plus the sync, webhook, pass, missing and claim suites. Expected: PASS.
-- [ ] **Step 5: Commit** `console: operations as prepared requests resolved by Stripe's idempotent result or a positive read; one outstanding predicate; passes only read; late restores detected (plans 6b)`.
+- [ ] **Step 5: Commit** `console: operations as prepared requests resolved by Stripe's idempotent result or a positive read; one outstanding predicate and one recovery gate; orphaned sends recovered; durable late-restore obligations; passes only read (plans 6b)`.
### Task 8: The billing page and the upgrade entry
@@ -929,11 +980,11 @@ Also binding:
```
- **The customer:**
1. The first attempt prepares `PrepareCustomer(sqid, "customer:<sqid>:1")` and stores it on the billing row before sending.
- 2. No response, 409 or 429: the handler retries (a read is not possible for a customer, so the resend is the check) inside `CustomerFirstSentAt + 23 h`. A later Checkout request finishes it the same way.
+ 2. No response, 409 or 429: the handler retries (a read is not possible for a customer, so the resend is the check) while `recoveryEligible` (window `CustomerFirstSentAt + 23 h`). A later Checkout request finishes it the same way. A crash leaves the attempt recorded with `CustomerFirstSentAt` set and no customer bound, so it is recovered exactly as a no-response.
3. A cached 5xx or a closed window: `CustomerAttempt++` with a new key (Risks R3). Only a definite answer is bound.
- **The Checkout create:**
1. The intent is put with its `Prepared`: every parameter resolved, including the coupon id from `BillingConfig.HouseCoupon` at that moment for a house account, URLs and expiry.
- 2. Send, with handler retries: a `Checkout` read by intent id through `CustomerCheckouts` where possible, then the same bytes, inside `min(FirstSentAt + 23 h, ExpiresAt)`.
+ 2. Send, with handler retries: an exhaustive `CustomerCheckouts` read looking for the intent id, then the same bytes, while `recoveryEligible` (window `min(FirstSentAt + 23 h, ExpiresAt)`, context: not expired). A crash leaves the intent `creating` with `FirstSentAt` set, which is recovered the same way by the next owner request.
3. Success: open. `ErrRefused`: abandoned. Otherwise it stays creating, and the page offers confirm.
4. When indeterminate or out of the window, observe `CustomerCheckouts` by intent id: found, record it; not found, abandoned (Invariant 1's stated exception, Risks R2).
- **Expiry** (Start over and retirement only): `PrepareExpire(session, "expire:<intent id>")` is stored on the intent. Send, with retries. The session's state from a read decides: expired, or complete (then sync it, completed).
@@ -980,6 +1031,9 @@ Also binding:
func TestCreateWindowClosedNotFoundAbandoned(t *testing.T)
func TestCustomerCreateNoResponseResent(t *testing.T)
func TestCustomerCreateCached500NewAttempt(t *testing.T)
+ func TestCreateRetryCountsSessionPages(t *testing.T) // 250 sessions since the intent, 2 retries: 1 + 2 x (3 + 1) == 9 requests
+ func TestCustomerRetryCountsNoRead(t *testing.T) // 3 retries: 4 requests
+ func TestCreateCrashRecovered(t *testing.T) // CrashAfterSend on the create; restart; Confirm now: found by intent id, open; no resend
func TestExpiryNoResponseResent(t *testing.T)
func TestPassRightAfterCheckoutKeepsSession(t *testing.T)
func TestPassObservesCompletedIntent(t *testing.T)
@@ -1267,7 +1321,7 @@ CLI: `carlos billing house -account <sqid> -on|-off -note "..."`, console mode o
- `carlos billing house` in the CLI reference.
- [ ] **Census from the final diff.**
- `make census-card` on the finished branch; units and envelopes come from its output.
- - Expect among them: `Prepare*`, `Send`, `sendOpLocked`, `finishOpLocked`, `settleOpsLocked`, `lateRestoreCheckLocked`, `MarkOpApplied`, `ensureCustomerLocked`, `createSessionLocked`, `observeIntentLocked`, `replaceIntentLocked`, `admitMember`, `reconcileSeatsLocked`, `retireGateLocked`, the passes, eleven routes and five tables.
+ - Expect among them: `Prepare*`, `Send`, `sendOpLocked`, `finishOpLocked`, `settleOpsLocked`, `restoreCheckLocked`, `recoveryEligible`, `AdoptOrphanedSending`, `MarkOpApplied`, `ensureCustomerLocked`, `createSessionLocked`, `observeIntentLocked`, `replaceIntentLocked`, `admitMember`, `reconcileSeatsLocked`, `retireGateLocked`, the passes, eleven routes and five tables.
- `census-propose` takes the body and sites changes. New units are hand-written decisions.
- Review every changed function in each re-pinned envelope. Keep the record-write gate.
- Astra approves; Paul takes the decisions.
@@ -1301,6 +1355,15 @@ CLI: `carlos billing house -account <sqid> -on|-off -note "..."`, console mode o
| inherited 1 (Checkout create exception) | Stated as Invariant 1's exception and Risk R2. |
| single file | Revisions 2 and 3's binding text, draft strings and test assertions are inlined; no task points elsewhere. |
+**Round 5** (`51a331c2`):
+
+| Finding | Revision 6 |
+| --- | --- |
+| 1. R1 detection stops after the first renewal observation | A `billing_restore_checks` obligation per restore (subscription, period, op), written with the op. It is re-checked on every observation and selected directly by the pass, until it is proven applied in its own period, never executed, or compared against a stored renewal-invoice baseline (flagged or clear). It survives invoice-read failures, `ErrIncomplete` and restarts, and stalls to an operator after 7 days. Tests: renew, observe, delayed apply, observe; invoice-read failure; crash after sync; later proration invoice. |
+| 2. orphaned `sending` rows | Invariant 8: a `sending` row seen under the hold is orphaned and adopted as `unresolved`. `recoveryEligible` is the single resend gate for ops, customer creates, Checkout creates and expiries, and the pass escalates rows that can never become eligible. Tests: crash before send, crash after send, an orphan escalating, a Checkout create crash. |
+| 3. retry costs | Per-branch retry costs: operation `1 + 2N`, Checkout create `1 + N × (L(c) + 1)`, customer `1 + N`, expiry `1 + 2N`. `I(v, l)` counts invoice and line pages. Counts are asserted against a fake that pages like Stripe. |
+| Invoices read | A pending decision for Paul (Call 18), recommended with Astra's concurrence, with the fallback if refused. |
+
---
## Plan 6c: Stripe setup runbook (outline)
@@ -1332,7 +1395,7 @@ The runbook goes at `docs/superpowers/plans/2026-10-XX-plans-6c-stripe-setup.md`
5. **The webhook:** `https://<console>/billing/webhook`, with `checkout.session.completed`, `customer.subscription.created`, `customer.subscription.updated`, `customer.subscription.deleted`, `invoice.paid` and `invoice.payment_failed`; API version `2025-02-24.acacia`; the secret goes to `CARLOS_STRIPE_WEBHOOK_SECRET`.
6. **Retry settings:** cancel after all retries fail.
7. **The restricted `rk_` key:**
- - granted: Checkout Sessions write (which also lists a customer's sessions), Customers write, Subscriptions write, Customer portal write, Billing portal configurations read, Prices read, Products read, Coupons read, and **Invoices read** (Risk R1's detection, new in revision 5);
+ - granted: Checkout Sessions write (which also lists a customer's sessions), Customers write, Subscriptions write, Customer portal write, Billing portal configurations read, Prices read, Products read, Coupons read, and **Invoices read, pending Paul's decision (Call 18)** for Risk R1's detection;
- not granted: refunds, charges, events, webhook endpoints, keys, subscription schedules.
8. **Console variables** (EnvironmentFile only): `CARLOS_BILLING`, `CARLOS_PLAN_CATALOG`, `CARLOS_PRICE_BOOK`, `CARLOS_BILLING_PRICES`, `CARLOS_STRIPE_SECRET_KEY`, `CARLOS_STRIPE_ACCOUNT`, `CARLOS_STRIPE_WEBHOOK_SECRET`, `CARLOS_STRIPE_PORTAL_CONFIGURATION`, and optionally `CARLOS_STRIPE_HOUSE_COUPON`.
9. **Test-mode rehearsal on dev** (test clocks):