carlos / platform Public

console: completeness covers every live subscription, in one place

Final review finding A (Astra 1, Ruling 23; second round in the
completeness family, so AGENTS.md rule 2). StaleFacts and Unknown counted
paying accounts only, but paying reads facts that are false after the
migration or a failed read, so an existing customer could drop out of ARR
under a complete figure, and the snapshot wrote -1 rows for non-paying
live subscriptions under complete=1.

The invariant, stated on factsRequired in billingrevenue.go: a figure
built from billing facts is complete only if every non-exempt account
with a live subscription (the set that gets a daily row) has fresh facts
and a known amount. moneyInputsFor (StaleFacts, never read counts as
stale), arrOf (Unknown) and the snapshot's rows all use factsRequired and
nothing else.

TestFactsRequiredInvariant walks all 144 stored states (billable, live,
annual -1/0/2400, facts never/3h/fresh, cancel, exempt) through the real
store, the snapshot pass and billingRevenueNow: complete iff every
required account is fresh and known, the door's ARR and inFacts agree,
and the migration defaults are refused for facts. Restoring the old
paying-only counting in either place fails it. TestMoneyInputsFor and
TestARROfUnknownAmount follow the wider set.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev b5486cbd5153c02c7a16e0094b0f71700d497cac parent bc0e9d1
3 files changed, +151 −23
  • internal/console/billingmoney.go +8 −8
  • internal/console/billingrevenue.go +30 −11
  • internal/console/billingrevenue_test.go +113 −4
