carlos / platform Public

plans 6b: revision 7 after Astra's round 6. Flagging a late-restore obligation and opening its problem in one transaction (openBillingProblemTx); provider time required only for restores, other resend deadlines console time 22 h from the first send, a clock-skew observation from every provider response refusing all resends past 5 minutes and opening clock_skew; 6a names re-checked against main 7f79385e (endMissingSubscriptionLocked, closeBillingProblemLocked, the house coupon on CreateCheckoutParams); rebase onto main now that 6a is merged

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

CI cancelled — superseded by a newer push — 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 fe60ab702..c1738c3de 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,12 +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 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 7 (2026-10-26)** answers Astra's round 6 (`plans6b-plan-review-r6.md`, at `09060b49`), which accepted round 5's fixes. 6a is now merged on main (`7f79385e`), and Paul granted Invoices read (Call 18).
+- Flagging a late-restore obligation and opening its problem commit in **one transaction**.
+- **Recovery's time source is now simple.** Provider time is required only for restores, from the subscription read that precedes every restore send. Every other resend deadline is console time, 22 hours from the first send. A recorded clock-skew observation, fed by every provider response, refuses all resends when it is more than 5 minutes off.
+- 6a's names are re-checked against main: `endMissingSubscriptionLocked`, `closeBillingProblemLocked`, and the house coupon's real home.
-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.
+Revision 6 added durable restore obligations, crash recovery of `sending` rows and per-branch retry costs. Revision 5 made every write an opaque prepared request. This file is **self-contained**: no task points to an earlier revision.
"Review record" maps every finding. Paul's seventeen calls stand as ruled.
@@ -45,7 +45,7 @@ Read with `stripe docs` on 2026-10-25. API v1, which is what the 6a client calls
1. **Finality comes from the provider.** It comes from an idempotent result or a positive read, never from elapsed time or a negative read.
- Every write is a **prepared request**: the adapter's exact encoded body, path, method and idempotency key, with every parameter resolved (price ids, item ids, coupon id, URLs, metadata, proration timestamp, constants). It is persisted before its first send and never edited afterwards.
- The only resend is those stored bytes with the same key, preceded by a read wherever one exists (every subscription and session write; a customer create has no id to read, so its same-key resend is its own check). If the read shows the target or a pending update, the outcome is recorded and nothing is sent.
- - The resend window closes at the earlier of `first send + 23 h` and `period end − 1 h`, both in provider time (Invariant 4). Facts 1 to 6 give it.
+ - The resend window is set by Invariant 8. Facts 1 to 6 give it.
- Never send different bytes under a key. Never send a prepared request whose context has gone stale (a new period, book, consent or intent, or an invite no longer pending) for the first time.
- New work is computed fresh.
- **One exception, stated:** a Checkout create that ends indeterminate or out of its window is abandoned when the customer's exhaustive session list does not contain its intent id. That is safe because a late session is unusable (Risks, R2), not because it is final.
@@ -56,8 +56,8 @@ Read with `stripe docs` on 2026-10-25. API v1, which is what the 6a client calls
3. **Provider enumeration is exhaustive or it refuses.** Lists page to completion, up to 10 pages of 100, else `ErrIncomplete`. This includes discovery, which is migrated.
4. **Refresh and allowance are separate; restores keep away from the period end.**
- `refreshLocked` is the plain sync. `allowanceLocked` also requires the paid period to match the read, and is used only for quantity changes and joins on a live, paid subscription.
- - A restore (a `ProrateNone` raise up to the period's paid quantity) is first sent only when `periodEnd − providerTime > 25 h`, where `providerTime` is the `Date` header of the fresh read.
- - No restore, and no resend of any request, is sent when the console clock and `providerTime` differ by more than 5 minutes (`change.clock`).
+ - A restore (a `ProrateNone` raise up to the period's paid quantity) is first sent, or resent, only when `periodEnd − providerTime > 25 h`, where `providerTime` is the `Date` header of the subscription read that immediately precedes that send in the same request. A restore read without a `Date` header refuses (`change.clock`).
+ - The same read's skew (`|consoleNow − providerTime|`) must be within 5 minutes, else `change.clock`.
- Inside the margin, buying back is refused, and after renewal it is an ordinary charged add.
5. **Background passes never write to the provider.** They read, record what reads show, and open billing problems. Every write happens inside an owner's or invitee's request.
6. **A terminal intent is history.** Checkout and retirement judge the account's subscriptions from an exhaustive list.
@@ -66,12 +66,21 @@ Read with `stripe docs` on 2026-10-25. API v1, which is what the 6a client calls
- 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:
+ - `recoveryEligible(r resendState, clock clockState, 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;
+ - `consoleNow < r.FirstSent + 22 h`, and for subscription operations also `consoleNow < PeriodEnd − 1 h`;
+ - **the clock is trusted:** the most recent skew observation (below) is within 5 minutes and no older than 10 minutes;
+ - for a restore, additionally Invariant 4's provider-time margin on the read just made;
- its context is still current (the invite is still pending; the intent has not expired).
+ - **Why console time and 22 hours are safe.** Stripe keeps a key "for at least 24 hours" from the original request (fact 6), measured on Stripe's clock. `FirstSent` is recorded on the console's clock **before** the first send, so it is no later than Stripe's receipt plus the skew. With the skew bounded at 5 minutes by the trusted-clock rule, a resend at `FirstSent + 22 h` reaches Stripe no later than about 22 h 5 min after the original: 1 h 55 min inside the key's lifetime. That margin also covers request queueing and the in-handler backoff (seconds).
+ - **The clock observation.** The adapter calls a hook on **every** provider response that carries a `Date` header: successes, errors, empty lists and session or list reads. It needs no new request. The console persists the latest skew in `billing_clock` (`observed_at`, `skew_seconds`). A headerless failure (a timeout before headers) records nothing.
+ - **A clock off by more than 5 minutes** refuses every resend and every restore, and opens a `clock_skew` billing problem (account 0) once, until an observation within 5 minutes closes it automatically.
+ - **Every resend path makes a provider read in the same request before it resends,** so the observation is fresh:
+ - an operation reads its subscription;
+ - a Checkout create reads `CustomerCheckouts`;
+ - an expiry reads the session;
+ - a customer create runs inside the Checkout POST, after its exhaustive `LiveSubscriptions` read.
- 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.
@@ -87,9 +96,9 @@ Read with `stripe docs` on 2026-10-25. API v1, which is what the 6a client calls
- 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`.
+ - compares the item's current quantity with the baseline. Above it, `Store.FlagRestoreCheck` sets the obligation `flagged` **and** opens `restore_after_renewal` ("item %s is at %d, the renewal billed %d") **in one transaction**. If either write fails, neither commits, and the obligation stays `open` for the next observation. 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.
+ - An obligation still `open` 7 days after the renewal opens `restore_check_stalled` for an operator. The obligation stays `open` (still retried), so a lost problem write is retried too.
- 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: granted by Paul (Call 18, 2026-10-25).
- **R2. A late Checkout session** after its create was abandoned (Invariant 1's exception).
@@ -142,7 +151,7 @@ Also binding:
## Base branch, order and 6a's names
-- Cut from `plans-6-checkout` (6a) at `f4ce6bda`. **Rebase onto main after 6a merges,** before Task 1. Until then, merge `origin/plans-6-checkout` and `origin/main`, build Tasks 0 to 2 only (they touch only `internal/plans`), and stop before Task 3.
+- Cut from `plans-6-checkout` (6a) at `f4ce6bda`. **6a is merged on main as `7f79385e`.** Rebase this branch onto `origin/main` before Task 1. Only this plan file and its review notes differ from 6a's branch, so the rebase is mechanical.
- **6a's merged names, which this plan uses:**
| Name | Notes |
@@ -151,13 +160,18 @@ Also binding:
| `applyBillingPlan` | |
| `transitionAccountPlan(ctx, acct, now, write func(old *AccountPlanRow) (bool, error))` | |
| `Store.SaveBillingSync(next, accountID, plan, markLapse, resetCaps, now)` | |
- | `syncSubscription` | takes the billing lock |
- | `applyBillingRead` | the caller holds it |
- | `subscriptionMissing`, `endMissingSubscription` | |
+ | `syncSubscription(ctx, subscriptionID, now)` | takes the billing lock itself (`s.billing.locks.lock` at `billingsync.go:192`); 6b splits it into lookup → `holdBilling` → `syncSubscriptionLocked` |
+ | `applyBillingRead(ctx, acct, prev, sub, now)` | the caller holds the lock |
+ | `subscriptionMissing(subscriptionID, now)` | |
+ | `endMissingSubscriptionLocked(ctx, acct, subscriptionID, now)` | **its caller already holds the lock** (`closeBillingProblemLocked`); 6b adds a `billingHold` first parameter |
+ | `closeBillingProblemLocked(ctx, p, addr, note, now)` (`apibilling.go`) | despite its name, it **takes** the billing lock itself (`apibilling.go:177`). 6b changes that line to `holdBilling` and passes the hold down. The lint keys on a `billingHold` parameter, not on the name, so 6a's name is kept |
+ | `Store.OpenBillingProblem(accountID, subscription, reason, detail, now)` | 6b factors its statement into `openBillingProblemTx(e sqlExecer, ...)` so other transactions can share it |
+ | `billingDoor(w, r)` | operator door gate |
+ | `Provider.CustomerSubscriptions` | capped, single page; deleted by Task 5 after discovery is migrated |
| `billingDiscoveryPass`, `DiscoverableBillingAccounts` | |
| `billingReadyCheck`, `StartBillingSyncPass` | |
| `s.billing.locks` | `keyedLocks` by sqid |
-- **6a's round-2 fix pass** is assumed to change discovery, pending-replacement adoption and the closing of `subscription_missing`, all under the billing lock. Use its merged names where they differ, and note the ruling in the ledger. 6b only adds hooks:
+- **These are checked against merged main `7f79385e`** (6a, "Checkout core"). Where a later main differs, use main's names and note the ruling in the ledger. 6b only adds hooks:
- seats in `decideBilling`;
- operation settlement and the late-restore check after `applyBillingRead`;
- intent observation in discovery.
@@ -285,6 +299,7 @@ Also binding:
| 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** |
+ - **No request is made for time.** The clock observation rides on the responses already counted above.
- 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, 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.**
@@ -609,7 +624,12 @@ Also binding:
| other 4xx | `ErrRefused` |
| 5xx | `ErrIndeterminate` |
| transport error or timeout | `ErrNoResponse` |
-- **The house coupon** moves from `ProviderConfig` to `BillingConfig.HouseCoupon`. The console resolves it into `CheckoutRequest.Coupon` when it creates an intent. Readiness still verifies the configured coupon: valid, this mode, 100% off, no `amount_off`, `forever`, unrestricted.
+- **The house coupon, from where it lives on main.** Today it is a client parameter, `CreateCheckoutParams.HouseCoupon` (`client.go:548`), sent as `discounts[0][coupon]` (`client.go:614`). `ProviderConfig` has no coupon field.
+ - `CARLOS_STRIPE_HOUSE_COUPON` is read once into `BillingConfig.HouseCoupon` (console) and a new `ProviderConfig.HouseCoupon` (adapter, readiness only).
+ - When the console creates an intent for a house account, it copies `BillingConfig.HouseCoupon` into `CheckoutRequest.Coupon`.
+ - `PrepareCheckout` fills `CreateCheckoutParams.HouseCoupon` from `CheckoutRequest.Coupon` and encodes the body. The coupon id is therefore frozen in the `Prepared` bytes.
+ - Readiness verifies `ProviderConfig.HouseCoupon`: valid, this mode, 100% off, no `amount_off`, `forever`, unrestricted.
+- **The clock hook.** `ProviderConfig.ObserveTime func(provider, local time.Time)` is called for every HTTP response with a parseable `Date` header, from `Client.do`. The console wires it to `Store.NoteProviderClock`.
- **The portal check:** active; this mode; payment method update on; invoice history on; subscription update and cancel off; customer update off or limited to address, name and tax id.
- `LiveSubscriptions` and `CustomerCheckouts` page with `starting_after` over every status, up to 10 pages. `RenewalInvoice` lists the subscription's invoices with `billing_reason=subscription_cycle` and a period start equal to the one given, then pages its lines exhaustively.
- **Discovery is migrated:** 6a's `billingDiscoveryPass` calls `LiveSubscriptions`. On `ErrIncomplete` it logs and changes nothing; it is an observing net. `CustomerSubscriptions` is deleted.
@@ -622,6 +642,7 @@ Also binding:
func TestSendVerbatimOneRequest(t *testing.T) // 500 or timeout: one HTTP request, body equals Prepared.Body
func TestOutcomeClasses(t *testing.T) // one case per table row
func TestReplayedAndProviderTime(t *testing.T)
+ func TestObserveTimeOnEveryResponse(t *testing.T) // success, 4xx, 5xx, empty list: hook called; transport timeout: not called
func TestLiveSubscriptionsPagesToCompletion(t *testing.T) // 200 ended + 1 active on page 3: 3 requests
func TestLiveSubscriptionsEmptyListIsOneRequest(t *testing.T)
func TestLiveSubscriptionsIncomplete(t *testing.T)
@@ -713,12 +734,13 @@ Also binding:
**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` (which first adopts orphaned `sending` rows), then `restoreCheckLocked` for every open obligation of the subscription;
+ - `billingsync.go`: lookup → `holdBilling` → `syncSubscriptionLocked`; `endMissingSubscriptionLocked` takes the `billingHold`; 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`);
- `billingstore.go` (problem reasons `operation_unresolved`, `restore_after_renewal`);
- - `apibilling.go` (the `operation_unresolved` close branch);
+ - `apibilling.go`: `closeBillingProblemLocked` takes the hold through `holdBilling` instead of `s.billing.locks.lock`, plus the `operation_unresolved` close branch;
+ - `billingstore.go`: `openBillingProblemTx`, `FlagRestoreCheck`, `StallRestoreCheck`, `NoteProviderClock`, `ProviderClock`, and the `billing_clock` table (one row, `NonApp`: "the console's latest observed clock skew against the billing provider; names no app");
- the claim entries.
**Interfaces:**
@@ -729,8 +751,12 @@ Also binding:
func (s *Server) syncSubscriptionLocked(h billingHold, ctx context.Context, acct *Account, subscriptionID string, now time.Time) error
func (s *Server) refreshLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) (*billingAccount, *billing.Subscription, error)
func (s *Server) allowanceLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) (*billingAccount, *billing.Subscription, billing.Purchase, error)
- const (restoreMargin = 25 * time.Hour; resendLifetime = 23 * time.Hour; periodMargin = time.Hour; maxSkew = 5 * time.Minute; handlerRetries = 3)
- func skewOK(sub *billing.Subscription, now time.Time) bool // |now - sub.ProviderTime| <= maxSkew
+ const (restoreMargin = 25 * time.Hour; resendLifetime = 22 * time.Hour; periodMargin = time.Hour; maxSkew = 5 * time.Minute; clockFreshness = 10 * time.Minute; handlerRetries = 3)
+ func skewOK(sub *billing.Subscription, now time.Time) bool // restores only: the read has a Date header and |now - sub.ProviderTime| <= maxSkew
+ type clockState struct { ObservedAt time.Time; Skew time.Duration }
+ func (s *Store) NoteProviderClock(provider, local time.Time) error // billing_clock: one row; opens or closes clock_skew in the same transaction
+ func (s *Store) ProviderClock() (clockState, error)
+ func clockTrusted(c clockState, consoleNow time.Time) bool // |Skew| <= maxSkew && consoleNow-ObservedAt <= clockFreshness
const (opSending = "sending"; opUnresolved = "unresolved"; opPending = "pending"; opApplied = "applied"; opFailed = "failed"; opAbandoned = "abandoned")
func opOutstanding(state string) bool // sending | unresolved | pending (Invariant 7)
type billingOp struct {
@@ -745,7 +771,7 @@ Also binding:
Indeterminate bool
FirstSentAt, LastSentAt, SettledAt time.Time
}
- func (op billingOp) resendUntil(providerNow time.Time) time.Time // min(FirstSentAt+resendLifetime, PeriodEnd-periodMargin)
+ func (op billingOp) resendUntil() time.Time // console time: min(FirstSentAt+resendLifetime, PeriodEnd-periodMargin)
func (s *Store) BeginBillingOp(op billingOp) error // ErrOpOutstanding when an opOutstanding row holds the subscription
func (s *Store) MarkOpApplied(opID string, now time.Time) error // the only route to applied; consumes AuthorisedBy in the same transaction
func (s *Store) PutBillingOpState(opID, state string, indeterminate bool, now time.Time) error
@@ -754,12 +780,17 @@ 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
- 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
+ type resendState struct { State string; Indeterminate bool; FirstSent, ResendUntil time.Time; ContextCurrent bool; Restore bool; RestoreRead *billing.Subscription }
+ func recoveryEligible(r resendState, clock clockState, 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 *Store) PutRestoreCheck(c restoreCheck) error // open or clear only
+ // FlagRestoreCheck sets the obligation flagged and opens restore_after_renewal through openBillingProblemTx, in one
+ // transaction (finding 1). StallRestoreCheck records stalled_at and opens restore_check_stalled the same way, leaving it open.
+ func (s *Store) FlagRestoreCheck(opID, detail string, now time.Time) error
+ func (s *Store) StallRestoreCheck(opID string, now time.Time) error
+ func openBillingProblemTx(e sqlExecer, accountID int64, subscription, reason, detail string, now time.Time) (bool, 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
@@ -787,8 +818,8 @@ Also binding:
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`.
+ 4. With a baseline: an item quantity above it, not explained by an `applied` op sent in the new period, is `FlagRestoreCheck`, one transaction for the flag and the problem. Otherwise, if the operation is terminal, `clear`; if not, stay `open`.
+ 5. Open longer than 7 days after the renewal: `StallRestoreCheck`.
It writes nothing to the provider.
- **The observation pass:**
@@ -841,12 +872,20 @@ Also binding:
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 TestRestoreCheckStalls(t *testing.T) // failures for 7 days: restore_check_stalled; obligation still open
+ func TestFlagAndProblemCommitTogether(t *testing.T) // a SQLite trigger fails the problem insert: obligation still open, no problem; restart; next observation:
+ // flagged and restore_after_renewal together
+ func TestHeaderlessTimeoutThenRestartWithSkew(t *testing.T) // op send times out before headers (no clock note); restart with the console clock +10 min;
+ // Confirm now: the subscription read notes skew 10 min: no resend, clock_skew opened; clock fixed: next read closes it, resend allowed
+ func TestCustomerResendUsesConsoleWindow(t *testing.T) // customer create timed out headerless; Checkout POST 21 h later: LiveSubscriptions notes good skew; resend allowed;
+ // at 22 h 1 m: no resend, a new attempt key only after the window (R3)
+ func TestStaleClockObservationRefusesResend(t *testing.T) // last observation 11 min old and no read in this request: refused (every path reads first, so this is a guard)
+ func TestRestoreNeedsDateHeader(t *testing.T) // a restore's read without Date: change.clock, no send
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|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 2: Run** `go test ./internal/console/ -run 'BillingLockedHelpers|ConsoleBillingHasNo|OpOutstanding|RecoveryEligible|FlagAndProblem|HeaderlessTimeout|CustomerResendUses|StaleClock|RestoreNeedsDate|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 and one recovery gate; orphaned sends recovered; durable late-restore obligations; passes only read (plans 6b)`.
@@ -980,11 +1019,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) 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.
+ 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` (console-time window `CustomerFirstSentAt + 22 h`; the Checkout POST's `LiveSubscriptions` read just before supplies the clock observation). 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: 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.
+ 2. Send, with handler retries: an exhaustive `CustomerCheckouts` read looking for the intent id, then the same bytes, while `recoveryEligible` (console-time window `min(FirstSentAt + 22 h, ExpiresAt)`, context: not expired; the `CustomerCheckouts` read supplies the clock observation). 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).
@@ -1364,6 +1403,14 @@ CLI: `carlos billing house -account <sqid> -on|-off -note "..."`, console mode o
| 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 | Granted by Paul (Call 18, 2026-10-25). |
+**Round 6** (`09060b49`):
+
+| Finding | Revision 7 |
+| --- | --- |
+| 1. flagging can lose its problem | `Store.FlagRestoreCheck` writes the flag and the problem in one transaction through `openBillingProblemTx` (factored from 6a's `OpenBillingProblem`), so a failure leaves the obligation open and retried. Stalling leaves it open too (`TestFlagAndProblemCommitTogether`). |
+| 2. recovery needs provider time some branches can't get | Provider time is required only for restores, from the subscription read before each restore send. Every other resend deadline is console time, `FirstSent + 22 h`, justified against the 5-minute skew bound (1 h 55 min inside Stripe's 24 h). A clock hook on every provider response records skew in `billing_clock`. More than 5 minutes off, or older than 10 minutes, refuses all resends and opens `clock_skew`. Every resend path reads in the same request first, with no new requests (`TestHeaderlessTimeoutThenRestartWithSkew`, `TestCustomerResendUsesConsoleWindow`). |
+| 3. 6a names | Re-checked against main `7f79385e`: `endMissingSubscriptionLocked(ctx, acct, subscriptionID, now)`, whose caller holds the lock; `closeBillingProblemLocked` takes the lock itself, and 6b moves it to `holdBilling`; the house coupon moves from `CreateCheckoutParams.HouseCoupon`, not `ProviderConfig`; `OpenBillingProblem`, `billingDoor` and `CustomerSubscriptions` are listed. |
+
---
## Plan 6c: Stripe setup runbook (outline)