console: plans 6b task 7: an unknown start quantity never explains a raise; ops without one are refused
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+232
−22
internal/console/billinglate.go+7 −6internal/console/billinglate_test.go+120 −4internal/console/billinglint_test.go+39 −0internal/console/billingops.go+35 −8internal/console/billingops_test.go+26 −1internal/console/billingstore.go+5 −3
diff --git a/internal/console/billinglate.go b/internal/console/billinglate.go| index c122a22ae..201d2b1f8 100644 |
| --- a/internal/console/billinglate.go |
| +++ b/internal/console/billinglate.go |
| @@ -344,18 +344,19 @@ func (s *Server) restoreStallsForMissingLocked(h billingHold, ctx context.Contex |
| } |
| // raiseExplained reports whether a quantity above the renewal's baseline is |
| -// accounted for by an applied operation first sent in the new period that |
| -// started at or below the baseline and whose target reaches the quantity. |
| -// A charge built on top of a late-restored quantity starts above the |
| -// baseline and explains nothing, so the late restore under it is still |
| -// flagged. |
| +// accounted for by an applied operation first sent in the new period with a |
| +// recorded start at or below the baseline and a target that reaches the |
| +// quantity. A charge built on top of a late-restored quantity starts above |
| +// the baseline and explains nothing, so the late restore under it is still |
| +// flagged; nor does an operation whose start is unknown (one written before |
| +// starts were recorded), since nothing shows where it started. |
| func (s *Server) raiseExplained(subscription, price string, periodEnd time.Time, baseline, current int64) (bool, error) { |
| ops, err := s.store.AppliedOpsSince(subscription, periodEnd) |
| if err != nil { |
| return false, err |
| } |
| for _, op := range ops { |
| - if q, ok := op.Target.Quantities[price]; ok && q >= current && op.StartQuantity <= baseline { |
| + if q, ok := op.Target.Quantities[price]; ok && q >= current && op.StartQuantity != nil && *op.StartQuantity <= baseline { |
| return true, nil |
| } |
| } |
diff --git a/internal/console/billinglate_test.go b/internal/console/billinglate_test.go| index 8c9535b73..5eea72b41 100644 |
| --- a/internal/console/billinglate_test.go |
| +++ b/internal/console/billinglate_test.go |
| @@ -295,8 +295,8 @@ func TestRestoreCheckBaselineIgnoresLaterInvoices(t *testing.T) { |
| if out, _, err := o.send(t, o.packOp(t, "op_3", "sub_1", "apps", 4, billing.ProrateNow, opPack)); err != nil || out.State != opApplied { |
| t.Fatalf("charge = %+v %v", out, err) |
| } |
| - if row := o.op(t, "op_3"); row.StartQuantity != 1 { |
| - t.Fatalf("op_3 started at %d, want 1", row.StartQuantity) |
| + if row := o.op(t, "op_3"); row.StartQuantity == nil || *row.StartQuantity != 1 { |
| + t.Fatalf("op_3 started at %v, want 1", row.StartQuantity) |
| } |
| o.pass(billingNow.Add(time.Hour)) |
| if c := o.check(t, "op_1"); c.State != restoreClear || c.Baseline[c.Price] != 1 { |
| @@ -328,8 +328,8 @@ func TestLateRestoreThenChargeStillFlags(t *testing.T) { |
| if out, _, err := o.send(t, o.packOp(t, "op_2", "sub_1", "apps", 4, billing.ProrateNow, opPack)); err != nil || out.State != opApplied { |
| t.Fatalf("charge = %+v %v", out, err) |
| } |
| - if row := o.op(t, "op_2"); row.StartQuantity != 3 { |
| - t.Fatalf("op_2 started at %d, want 3", row.StartQuantity) |
| + if row := o.op(t, "op_2"); row.StartQuantity == nil || *row.StartQuantity != 3 { |
| + t.Fatalf("op_2 started at %v, want 3", row.StartQuantity) |
| } |
| o.pass(billingNow.Add(time.Hour)) |
| c := o.check(t, "op_1") |
| @@ -347,6 +347,122 @@ func TestLateRestoreThenChargeStillFlags(t *testing.T) { |
| } |
| } |
| +// dropStartColumn turns the store back into one created before |
| +// start_quantity existed, then runs the migration again, so every row |
| +// present gets the column's default as an old store would. |
| +func dropStartColumn(t *testing.T, st *Store) { |
| + t.Helper() |
| + if _, err := st.db.Exec(`ALTER TABLE billing_operations DROP COLUMN start_quantity`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := st.migrateBillingOperations(); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// The re-review's case: a charge from 3 to 4 applied over a renewal that |
| +// billed 1, on a store migrated after the charge was recorded. Its start is |
| +// unknown, and an unknown start explains nothing: the late restore under it |
| +// is flagged. |
| +func TestMigratedStartNeverExplains(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + o.heldRestore(t, "op_1", "sub_1") |
| + if err := o.fake.Renew("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.fake.InvoiceReadFails(1) |
| + o.pass(billingNow) |
| + if c := o.check(t, "op_1"); c.State != restoreOpen || c.Attempts != 1 { |
| + t.Fatalf("after the failed baseline read: %+v", c) |
| + } |
| + o.fresh() |
| + o.observe() |
| + if out, _, err := o.send(t, o.packOp(t, "op_2", "sub_1", "apps", 4, billing.ProrateNow, opPack)); err != nil || out.State != opApplied { |
| + t.Fatalf("charge = %+v %v", out, err) |
| + } |
| + dropStartColumn(t, o.st) |
| + if row := o.op(t, "op_2"); row.StartQuantity != nil { |
| + t.Fatalf("migrated start = %d, want unknown", *row.StartQuantity) |
| + } |
| + o.pass(billingNow.Add(time.Hour)) |
| + if c := o.check(t, "op_1"); c.State != restoreFlagged || c.Baseline[c.Price] != 1 { |
| + t.Fatalf("obligation = %+v", c) |
| + } |
| + if got := o.openProblems(t); !slices.Contains(got, problemRestoreAfterRenewal) { |
| + t.Fatalf("problems = %v", got) |
| + } |
| +} |
| + |
| +// An applied operation explains a raise above the baseline only with a |
| +// recorded start at or below it; a recorded 0 (a new item) is evidence, an |
| +// unknown start never is. |
| +func TestRaiseExplainedNeedsAKnownStart(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + cases := []struct { |
| + name string |
| + start *int64 |
| + baseline, after int64 |
| + want bool |
| + }{ |
| + {"recorded zero, a new item", knownStart(0), 0, 4, true}, |
| + {"recorded zero under the baseline", knownStart(0), 1, 4, true}, |
| + {"recorded at the baseline", knownStart(1), 1, 4, true}, |
| + {"recorded above the baseline", knownStart(3), 1, 4, false}, |
| + {"unknown", nil, 1, 4, false}, |
| + {"unknown, baseline zero", nil, 0, 4, false}, |
| + } |
| + for i, tc := range cases { |
| + t.Run(tc.name, func(t *testing.T) { |
| + sub := fmt.Sprintf("sub_raise_%d", i) |
| + op := billingOp{ID: "op_" + sub, AccountID: o.acct.ID, Subscription: sub, Kind: opPack, PeriodEnd: periodEnd.AddDate(1, 0, 0), |
| + Target: opTarget{Quantities: map[string]int64{"price_x": tc.after}}, StartQuantity: tc.start, |
| + Prepared: billing.Prepared{Kind: billing.PreparedChange, Method: "POST", Path: "/x", Key: "op:" + sub}, |
| + FirstSentAt: periodEnd.Add(time.Hour), CreatedAt: billingNow, State: opApplied} |
| + if err := o.st.BeginBillingOp(op); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := o.srv.raiseExplained(sub, "price_x", periodEnd, tc.baseline, tc.after) |
| + if err != nil || got != tc.want { |
| + t.Fatalf("explained = %v %v, want %v", got, err, tc.want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// The column's default is the unknown start, for a new store's rows written |
| +// without one and for an old store's rows on migration; a recorded 0 reads |
| +// back as 0. |
| +func TestStartQuantityColumnDefaultsToUnknown(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + if _, err := o.st.db.Exec(`INSERT INTO billing_operations (id, account_id, subscription, kind, period_end, target, prepared, state, created_at) |
| + VALUES ('op_raw', ?, 'sub_raw', 'pack', 0, '{}', '{}', 'applied', 0)`, o.acct.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + zero := billingOp{ID: "op_zero", AccountID: o.acct.ID, Subscription: "sub_zero", Kind: opPack, |
| + Target: opTarget{Quantities: map[string]int64{"price_x": 2}}, StartQuantity: knownStart(0), |
| + Prepared: billing.Prepared{Kind: billing.PreparedChange, Method: "POST", Path: "/x", Key: "op:zero"}, State: opApplied} |
| + if err := o.st.BeginBillingOp(zero); err != nil { |
| + t.Fatal(err) |
| + } |
| + check := func(when string) { |
| + t.Helper() |
| + if row := o.op(t, "op_raw"); row.StartQuantity != nil { |
| + t.Fatalf("%s: a row written without a start reads %d, want unknown", when, *row.StartQuantity) |
| + } |
| + if row := o.op(t, "op_zero"); row.StartQuantity == nil || *row.StartQuantity != 0 { |
| + t.Fatalf("%s: a recorded 0 reads %v", when, row.StartQuantity) |
| + } |
| + } |
| + check("new store") |
| + dropStartColumn(t, o.st) |
| + if row := o.op(t, "op_zero"); row.StartQuantity != nil { |
| + t.Fatalf("after migration: start = %d, want unknown (the old store had no column)", *row.StartQuantity) |
| + } |
| + if row := o.op(t, "op_raw"); row.StartQuantity != nil { |
| + t.Fatalf("after migration: start = %d, want unknown", *row.StartQuantity) |
| + } |
| +} |
| + |
| // Invariant 4's backstop: sendOpLocked refuses a restore's first send inside |
| // the margin, writing and sending nothing. |
| func TestRestoreRefusedNearRenewalInSend(t *testing.T) { |
diff --git a/internal/console/billinglint_test.go b/internal/console/billinglint_test.go| index 7d65f6e6e..c4e343c1e 100644 |
| --- a/internal/console/billinglint_test.go |
| +++ b/internal/console/billinglint_test.go |
| @@ -224,6 +224,45 @@ func (s *Server) forge() { s.closeBillingProblemLocked(billingHold{}, nil, nil, |
| } |
| } |
| +// beginOpCallers names every non-test function that calls BeginBillingOp. |
| +func beginOpCallers(files map[string]*ast.File) []string { |
| + var callers []string |
| + for _, f := range files { |
| + for _, d := range f.Decls { |
| + fd, ok := d.(*ast.FuncDecl) |
| + if !ok || fd.Body == nil { |
| + continue |
| + } |
| + ast.Inspect(fd.Body, func(n ast.Node) bool { |
| + if call, ok := n.(*ast.CallExpr); ok { |
| + if sel, ok := call.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "BeginBillingOp" { |
| + callers = append(callers, fd.Name.Name) |
| + } |
| + } |
| + return true |
| + }) |
| + } |
| + } |
| + sort.Strings(callers) |
| + return callers |
| +} |
| + |
| +// TestBeginBillingOpOnlyFromSend: sendOpLocked is the one production |
| +// writer of an operation, so its checks (provider time, the restore margin, |
| +// a recorded start quantity) cover every operation the console sends. |
| +func TestBeginBillingOpOnlyFromSend(t *testing.T) { |
| + fset, files := parsePackageSources(t) |
| + if got := beginOpCallers(files); !slices.Equal(got, []string{"sendOpLocked"}) { |
| + t.Fatalf("BeginBillingOp callers = %v, want [sendOpLocked]", got) |
| + } |
| + planted := parsePlanted(t, fset, "billingplanted.go", ` |
| +func (s *Server) sneak(op billingOp) { s.store.BeginBillingOp(op) } |
| +`) |
| + if got := beginOpCallers(planted); !slices.Equal(got, []string{"sneak"}) { |
| + t.Fatalf("planted callers = %v", got) |
| + } |
| +} |
| + |
| // providerStatusWords are the provider's own status words, which stay inside |
| // the adapter (Global Constraints: provider neutrality). |
| var providerStatusWords = regexp.MustCompile(`\b(active|trialing|past_due|incomplete|incomplete_expired|unpaid|canceled|paused)\b`) |
diff --git a/internal/console/billingops.go b/internal/console/billingops.go| index ddbced289..194b434ee 100644 |
| --- a/internal/console/billingops.go |
| +++ b/internal/console/billingops.go |
| @@ -107,12 +107,26 @@ type billingOp struct { |
| AppliedPeriodEnd time.Time |
| CreatedAt time.Time |
| // StartQuantity is the changed item's quantity before the change, |
| - // recorded when the request is prepared (0 for a new item). A charge |
| - // explains a quantity above a renewal's baseline only when it started at |
| - // or below that baseline (Risk R1). |
| - StartQuantity int64 |
| + // recorded when the request is prepared (knownStart(0) for a new item); |
| + // nil is unknown (startUnknown in the store, as for every operation |
| + // written before the column existed). A charge explains a quantity above |
| + // a renewal's baseline only with a recorded start at or below that |
| + // baseline (Risk R1); an unknown start never does, and sendOpLocked |
| + // refuses a quantity change without one (errStartUnknown). |
| + StartQuantity *int64 |
| } |
| +// startUnknown is the stored start_quantity of an operation whose start was |
| +// never recorded: the column's default, never a real quantity. |
| +const startUnknown = -1 |
| + |
| +// knownStart is a recorded start quantity. |
| +func knownStart(q int64) *int64 { return &q } |
| + |
| +// errStartUnknown refuses a quantity change prepared without the quantity it |
| +// starts from. |
| +var errStartUnknown = errors.New("billing: a quantity change must record the quantity it starts from") |
| + |
| // resendUntil is the end of the operation's resend window in provider time: |
| // the key lifetime from the first send, cut off before the period end. |
| func (op billingOp) resendUntil() time.Time { |
| @@ -133,12 +147,15 @@ const billingOpColumns = `id, account_id, subscription, kind, period_end, target |
| func scanBillingOp(sc interface{ Scan(...any) error }) (*billingOp, error) { |
| var op billingOp |
| var target, prepared []byte |
| - var periodEnd, firstSent, lastSent, settled, applied, created int64 |
| + var periodEnd, firstSent, lastSent, settled, applied, created, start int64 |
| var indeterminate int |
| if err := sc.Scan(&op.ID, &op.AccountID, &op.Subscription, &op.Kind, &periodEnd, &target, &prepared, &op.InviteToken, &op.AuthorisedBy, |
| - &op.State, &indeterminate, &firstSent, &lastSent, &settled, &applied, &created, &op.StartQuantity); err != nil { |
| + &op.State, &indeterminate, &firstSent, &lastSent, &settled, &applied, &created, &start); err != nil { |
| return nil, err |
| } |
| + if start != startUnknown { |
| + op.StartQuantity = knownStart(start) |
| + } |
| if err := json.Unmarshal(target, &op.Target); err != nil { |
| return nil, err |
| } |
| @@ -196,6 +213,10 @@ func (s *Store) BeginBillingOp(op billingOp) error { |
| if err != nil { |
| return err |
| } |
| + start := int64(startUnknown) |
| + if op.StartQuantity != nil { |
| + start = *op.StartQuantity |
| + } |
| tx, err := s.db.Begin() |
| if err != nil { |
| return err |
| @@ -212,7 +233,7 @@ func (s *Store) BeginBillingOp(op billingOp) error { |
| if _, err := tx.Exec(`INSERT INTO billing_operations (`+billingOpColumns+`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, |
| op.ID, op.AccountID, op.Subscription, op.Kind, unixOrZero(op.PeriodEnd), target, prepared, op.InviteToken, op.AuthorisedBy, |
| op.State, boolInt(op.Indeterminate), unixOrZero(op.FirstSentAt), unixOrZero(op.LastSentAt), unixOrZero(op.SettledAt), |
| - unixOrZero(op.AppliedPeriodEnd), unixOrZero(op.CreatedAt), op.StartQuantity); err != nil { |
| + unixOrZero(op.AppliedPeriodEnd), unixOrZero(op.CreatedAt), start); err != nil { |
| return err |
| } |
| if op.Kind == opRestore { |
| @@ -517,9 +538,15 @@ func (s *Server) recordSendOutcome(op *billingOp, res billing.Result, err error, |
| // and the request is refused with change.clock. A restore inside |
| // restoreMargin of the period end (Invariant 4) is refused the same way |
| // with errRestoreNearRenewal: the handlers check it first, and this is the |
| -// backstop. |
| +// backstop. A quantity change with no recorded start quantity is refused |
| +// with errStartUnknown before anything else (Risk R1's evidence needs it); |
| +// sendOpLocked is the only writer of an operation |
| +// (TestBeginBillingOpOnlyFromSend), so no caller can skip that. |
| func (s *Server) sendOpLocked(h billingHold, ctx context.Context, op billingOp, now time.Time) (opOutcome, *billing.Subscription, error) { |
| _ = h |
| + if len(op.Target.Quantities) > 0 && op.StartQuantity == nil { |
| + return opOutcome{}, nil, errStartUnknown |
| + } |
| cfg := s.billing.cfg |
| pnow, err := s.providerNow(ctx) |
| if err != nil { |
diff --git a/internal/console/billingops_test.go b/internal/console/billingops_test.go| index 591ba8819..9e6366ba1 100644 |
| --- a/internal/console/billingops_test.go |
| +++ b/internal/console/billingops_test.go |
| @@ -145,7 +145,7 @@ func (o *opsFixture) packOp(t *testing.T, id, subID, name string, qty int64, pr |
| } |
| sub := o.sub(subID) |
| return billingOp{ID: id, Subscription: subID, Kind: kind, AccountID: o.accountOf(t, subID), PeriodEnd: sub.PeriodEnd, |
| - Target: opTarget{Quantities: map[string]int64{it.PriceID: qty}}, Prepared: p, StartQuantity: it.Quantity} |
| + Target: opTarget{Quantities: map[string]int64{it.PriceID: qty}}, Prepared: p, StartQuantity: knownStart(it.Quantity)} |
| } |
| func (o *opsFixture) accountOf(t *testing.T, subID string) int64 { |
| @@ -850,6 +850,31 @@ func TestCrashBeforeSendRecovered(t *testing.T) { |
| wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1}) |
| } |
| +// A quantity change that never recorded the quantity it starts from is |
| +// refused before anything is written or sent, so a handler cannot forget |
| +// it; a change with no quantities (a renewal) needs none. |
| +func TestSendRefusesAnUnknownStart(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.observe() |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + op.StartQuantity = nil |
| + if _, _, err := o.send(t, op); !errors.Is(err, errStartUnknown) { |
| + t.Fatalf("err = %v, want errStartUnknown", err) |
| + } |
| + if row, err := o.st.BillingOp("op_1"); err != nil || row != nil { |
| + t.Fatalf("an op was written: %+v %v", row, err) |
| + } |
| + if len(o.counts()) != 0 { |
| + t.Fatalf("calls = %v, want none", o.counts()) |
| + } |
| + if out, _, err := o.send(t, o.renewalOp(t, "op_2", "sub_1", false)); err != nil || out.State != opApplied { |
| + t.Fatalf("renewal with no start: %+v %v", out, err) |
| + } |
| + if _, _, err := o.send(t, o.packOp(t, "op_3", "sub_1", "apps", 3, billing.ProrateNow, opPack)); err != nil { |
| + t.Fatalf("with a start: %v", err) |
| + } |
| +} |
| + |
| // A problem whose account is gone is closed without a hold, and nothing is |
| // decided about an operation there: an operation_unresolved close with no |
| // account is refused and the operation is left as it is. Other reasons |
diff --git a/internal/console/billingstore.go b/internal/console/billingstore.go| index a0634d38b..d47ef0aaa 100644 |
| --- a/internal/console/billingstore.go |
| +++ b/internal/console/billingstore.go |
| @@ -225,15 +225,17 @@ func (s *Store) migrateBillingOperations() error { |
| settled_at INTEGER NOT NULL DEFAULT 0, |
| applied_period_end INTEGER NOT NULL DEFAULT 0, |
| created_at INTEGER NOT NULL, |
| - start_quantity INTEGER NOT NULL DEFAULT 0 |
| + start_quantity INTEGER NOT NULL DEFAULT -1 |
| ); |
| CREATE UNIQUE INDEX IF NOT EXISTS billing_operations_outstanding ON billing_operations(subscription) WHERE state IN ('sending', 'unresolved', 'pending'); |
| CREATE INDEX IF NOT EXISTS billing_operations_invite ON billing_operations(invite_token) WHERE invite_token != '';`) |
| if err != nil { |
| return err |
| } |
| - // Additive, for a store created before the column existed. |
| - if _, err := s.db.Exec(`ALTER TABLE billing_operations ADD COLUMN start_quantity INTEGER NOT NULL DEFAULT 0`); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| + // Additive, for a store created before the column existed: its rows' |
| + // starts were never recorded, so they take startUnknown (-1), which |
| + // explains no raise; 0 would read as a recorded new item. |
| + if _, err := s.db.Exec(`ALTER TABLE billing_operations ADD COLUMN start_quantity INTEGER NOT NULL DEFAULT -1`); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| return err |
| } |
| return nil |