diff --git a/internal/console/billingmoney.go b/internal/console/billingmoney.go
index f6ff01066..8de3d264c 100644
--- a/internal/console/billingmoney.go
+++ b/internal/console/billingmoney.go
@@ -14,10 +14,10 @@ import (
type moneyInput uint8
const (
- inFacts moneyInput = 1 << iota // every paying account's subscription read is current
+ inFacts moneyInput = 1 << iota // every factsRequired account's subscription read is current
inPayments // the payment reconcile is current
inRates // the rates are current and cover the figure's currencies
- inAmounts // no paying account's yearly amount is unknown
+ inAmounts // no factsRequired account's yearly amount is unknown
inEconomics // the Economics read is complete
inPlatform // the figure's month has a CARLOS-only platform cost
)
@@ -36,8 +36,8 @@ type moneyUse struct {
type moneyInputs struct {
Now time.Time
Rates eurRates // LatestEURRates, with FetchedAt
- StaleFacts int // paying, non-exempt accounts whose FactsReadAt is older than billingFactsMaxAge
- Unknown int // arrTotals.Unknown
+ StaleFacts int // factsRequired accounts whose FactsReadAt is zero or billingFactsMaxAge old
+ Unknown int // arrTotals.Unknown: factsRequired accounts with Annual -1
Reconciled time.Time // PaymentsReconciledAt
EconomicsComplete bool // Plan 2 fills; false here
PlatformOK map[string]bool // Plan 2 fills, by month; nil here
@@ -131,9 +131,9 @@ type moneyFigure struct {
}
// moneyInputsFor reads the rates and the reconciled time and counts the
-// paying, non-exempt accounts whose subscription read is stale; Unknown
-// comes from arr. The cost inputs (EconomicsComplete, PlatformOK) stay
-// unset.
+// factsRequired accounts whose subscription read is stale (or never
+// happened); Unknown comes from arr, counted over the same set. The cost
+// inputs (EconomicsComplete, PlatformOK) stay unset.
func (s *Server) moneyInputsFor(now time.Time, facts []billingFact, arr arrTotals) (moneyInputs, error) {
rates, err := s.store.LatestEURRates()
if err != nil {
@@ -145,7 +145,7 @@ func (s *Server) moneyInputsFor(now time.Time, facts []billingFact, arr arrTotal
}
in := moneyInputs{Now: now, Rates: rates, Reconciled: reconciled, Unknown: arr.Unknown}
for _, f := range facts {
- if f.AccountID == s.store.planExemptID || !payingNow(f) {
+ if !factsRequired(f, s.store.planExemptID) {
continue
}
if f.FactsReadAt.IsZero() || now.Sub(f.FactsReadAt) >= billingFactsMaxAge {
diff --git a/internal/console/billingrevenue.go b/internal/console/billingrevenue.go
index 96d7119be..5de98e6d9 100644
--- a/internal/console/billingrevenue.go
+++ b/internal/console/billingrevenue.go
@@ -135,6 +135,24 @@ func billingGroupOf(f billingFact, exemptID int64) billingGroup {
return groupFree
}
+// factsRequired is the one set of accounts whose billing facts must be
+// current for any figure built from them: not exempt, with a subscription
+// that is live (billing_accounts live). It is exactly the set that gets a
+// daily account row (Ruling 18), and it holds every account ARR counts as
+// paying (a subscription read sets Billable only with Live).
+//
+// The invariant: a figure built from billing facts is complete only if
+// every account in factsRequired has fresh facts (read less than
+// billingFactsMaxAge ago; never read is stale) and a known yearly amount.
+// StaleFacts (moneyInputsFor) and Unknown (arrOf) both count over this set
+// and nothing else; no other code decides which accounts must be current.
+// An account the migration left at its defaults (not billable, amount -1,
+// never read) is in it as soon as its subscription is live, so it refuses
+// the figure until it is read rather than dropping out of it.
+func factsRequired(f billingFact, exemptID int64) bool {
+ return f.AccountID != exemptID && f.Subscribed
+}
+
// inARR is an account ARR counts: paying, not cancelling, a known
// non-zero yearly amount, not exempt.
func inARR(f billingFact, exemptID int64) bool {
@@ -142,10 +160,11 @@ func inARR(f billingFact, exemptID int64) bool {
}
// arrTotals is ARR by currency and in euros at RateDay's rates. Paying
-// counts the paying group; Attention its accounts whose renewal is failing or
-// cancelling; Unknown its accounts whose yearly amount is unknown,
-// cancelling ones included (left out of ByCurrency; their daily rows would
-// store the unknown amount, so the gate refuses either way). EUR is 0 when a currency has no rate.
+// counts the paying group; Attention its accounts whose renewal is failing
+// or cancelling; Unknown the factsRequired accounts whose yearly amount is
+// unknown, paying or not, cancelling ones included (left out of ByCurrency;
+// their daily rows would store the unknown amount, so the gate refuses
+// either way). EUR is 0 when a currency has no rate.
type arrTotals struct {
ByCurrency map[string]int64
EUR int64
@@ -157,6 +176,9 @@ type arrTotals struct {
func arrOf(facts []billingFact, exemptID int64, r eurRates) arrTotals {
t := arrTotals{ByCurrency: map[string]int64{}, RateDay: r.Day}
for _, f := range facts {
+ if factsRequired(f, exemptID) && f.Annual == -1 {
+ t.Unknown++
+ }
if billingGroupOf(f, exemptID) != groupPaying {
continue
}
@@ -164,9 +186,6 @@ func arrOf(facts []billingFact, exemptID int64, r eurRates) arrTotals {
if f.RenewalFailing || f.CancelAtPeriodEnd {
t.Attention++
}
- if f.Annual == -1 {
- t.Unknown++
- }
if inARR(f, exemptID) {
t.ByCurrency[f.Currency] += f.Annual
}
@@ -184,7 +203,7 @@ func arrOf(facts []billingFact, exemptID int64, r eurRates) arrTotals {
// migrateBillingSnapshots adds the daily ARR snapshot: one row per day
// with the totals and whether its inputs were complete, and one row per
-// non-exempt subscribed account per day. Called from migrateBillingMoney.
+// factsRequired account per day. Called from migrateBillingMoney.
func (s *Store) migrateBillingSnapshots() error {
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS billing_arr_daily (
day TEXT PRIMARY KEY,
@@ -387,8 +406,8 @@ func (s *Server) billingRevenueNow(now time.Time) (billingRevenue, []billingFact
}
// billingSnapshotPass writes today's (UTC) snapshot: ARR and one row per
-// non-exempt subscribed account, complete only when every input they use
-// is (moneyReady). Every pass rewrites today; the day's last pass is what
+// factsRequired account, complete only when every input they use is
+// (moneyReady; the facts and amounts inputs count over the same set). Every pass rewrites today; the day's last pass is what
// stays. No earlier day is ever written, so history starts at the first
// pass.
func (s *Server) billingSnapshotPass(ctx context.Context, now time.Time) error {
@@ -407,7 +426,7 @@ func (s *Server) billingSnapshotPass(ctx context.Context, now time.Time) error {
seen[c] = true
}
for _, f := range facts {
- if f.AccountID == exempt || !f.Subscribed {
+ if !factsRequired(f, exempt) {
continue
}
r := accountDay{Day: today, AccountID: f.AccountID, Annual: f.Annual, Currency: f.Currency,
diff --git a/internal/console/billingrevenue_test.go b/internal/console/billingrevenue_test.go
index a86c03c52..fd8246bc5 100644
--- a/internal/console/billingrevenue_test.go
+++ b/internal/console/billingrevenue_test.go
@@ -3,6 +3,7 @@ package console
import (
"context"
"errors"
+ "fmt"
"maps"
"reflect"
"testing"
@@ -76,7 +77,7 @@ func TestBillingGroupOf(t *testing.T) {
// payingFact is an active, paid subscription on account id.
func payingFact(id int64, currency string, annual int64) billingFact {
- return billingFact{AccountID: id, Subscription: "sub_" + currency, Billable: true, Paid: true,
+ return billingFact{AccountID: id, Subscription: "sub_" + currency, Subscribed: true, Billable: true, Paid: true,
Currency: currency, Annual: annual}
}
@@ -123,6 +124,17 @@ func TestARROfUnknownAmount(t *testing.T) {
if got.Paying != 3 || got.Unknown != 2 || got.ByCurrency["eur"] != 2400 || got.EUR != 2400 || got.Attention != 1 {
t.Fatalf("arrOf = %+v; want Paying 3, Unknown 2 (the cancelling one too), eur 2400", got)
}
+ // Unknown counts every factsRequired account, paying or not: a live
+ // trial's unknown amount would be stored in its daily row. Not an
+ // ended subscription's.
+ trial := payingFact(5, "eur", -1)
+ trial.Billable = false
+ ended := payingFact(6, "eur", -1)
+ ended.Subscribed, ended.Billable = false, false
+ got = arrOf([]billingFact{payingFact(3, "eur", 2400), trial, ended}, OpsAccountID, rates)
+ if got.Paying != 1 || got.Unknown != 1 {
+ t.Fatalf("arrOf = %+v; want Paying 1, Unknown 1 (the trial)", got)
+ }
// The brief's case: one unknown beside a known eur 2400.
got = arrOf([]billingFact{payingFact(2, "eur", -1), payingFact(3, "eur", 2400)}, OpsAccountID, rates)
if got.Paying != 2 || got.Unknown != 1 {
@@ -147,13 +159,19 @@ func TestMoneyInputsFor(t *testing.T) {
trialing.Billable = false
trialing.FactsReadAt = now.Add(-30 * 24 * time.Hour)
exempt := payingFact(OpsAccountID, "eur", 900)
- facts := []billingFact{fresh, stale, trialing, exempt}
+ ended := payingFact(5, "eur", 300)
+ ended.Subscribed, ended.Billable = false, false
+ neverRead := billingFact{AccountID: 6, Subscription: "sub_6", Subscribed: true, Annual: -1}
+ facts := []billingFact{fresh, stale, trialing, exempt, ended, neverRead}
in, err := fx.srv.moneyInputsFor(now, facts, arrTotals{Unknown: 4})
if err != nil {
t.Fatal(err)
}
- if in.StaleFacts != 1 || in.Unknown != 4 || !in.Now.Equal(now) {
- t.Fatalf("inputs = %+v; want StaleFacts 1, Unknown 4", in)
+ // Stale: the paying usd account, the live trial (a live subscription
+ // needs current facts, paying or not) and the never-read one; not the
+ // exempt account or the ended subscription.
+ if in.StaleFacts != 3 || in.Unknown != 4 || !in.Now.Equal(now) {
+ t.Fatalf("inputs = %+v; want StaleFacts 3, Unknown 4", in)
}
if !in.Reconciled.Equal(now.Add(-10*time.Minute)) || in.Rates.Day != "2026-10-24" || !in.Rates.FetchedAt.Equal(now.Add(-time.Hour)) {
t.Fatalf("inputs = %+v; want the stored reconcile and rates", in)
@@ -613,3 +631,94 @@ func TestSnapshotCancellingUnknownAmount(t *testing.T) {
t.Fatalf("rows = %+v; want the cancelling account at -1", rows)
}
}
+
+// TestFactsRequiredInvariant guards Ruling 23 over stored states, through
+// the real store, the snapshot pass and billingRevenueNow: for every
+// combination of billable, live, yearly amount, facts age, cancel and
+// exempt on one account that has paid, the day's snapshot is complete iff
+// every non-exempt live account has fresh facts and a known amount; the
+// revenue door's ARR agrees with it, and so does its facts input alone.
+// The migration's defaults on a live subscription (not billable, amount
+// -1, never read) are refused for facts.
+func TestFactsRequiredInvariant(t *testing.T) {
+ bf := newBillingFixture(t)
+ now := billingNow
+ today := now.UTC().Format(snapshotDayFormat)
+ if err := bf.st.PutEURRates(fxrate.Rates{Day: "2026-10-24", PerEUR: map[string]float64{"usd": 1.12}}, now); err != nil {
+ t.Fatal(err)
+ }
+ if err := bf.st.SetPaymentsReconciled(now); err != nil {
+ t.Fatal(err)
+ }
+ paid := testCharge("mv_paid", "ch_paid")
+ paid.At = now.Add(-30 * 24 * time.Hour)
+ recordPayment(t, bf.st, paid) // sub_1 on cus_1: the account has paid
+ base, err := bf.st.BillingAccount(bf.acct.ID)
+ if err != nil || base == nil {
+ t.Fatalf("billing row: %+v, %v", base, err)
+ }
+ defaultExempt := bf.st.planExemptID
+ t.Cleanup(func() { bf.st.planExemptID = defaultExempt })
+
+ factsAges := map[string]time.Time{"never": {}, "3h old": now.Add(-3 * time.Hour), "fresh": now.Add(-10 * time.Minute)}
+ cases := 0
+ for _, billable := range []bool{false, true} {
+ for _, live := range []bool{false, true} {
+ for _, annual := range []int64{-1, 0, 2400} {
+ for _, age := range []string{"never", "3h old", "fresh"} {
+ for _, cancel := range []bool{false, true} {
+ for _, exempt := range []bool{false, true} {
+ cases++
+ name := fmt.Sprintf("billable=%v live=%v annual=%d facts=%s cancel=%v exempt=%v",
+ billable, live, annual, age, cancel, exempt)
+ b := *base
+ b.Subscription, b.Currency, b.State = "sub_1", "eur", billing.StatePaid
+ b.Billable, b.Live, b.Annual, b.FactsReadAt, b.CancelAtPeriodEnd = billable, live, annual, factsAges[age], cancel
+ if err := bf.st.PutBillingState(b); err != nil {
+ t.Fatalf("%s: %v", name, err)
+ }
+ bf.st.planExemptID = defaultExempt
+ if exempt {
+ bf.st.planExemptID = bf.acct.ID
+ }
+ if err := bf.srv.billingSnapshotPass(context.Background(), now); err != nil {
+ t.Fatalf("%s: snapshot: %v", name, err)
+ }
+ required := !exempt && live
+ fresh := age == "fresh"
+ wantComplete := !required || (fresh && annual != -1)
+ a := arrDay(t, bf.st, today)
+ if a.Complete != wantComplete {
+ t.Errorf("%s: snapshot complete=%v (why %q), want %v", name, a.Complete, a.Why, wantComplete)
+ }
+ rev, _, err := bf.srv.billingRevenueNow(now)
+ if err != nil {
+ t.Fatalf("%s: revenue: %v", name, err)
+ }
+ figs, reply := revenueFigures(rev, rev.Inputs)
+ if figs[0].Name != "arr" || figs[0].Shown != a.Complete || reply.ARR.Available != a.Complete {
+ t.Errorf("%s: door ARR shown=%v, snapshot complete=%v", name, figs[0].Shown, a.Complete)
+ }
+ if ok, _ := moneyReady(rev.Inputs, moneyUse{Inputs: inFacts}); ok != (!required || fresh) {
+ t.Errorf("%s: inFacts ready=%v, want %v", name, ok, !required || fresh)
+ }
+ wantARR := int64(0)
+ if !exempt && billable && !cancel && annual > 0 {
+ wantARR = annual
+ }
+ if rev.ByCurrency["eur"] != wantARR || a.ARR["eur"] != wantARR {
+ t.Errorf("%s: ARR door %d snapshot %d, want %d", name, rev.ByCurrency["eur"], a.ARR["eur"], wantARR)
+ }
+ if !billable && live && annual == -1 && age == "never" && !exempt && (a.Complete || a.Why != moneyWhyFacts) {
+ t.Errorf("%s: migration defaults: %+v, want refused for facts", name, a)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ if cases != 144 {
+ t.Fatalf("%d cases, want 144", cases)
+ }
+}