carlos / platform Public

plans 6b: revision 8 after Astra's round 7. The console's wall clock leaves every billing safety decision: first-send stamps, recovery deadlines, margins, expires_at and proration_date are provider time (a response Date at most 60 s old plus monotonic elapsed), with one price-GET clock probe where a path has no read; the skew record and clock_skew are deleted; closeBillingProblem wraps closeBillingProblemLocked so no Locked function takes a lock

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

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 c1738c3de..0f2cb9ecf 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,13 @@
A static pricing page links to one stable console URL, which takes a signed-out visitor through sign-in or sign-up first.
-**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 8 (2026-10-26)** answers Astra's round 7 (`plans6b-plan-review-r7.md`, at `a0654af6`). **The console's wall clock is taken out of every billing safety decision.**
+- Every deadline, first-send stamp, restore margin, `expires_at` and `proration_date` is **provider time**: the `Date` of a provider response seen in the same request no more than 60 s earlier, plus the monotonic time since.
+- A path with no such read makes **one clock probe**: a GET of one configured price.
+- The skew record, its refusal rule and the `clock_skew` problem are deleted.
+- The lock-taking close wrapper is renamed so that no `*Locked` function takes a lock.
-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.
+Revision 7 made flagging transactional and corrected 6a's names against main `7f79385e`. Revision 6 added durable restore obligations and crash recovery of `sending` rows. 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.
@@ -56,8 +57,7 @@ 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, 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`.
+ - A restore (a `ProrateNone` raise up to the period's paid quantity) is first sent, or resent, only when `periodEnd − providerNow > 25 h`. Here `providerNow` comes from the subscription read that precedes that send in the same request (Invariant 9). With no provider time available, it refuses (`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,28 +66,41 @@ 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, 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:
+ - `recoveryEligible(r resendState, providerNow 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`;
- - `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.
+ - `providerNow < r.FirstSent + 22 h`, and for subscription operations also `providerNow < PeriodEnd − 1 h`;
+ - for a restore, Invariant 4's margin on the same `providerNow`;
+ - its context is still current: the invite is still pending, and the intent's provider-time `ExpiresAt` has not passed.
+
+ `providerNow` comes from Invariant 9. With none available, nothing is sent.
+ - The observation pass escalates exactly the rows that are outstanding, not `pending`, and **permanently ineligible**: indeterminate, or past their window by the pass's own provider time. The pass makes reads anyway, so it has provider time; if it has none, it escalates nothing that round.
+9. **Provider time, never the console's wall clock, in every billing safety decision.**
+ - **Where it comes from.** A request-scoped recorder (`billing.WithClock(ctx, rec)`) receives the `Date` header of every provider response the adapter gets in that request (`Client.do` calls `billing.ObserveDate(ctx, date)`), together with a **monotonic** local reading taken on receipt.
+ - `rec.Now()` returns `date + monotonic elapsed since`, valid only while that observation is at most 60 s old by the monotonic clock. Otherwise `errNoProviderTime`.
+ - The monotonic reading never leaves the process. After a restart the recorder starts empty.
+ - **The probe.** When a decision needs provider time and the recorder has none (customer creation on a first purchase; a quiet recovery with no customer id; a pass round before any read), the path makes **one clock probe**: `Provider.ClockProbe`, a GET of the first configured price (Prices read is already granted, and it needs no customer). A headerless or failed probe means no provider time, and nothing is sent.
+ - **What uses it:**
+ - every `FirstSentAt` (operations, customer creates, Checkout creates, expiries), stamped from `rec.Now()` immediately before the first send;
+ - every recovery deadline (`providerNow < FirstSentAt + 22 h`);
+ - the operation period margin (`providerNow < PeriodEnd − 1 h`);
+ - the restore margin;
+ - a Checkout's `expires_at` (`providerNow + 1 h`) and the continue check (`ExpiresAt > providerNow + 5 min`);
+ - every `proration_date` frozen into a `Prepared`.
+ - **Why 22 hours is safe.**
+ - Stripe keeps a key "for at least 24 hours" from the original request (fact 6), on Stripe's clock.
+ - `FirstSentAt` is a provider timestamp taken before the send. It can only be **earlier** than Stripe's receipt (by network latency and the `Date` header's one-second resolution), which shortens our window and never lengthens it.
+ - A recovery's `providerNow` underestimates true provider time by at most the observation's one-way latency (seconds). That is the only direction that lengthens our window.
+ - The total error is a few seconds against a 2-hour margin. A wrong console wall clock, a corrected clock or a restart cannot move either endpoint.
+ - **No wall clock** appears in these decisions. The skew record, `clockTrusted`, the skew refusal and the `clock_skew` problem are deleted. The adapter may log the observed skew at debug level as a diagnostic only.
+ - **Console-local timers stay on console time**, because they are not compared with any Stripe time: the retirement row's 1 h staleness, the 7-day restore-check stall alert, the daily `seats_unpaid` re-check and the in-handler backoff.
- 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.
+ - The 25 h margin and the `period end − 1 h` resend cut-off, both in provider time, 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: 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`.
@@ -163,8 +176,8 @@ Also binding:
| `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 |
+ | `endMissingSubscriptionLocked(ctx, acct, subscriptionID, now)` | **its caller already holds the lock**; 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 splits it**: a new wrapper `closeBillingProblem(ctx, p, addr, note, now)` takes `holdBilling` and calls `closeBillingProblemLocked(h, ctx, p, addr, note, now)`, which no longer locks. 6a's callers move to the wrapper. |
| `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 |
@@ -244,7 +257,7 @@ Also binding:
- **Locks: member → billing → lapse → store.**
- `s.memberLocks` is keyed by sqid.
- The billing lock is taken only through `holdBilling`.
- - Functions named `*Locked` take a `billingHold` first and never lock; an AST test enforces it.
+ - **Every** function named `*Locked` takes a `billingHold` first and never takes a lock. `TestBillingLockedHelpersNeverLock` enforces that globally, by name, across `internal/console`, including 6a's renamed `closeBillingProblemLocked` and `endMissingSubscriptionLocked`.
- Timeout tests use 15 s.
- **Granted once paid.** Charges are `ProrateNow` (`always_invoice` + `pending_if_incomplete`). Reductions and restores are `ProrateNone`.
- **Idempotency keys**, each stored inside its `Prepared`:
@@ -271,6 +284,7 @@ Also binding:
- **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.
+ - `P`: one clock probe (a price GET), **only** on a path with no provider response in the last 60 s: customer create on a first purchase, customer-create recovery, and a pass round before its first read. Every other branch already reads.
- `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 |
@@ -278,7 +292,8 @@ Also binding:
| 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 + N) + create (1 + N × (L(c) + 1)) |
+ | Confirm now | unresolved customer create (no customer id) | `P` + at most 1 resend |
+ | Checkout start | first purchase | `S` (recorded subscription, if any) + `L(all subs)` (only with a bound customer) + `P` when neither read happened + 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 + 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 |
@@ -299,7 +314,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.
+ - **Time costs a request only through `P`.** Everywhere else, provider time rides on responses already counted.
- 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.**
@@ -317,7 +332,7 @@ Also binding:
- cached 5xx before and after applying; 409 in flight; 429;
- renewal across a period boundary, with a renewal invoice;
- **a request that first applies after a renewal**;
- - provider time and skew; paging; Checkout races; call counts by method.
+ - provider time separate from the test's console wall clock, with an injectable monotonic clock; paging; Checkout races; call counts by method.
## Review Focus
@@ -569,7 +584,7 @@ Also binding:
- `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.
+ - `ProviderClock` (the time in every response's `Date`) is independent of the console's injected wall clock (`SetConsoleClock`) and of an injected monotonic source (`AdvanceMonotonic`); `HeaderlessTimeout` fails before headers; `PageSize`; Checkout sessions and races; `CallsBy` per method (the probe is counted as `ClockProbe`).
- [ ] **Step 1: Write the failing tests**
```go
@@ -629,7 +644,7 @@ Also binding:
- 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`.
+- **Provider time.** `Client.do` calls `billing.ObserveDate(ctx, date)` for every HTTP response with a parseable `Date` header, whatever its status, empty lists included. The request-scoped recorder installed by the console (`billing.WithClock`) keeps it with a monotonic receipt reading. `Provider.ClockProbe(ctx)` GETs `/v1/prices/<first configured price id>`, returns nothing but feeds the recorder, and is counted as one request. The adapter may log the observed skew at debug level; nothing reads that log.
- **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.
@@ -642,7 +657,8 @@ 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 TestObserveDateOnEveryResponse(t *testing.T) // success, 4xx, 5xx, empty list: recorder fed; transport timeout before headers: not fed
+ func TestClockProbeIsOnePriceGet(t *testing.T) // GET /v1/prices/<first>; recorder fed; CallsBy[ClockProbe] == 1
func TestLiveSubscriptionsPagesToCompletion(t *testing.T) // 200 ended + 1 active on page 3: 3 requests
func TestLiveSubscriptionsEmptyListIsOneRequest(t *testing.T)
func TestLiveSubscriptionsIncomplete(t *testing.T)
@@ -668,7 +684,7 @@ Also binding:
```go
// billingAccount gains Plan; Seats (current team quantity); PaidSeats (the period's highest paid); Live, Collecting,
// PendingUpdate; PendingExpires; SeatsCheckedAt; SeatDriftAt, SeatDriftMembers; CustomerAttempt int;
- // CustomerPrepared *billing.Prepared; CustomerFirstSentAt.
+ // CustomerPrepared *billing.Prepared; CustomerFirstSentAt (provider time, Invariant 9).
// planChange gains Seats (0 for non-team plans).
func billingRenewing(b *billingAccount) bool // Live && !CancelAtPeriodEnd
type checkoutIntent struct {
@@ -739,8 +755,9 @@ Also binding:
- `server.go`: `POST /a/{sqid}/billing/confirm`;
- `store_gate.go` (`billing_operations`);
- `billingstore.go` (problem reasons `operation_unresolved`, `restore_after_renewal`);
- - `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");
+ - `apibilling.go`: a new `closeBillingProblem` wrapper takes `holdBilling` and calls `closeBillingProblemLocked(h, ...)`, which no longer locks; plus the `operation_unresolved` close branch;
+ - `billingstore.go`: `openBillingProblemTx`, `FlagRestoreCheck`, `StallRestoreCheck`;
+ - `internal/billing/clock.go` (new): `WithClock`, `ObserveDate`, the recorder;
- the claim entries.
**Interfaces:**
@@ -751,12 +768,14 @@ 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 = 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 (restoreMargin = 25 * time.Hour; resendLifetime = 22 * time.Hour; periodMargin = time.Hour; observationMaxAge = 60 * time.Second; handlerRetries = 3)
+ // package billing (clock.go):
+ type ClockRecorder struct { /* last Date, monotonic receipt reading; injectable monotonic source for tests */ }
+ func WithClock(ctx context.Context, r *ClockRecorder) context.Context
+ func ObserveDate(ctx context.Context, date time.Time) // called by the adapter on every response with a Date header
+ func (r *ClockRecorder) Now() (time.Time, error) // date + monotonic elapsed; errNoProviderTime past observationMaxAge
+ // package console:
+ func (s *Server) providerNow(ctx context.Context) (time.Time, error) // the recorder, else one ClockProbe, else errNoProviderTime
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 {
@@ -771,7 +790,7 @@ Also binding:
Indeterminate bool
FirstSentAt, LastSentAt, SettledAt time.Time
}
- func (op billingOp) resendUntil() time.Time // console time: min(FirstSentAt+resendLifetime, PeriodEnd-periodMargin)
+ func (op billingOp) resendUntil() time.Time // provider 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
@@ -780,8 +799,8 @@ 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; Restore bool; RestoreRead *billing.Subscription }
- func recoveryEligible(r resendState, clock clockState, 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; PeriodEnd time.Time }
+ func recoveryEligible(r resendState, providerNow time.Time) (bool, string) // Invariant 8; the only resend gate; all times provider time
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)
@@ -796,7 +815,7 @@ Also binding:
func billingCheckDelay(failures int) time.Duration
```
- **`sendOpLocked`:**
- 1. `BeginBillingOp` (`sending`, with `Prepared`).
+ 1. `BeginBillingOp` (`sending`, with `Prepared`, and `FirstSentAt = providerNow` from the read that precedes it in this request; with no provider time, nothing is written or sent and the request answers `change.clock`).
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 `recoveryEligible`.
4. Record the outcome:
@@ -807,7 +826,7 @@ Also binding:
- otherwise: `unresolved`.
- **`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 `recoveryEligible` is false (indeterminate, past the window, skew, or an invite no longer pending): no send.
+ 2. If `recoveryEligible(r, providerNow)` is false (indeterminate, past the provider-time window, no provider time, 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`;
@@ -855,7 +874,7 @@ Also binding:
func TestWindowClosesToOperator(t *testing.T)
func TestNoResendAfterKeyLifetime(t *testing.T)
func TestNoResendAfterPeriodMargin(t *testing.T)
- func TestNoResendWithClockSkew(t *testing.T) // SkewBy(6m): read only, no send
+ func TestNoProviderTimeNoSend(t *testing.T) // the read and the probe both headerless: nothing sent; the op stays unresolved
func TestPendingNeverEscalates(t *testing.T)
func TestPendingExpiryAbandons(t *testing.T)
func TestOperatorCloseNeedsEvidence(t *testing.T)
@@ -875,17 +894,22 @@ Also binding:
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 TestFirstSendUnderSkewThenLateRecoveryRefused(t *testing.T) // console wall clock 3 h ahead; renewal op first sent (FirstSentAt from the provider Date, correct);
+ // the wall clock corrected; restart; the provider clock advances 24.5 h; Confirm now: the read gives providerNow,
+ // FirstSentAt + 22 h has passed: no resend (CallsBy writes == 1), the pass opens operation_unresolved
+ func TestFirstSendUnderSkewRecoveryInsideWindow(t *testing.T) // the same skew, recovery at provider + 21 h: resend allowed; console clock irrelevant both ways
+ func TestQuietCustomerRecoveryUsesProbe(t *testing.T) // first purchase: customer create times out before headers; 11 quiet minutes, no restart; Checkout POST:
+ // no customer, so no list read; recorder empty: one ClockProbe, then the same bytes once; bound;
+ // CallsBy == {ClockProbe: 1, Send: 2}
+ func TestHeaderlessTimeoutRecoveredThroughProbe(t *testing.T) // customer create times out before headers; Confirm now 2 min later (observation > 60 s old): probe, resend, bound
+ func TestObservationOlderThan60sIsNotUsed(t *testing.T) // AdvanceMonotonic(61s) after the last read: providerNow probes
+ func TestRestoreNeedsProviderTime(t *testing.T) // a restore whose read has no Date and whose probe fails: change.clock, no send
+ func TestExpiresAtAndProrationDateUseProviderTime(t *testing.T) // console wall clock 3 h off: expires_at == providerNow + 1 h; proration_date == providerNow
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|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 2: Run** `go test ./internal/console/ -run 'BillingLockedHelpers|ConsoleBillingHasNo|OpOutstanding|RecoveryEligible|FlagAndProblem|FirstSendUnderSkew|QuietCustomerRecovery|HeaderlessTimeoutRecovered|ObservationOlder|RestoreNeedsProviderTime|ExpiresAtAndProration|NoProviderTime|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)`.
@@ -1018,12 +1042,12 @@ Also binding:
func (s *Server) billingIntentPass(ctx context.Context, now time.Time)
```
- **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` (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.
+ 1. The first attempt prepares `PrepareCustomer(sqid, "customer:<sqid>:1")` and stores it on the billing row with `CustomerFirstSentAt = providerNow` (the recorder, else one `ClockProbe`) before sending. With no provider time, nothing is sent.
+ 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(r, providerNow)` (provider-time window `CustomerFirstSentAt + 22 h`). There is no customer id to read, so `providerNow` comes from the recorder (any response in the last 60 s of this request) or one `ClockProbe`. `CustomerFirstSentAt` itself was stamped the same way before the first send. 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` (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.
+ 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 `expires_at = providerNow + checkoutLifetime` (provider time, so a wrong console clock cannot make Stripe refuse or mis-time it).
+ 2. Send, with handler retries: an exhaustive `CustomerCheckouts` read looking for the intent id, then the same bytes, while `recoveryEligible(r, providerNow)` (provider-time window `min(FirstSentAt + 22 h, ExpiresAt)`, context: not expired). The `CustomerCheckouts` read supplies `providerNow`. 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).
@@ -1040,7 +1064,7 @@ Also binding:
- same request and open: 303 to its URL;
- Start over or a different request: `replaceIntentLocked`.
7. `ensureCustomerLocked`, then put and create the new intent.
-- **Continue (GET):** owner. A session read: open and `ExpiresAt > now + 5 min` gives a 303 to its URL; otherwise a flash and back.
+- **Continue (GET):** owner. A session read: open and `ExpiresAt > providerNow + 5 min` (the read's provider time) gives a 303 to its URL; otherwise a flash and back.
- **Done:** owner; the intent named by the session; mark returned; observe; then 303.
- **The pass:** open intents get a session read; creating intents past `ExpiresAt` get a `CustomerCheckouts` read. **0 writes.**
- Draft copy:
@@ -1102,11 +1126,11 @@ Also binding:
4. `allowanceLocked`.
5. **pack:** `quantityPlan(current, target, PaidPacks[name])`:
- a reduction is one `opPack` with `ProrateNone`;
- - a restore needs `PeriodEnd − sub.ProviderTime > restoreMargin` and `skewOK`, else the whole request is refused (`change.near_renewal` or `change.clock`);
+ - a restore needs `PeriodEnd − providerNow > restoreMargin`, with `providerNow` from the allowance read, else the whole request is refused (`change.near_renewal`, or `change.clock` when no provider time is available);
- a charge is computed only after a definite applied restore.
6. **plan (Call 4):** one swap with `ProrateNow`, at `Billed(MemberCount)` or 1. The target must be higher in the configured book and offer every held pack.
7. No step: `change.none`. A charge without `confirmed`: release, then the confirm page with `prorateEstimate`.
- 8. The proration timestamp is captured once, in the `Prepared`.
+ 8. The proration timestamp is `providerNow`, captured once, in the `Prepared`.
9. Settle, then flash.
- **Renewal:** owner, CSRF, `holdBilling`, then refuse when retiring. Finish outstanding ops, `refreshLocked`, then one `opRenewal` via `sendOpLocked`, then settle.
- Draft copy:
@@ -1136,7 +1160,7 @@ Also binding:
func TestPackReduceAndBuyBack(t *testing.T)
func TestDeletedPackRestoreThenCharge(t *testing.T) // 0 -> restore 3 (si_n from the response) -> charge si_n to 4; two ops
func TestRestoreRefusedNearRenewal(t *testing.T) // ProviderTime = PeriodEnd - 24h: refused, no write
- func TestRestoreRefusedOnClockSkew(t *testing.T)
+ func TestRestoreIgnoresConsoleClock(t *testing.T) // console wall clock 2 days behind: the margin uses providerNow; refused at provider PeriodEnd - 24h
func TestRestoreResendWindowEndsBeforeRenewal(t *testing.T)
func TestOneOutstandingOperation(t *testing.T)
func TestRetryAfterDeclineIsRefusedUntilSettled(t *testing.T)
@@ -1154,7 +1178,7 @@ Also binding:
- [ ] **Step 2: Run** `go test ./internal/console/ -run 'Pack|DeletedPack|Restore|OneOutstanding|RetryAfterDecline|ChangeTwice|ChangeComputes|ChangeAfter|ChangeUnresolved|PlanUpgrade|UpgradeRefused|ChangeUses|Renewal|ChangeAndRenewal'`. Expected: FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4: Run** again, plus the claim suite. Expected: PASS.
-- [ ] **Step 5: Commit** `console: pack changes and upgrades as prepared operations; no restore near renewal or on clock skew; stop and resume renewal (plans 6b)`.
+- [ ] **Step 5: Commit** `console: pack changes and upgrades as prepared operations; no restore within 25 provider-time hours of renewal; stop and resume renewal (plans 6b)`.
### Task 11: Seats: authorised invites, admission, revocation, drift
@@ -1191,7 +1215,7 @@ Also binding:
3. Billing team: `holdBilling`, then refuse when retiring. `finishOpLocked` each outstanding op of the subscription. Still outstanding: this invite's `pending` op gives `admitWaitPayment`; anything else gives `admitOutstanding`.
4. `allowanceLocked`. Then **use available capacity first, never reduce:** `need = Billed(members+1)`, `cur` = the plan item's quantity, `paid = PaidSeats`.
- `need ≤ cur`: free, with no write. This covers a paid seat left by an earlier credit, even inside the renewal margin.
- - `cur < need ≤ paid`: a restore, needing the margin and skew rules, else `admitNearRenewal`.
+ - `cur < need ≤ paid`: a restore, needing the provider-time margin, else `admitNearRenewal`.
- `need > paid`: `seatCovered`, else `admitNeedsConsent`. Then a restore if `paid > cur` (margin rules), then the `opSeat` charge with `AuthorisedBy` and `InviteToken`, only after a definite applied restore.
5. `membershipTransition(acceptInviteTx)`, then settle.
6. `reconcileSeatsLocked(h, ctx, acct, members+1)`, **never reducing at a join**: it only opens or closes `seats_unpaid`.
@@ -1411,6 +1435,14 @@ CLI: `carlos billing house -account <sqid> -on|-off -note "..."`, console mode o
| 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. |
+**Round 7** (`a0654af6`):
+
+| Finding | Revision 8 |
+| --- | --- |
+| inherited 2 (customer recovery has no clock refresh without a customer id) | A path with no provider response in the last 60 s makes one `ClockProbe` (a price GET, no customer needed), counted as `P` on those branches only (`TestQuietCustomerRecoveryUsesProbe`, with no restart; `TestHeaderlessTimeoutRecoveredThroughProbe`). |
+| 1. first-send stamps trust the wall clock | Invariant 9: every `FirstSentAt`, deadline, margin, `expires_at` and `proration_date` is provider time, a response `Date` at most 60 s old plus monotonic elapsed, so neither endpoint uses the console's wall clock. The skew record, its refusal rule and `clock_skew` are deleted (`TestFirstSendUnderSkewThenLateRecoveryRefused`: 3 h skew, correction, restart, recovery at provider + 24.5 h refused). |
+| 2. the lock-taking wrapper | `closeBillingProblem` takes `holdBilling` and calls `closeBillingProblemLocked(h, ...)`, which no longer locks. `TestBillingLockedHelpersNeverLock` enforces "every `*Locked` takes a hold and never locks" globally by name, unchanged. |
+
---
## Plan 6c: Stripe setup runbook (outline)