plans: sponsor every account that existed before plans went on (sponsor_accounts_before)
Paul's ruling (2026-10-31): every account that exists when Carloku switches plan limits on is sponsored with no limits, so no existing user meets a cap or has to pay. Sponsoring by hand after the catalog is configured leaves a gap, because configuring the catalog makes limits act at once. The catalog gains an optional sponsor_accounts_before (RFC 3339; empty is unset and stays out of the ID's canonical form, so existing catalog IDs do not move). With it set: - sponsorOwed is the one predicate: a live, non-exempt account created before the cutoff (accounts.created_at) with no plan row. - EffectiveLimits answers no limits for an owed account, so no cap check, grace pass, mail pause or keep door acts on it; checkMemberCap passes it. EnsureDefaultPlans never gives an account created before the cutoff a default row, so an owed account has no row and no limits record until it is sponsored. - The limits pass runs settleSponsoredAccounts first and nothing else until it succeeds. Each owed account gets the default plan, source sponsored, reason "existing account at plan launch", by "plans", with sponsorUnlimited limits, through applyAccountPlanUnassigned, the plan transition that writes only while the account still has no row (so a plan an operator or a checkout wrote since the list is kept). Errors come back joined; the next pass retries. It is done for the process once a run succeeds at or after the cutoff plus ten minutes. - sponsorUnlimited: counts and sizes MaxInt64/4 (levelOf's limit*4 and 2*limit, the mail pause's 2*limit), idle_seconds and history_days the most a time.Duration holds, min_schedule_seconds 1, rate ceilings ratelimit.MaxValue, memory tier default, every switch on. Docs: one sentence in docs/site/plans.md (Sponsored accounts), pending copy review. Census: only the internal/plans envelope is re-pinned (catalog.go); card docs/superpowers/notes/census-proposal-sponsor-existing-accounts.md, awaiting the independent reviewer.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
15 files changed,
+796
−36
docs/site/plans.md+2 −0docs/superpowers/notes/census-proposal-sponsor-existing-accounts.md+11 −0internal/console/accountplans.go+11 −4internal/console/accountplans_test.go+6 −6internal/console/planlapse.go+42 −16internal/console/planlimits.go+20 −6internal/console/planlimits_test.go+1 −1internal/console/planmembers.go+8 −2internal/console/plansponsor.go+205 −0internal/console/plansponsor_test.go+415 −0internal/console/server.go+4 −0internal/plans/catalog.go+21 −1internal/plans/catalog_test.go+46 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-sponsor-existing-accounts.tsv+3 −0
CI cancelled — superseded by a newer push — run details
diff --git a/docs/site/plans.md b/docs/site/plans.md| index c91feb5d8..62e546dc1 100644 |
| --- a/docs/site/plans.md |
| +++ b/docs/site/plans.md |
| @@ -58,6 +58,8 @@ carlos accounts plan --account bac --set free --sponsored limits.json --reason " |
| `limits.json` holds any of the limit names from the catalog. A sponsored limit can go above a ceiling: that is a decision you made for that account. |
| +Set `sponsor_accounts_before` in the catalog to a time, like `"2026-11-01T09:00:00Z"`, and every account created before then that has no plan of its own is sponsored with no limits before any limit applies to it. |
| + |
| ## Rate limit ceilings |
| A plan can cap how far an account may raise an instance's rate limits, with `rate_client_share`, `rate_per_second` and `rate_burst` in its limits or in `ceilings`. Leave one out and that number has no ceiling. Packs cannot raise them. A `rate_per_second` below 300 or a `rate_burst` below 1000 is refused when the catalog loads, because a plan may never make limits stricter than the platform's defaults. See [Rate limits](rate-limits.md). |
diff --git a/docs/superpowers/notes/census-proposal-sponsor-existing-accounts.md b/docs/superpowers/notes/census-proposal-sponsor-existing-accounts.md| new file mode 100644 |
| index 000000000..0fceefd6a |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-sponsor-existing-accounts.md |
| @@ -0,0 +1,11 @@ |
| +# Census approval: sponsor-existing-accounts |
| + |
| +Ruling `census-ruling-sponsor-existing-accounts`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +Envelopes re-pinned: `internal/plans`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Seal: `43d1824141f0ce7024cc3740ab5feac3f3539322f8afb856c9ca2f10d5095e95` → `43d1824141f0ce7024cc3740ab5feac3f3539322f8afb856c9ca2f10d5095e95`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-sponsor-existing-accounts.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/internal/console/accountplans.go b/internal/console/accountplans.go| index 87a84d482..aa4896c82 100644 |
| --- a/internal/console/accountplans.go |
| +++ b/internal/console/accountplans.go |
| @@ -4,6 +4,7 @@ import ( |
| "database/sql" |
| "encoding/json" |
| "errors" |
| + "math" |
| "slices" |
| "strings" |
| "time" |
| @@ -241,13 +242,19 @@ func billingSetPlan(tx *sql.Tx, accountID int64, plan string, packs map[string]i |
| // EnsureDefaultPlans gives every live account without a plan row the |
| // default plan, and reports how many rows it inserted. The exempt account |
| -// (planExempt) gets none. |
| -func (s *Store) EnsureDefaultPlans(defaultPlan string, now time.Time) (int, error) { |
| +// (planExempt) gets none, and nor does an account created before |
| +// sponsorCutoff (when set): it is owed the launch sponsorship |
| +// (plansponsor.go), never the default plan. |
| +func (s *Store) EnsureDefaultPlans(defaultPlan string, sponsorCutoff time.Time, now time.Time) (int, error) { |
| + from := int64(math.MinInt64) |
| + if !sponsorCutoff.IsZero() { |
| + from = sponsorCutoff.Unix() |
| + } |
| res, err := s.db.Exec(`INSERT INTO account_plans |
| (account_id, plan, packs, source, revision, updated_by, updated_at) |
| SELECT id, ?, '{}', ?, 1, ?, ? FROM accounts |
| - WHERE deleted_at = 0 AND id != ? AND id NOT IN (SELECT account_id FROM account_plans)`, |
| - defaultPlan, PlanSourceDefault, planDefaultActor, now.Unix(), s.planExemptID) |
| + WHERE deleted_at = 0 AND id != ? AND created_at >= ? AND id NOT IN (SELECT account_id FROM account_plans)`, |
| + defaultPlan, PlanSourceDefault, planDefaultActor, now.Unix(), s.planExemptID, from) |
| if err != nil { |
| return 0, err |
| } |
diff --git a/internal/console/accountplans_test.go b/internal/console/accountplans_test.go| index a3e5bc5d2..45b7bc49b 100644 |
| --- a/internal/console/accountplans_test.go |
| +++ b/internal/console/accountplans_test.go |
| @@ -78,7 +78,7 @@ func TestEnsureDefaultPlansInsertsOnlyMissing(t *testing.T) { |
| if _, err := st.SetAccountPlan(ids["bbb"], "personal", nil, 0, "operator", nil, "paid", "ops@example.com", planNow); err != nil { |
| t.Fatal(err) |
| } |
| - n, err := st.EnsureDefaultPlans("free", planNow) |
| + n, err := st.EnsureDefaultPlans("free", time.Time{}, planNow) |
| if err != nil || n != 2 { |
| t.Fatalf("inserted %d, %v; want 2", n, err) |
| } |
| @@ -90,7 +90,7 @@ func TestEnsureDefaultPlansInsertsOnlyMissing(t *testing.T) { |
| if a == nil || a.Plan != "free" || a.Source != "default" || a.Revision != 1 || a.UpdatedBy != "plans" { |
| t.Fatalf("default row %+v", a) |
| } |
| - if n, err := st.EnsureDefaultPlans("free", planNow); err != nil || n != 0 { |
| + if n, err := st.EnsureDefaultPlans("free", time.Time{}, planNow); err != nil || n != 0 { |
| t.Fatalf("second ensure inserted %d, %v", n, err) |
| } |
| } |
| @@ -100,7 +100,7 @@ func TestEnsureDefaultPlansSkipsDeletedAccounts(t *testing.T) { |
| if _, err := st.db.Exec(`UPDATE accounts SET deleted_at = ? WHERE id = ?`, planNow.Unix(), ids["gone"]); err != nil { |
| t.Fatal(err) |
| } |
| - if n, err := st.EnsureDefaultPlans("free", planNow); err != nil || n != 1 { |
| + if n, err := st.EnsureDefaultPlans("free", time.Time{}, planNow); err != nil || n != 1 { |
| t.Fatalf("inserted %d, %v; want 1", n, err) |
| } |
| if row, _ := st.AccountPlan(ids["gone"]); row != nil { |
| @@ -110,7 +110,7 @@ func TestEnsureDefaultPlansSkipsDeletedAccounts(t *testing.T) { |
| func TestPlansToPublish(t *testing.T) { |
| st, ids := planStore(t, "aaa", "bbb", "ccc") |
| - if _, err := st.EnsureDefaultPlans("free", planNow); err != nil { |
| + if _, err := st.EnsureDefaultPlans("free", time.Time{}, planNow); err != nil { |
| t.Fatal(err) |
| } |
| rows, err := st.PlansToPublish("v1@abc", 0, 10) |
| @@ -213,7 +213,7 @@ func TestSetBillingPlanWritesOnlyChanges(t *testing.T) { |
| func TestSetBillingPlanTakesDefaultRows(t *testing.T) { |
| st, ids := planStore(t, "bab") |
| - if _, err := st.EnsureDefaultPlans("free", planNow); err != nil { |
| + if _, err := st.EnsureDefaultPlans("free", time.Time{}, planNow); err != nil { |
| t.Fatal(err) |
| } |
| written, owned, err := st.SaveBillingSync(nil, ids["bab"], &planChange{Plan: "personal", Packs: nil, Reason: "subscription sub_1 active"}, false, nil, planNow) |
| @@ -226,7 +226,7 @@ func TestSetBillingPlanTakesDefaultRows(t *testing.T) { |
| // A default row that already says the default plan, written by |
| // billing as the default plan: the source still becomes billing. |
| st2, ids2 := planStore(t, "bdk") |
| - if _, err := st2.EnsureDefaultPlans("free", planNow); err != nil { |
| + if _, err := st2.EnsureDefaultPlans("free", time.Time{}, planNow); err != nil { |
| t.Fatal(err) |
| } |
| if written, _, err := st2.SaveBillingSync(nil, ids2["bdk"], &planChange{Plan: "free", Packs: nil, Reason: "subscription sub_1 ended"}, false, nil, planNow); err != nil || !written { |
diff --git a/internal/console/planlapse.go b/internal/console/planlapse.go| index 4523e3bc0..8cd82d650 100644 |
| --- a/internal/console/planlapse.go |
| +++ b/internal/console/planlapse.go |
| @@ -127,25 +127,51 @@ func teamMembers(cat *plans.Catalog, plan string, seats int, count func() (int, |
| func (s *Server) applyAccountPlan(ctx context.Context, acct *Account, plan string, packs map[string]int, seats int, |
| source string, sponsored *plans.Limits, reason, by string, now time.Time) error { |
| return s.transitionAccountPlan(ctx, acct, now, func(old *AccountPlanRow) (bool, error) { |
| - // The fall is judged before the write, while the old row is the |
| - // one the store holds. |
| - fell := s.lapseStarted(acct.ID, old, plan, packs, seats, sponsored) |
| - if _, err := s.store.SetAccountPlan(acct.ID, plan, packs, seats, source, sponsored, reason, by, now); err != nil { |
| - return false, err |
| + return true, s.writeAccountPlan(acct, old, plan, packs, seats, source, sponsored, reason, by, now) |
| + }) |
| +} |
| + |
| +// applyAccountPlanUnassigned is applyAccountPlan for an account that has |
| +// no plan row: the launch sponsorship (plansponsor.go). Under the same |
| +// lock and transition it writes only while the account still has no row, |
| +// so a plan an operator or a checkout wrote since the caller looked is |
| +// kept. It reports whether it wrote. |
| +func (s *Server) applyAccountPlanUnassigned(ctx context.Context, acct *Account, plan string, |
| + source string, sponsored *plans.Limits, reason, by string, now time.Time) (bool, error) { |
| + wrote := false |
| + err := s.transitionAccountPlan(ctx, acct, now, func(old *AccountPlanRow) (bool, error) { |
| + if old != nil { |
| + return false, nil |
| } |
| - if fell { |
| - if err := s.store.MarkLapse(acct.ID, now); err != nil { |
| - return true, err |
| - } |
| - // Each fall gets its own grace: the lapse caps' clocks start afresh. |
| - for _, c := range lapseCaps { |
| - if err := s.store.DeleteCapState(acct.ID, c); err != nil { |
| - return true, err |
| - } |
| + err := s.writeAccountPlan(acct, old, plan, nil, 0, source, sponsored, reason, by, now) |
| + wrote = err == nil |
| + return true, err |
| + }) |
| + return wrote, err |
| +} |
| + |
| +// writeAccountPlan is applyAccountPlan's write, for a caller inside the |
| +// plan transition holding old, the row the store had. |
| +func (s *Server) writeAccountPlan(acct *Account, old *AccountPlanRow, plan string, packs map[string]int, seats int, |
| + source string, sponsored *plans.Limits, reason, by string, now time.Time) error { |
| + // The fall is judged before the write, while the old row is the one |
| + // the store holds. |
| + fell := s.lapseStarted(acct.ID, old, plan, packs, seats, sponsored) |
| + if _, err := s.store.SetAccountPlan(acct.ID, plan, packs, seats, source, sponsored, reason, by, now); err != nil { |
| + return err |
| + } |
| + if fell { |
| + if err := s.store.MarkLapse(acct.ID, now); err != nil { |
| + return err |
| + } |
| + // Each fall gets its own grace: the lapse caps' clocks start afresh. |
| + for _, c := range lapseCaps { |
| + if err := s.store.DeleteCapState(acct.ID, c); err != nil { |
| + return err |
| } |
| } |
| - return true, nil |
| - }) |
| + } |
| + return nil |
| } |
| // applyBillingPlan is billing's plan change (plans 6a, Astra finding 5), |
diff --git a/internal/console/planlimits.go b/internal/console/planlimits.go| index 3e5e61b44..566a249d6 100644 |
| --- a/internal/console/planlimits.go |
| +++ b/internal/console/planlimits.go |
| @@ -36,15 +36,22 @@ func (s *Server) StartPlanLimitsPass(ctx context.Context) { |
| } |
| } |
| -// planLimitsPass is one pass at the given clock: give unassigned accounts |
| -// the default plan, then publish every row the bucket is behind on. One |
| -// account's failure never stops the others. |
| +// planLimitsPass is one pass at the given clock: sponsor the accounts that |
| +// existed before plans went on (plansponsor.go), give unassigned accounts |
| +// the default plan, then publish every row the bucket is behind on. Until |
| +// the sponsorship settles, nothing after it runs. One account's failure |
| +// never stops the others. |
| func (s *Server) planLimitsPass(ctx context.Context, now time.Time) { |
| cat := s.cfg.PlanCatalog |
| if s.cfg.Releases == nil || cat == nil { |
| return |
| } |
| - if _, err := s.store.EnsureDefaultPlans(cat.DefaultPlan, now); err != nil { |
| + if err := s.settleSponsoredAccounts(ctx, now); err != nil { |
| + log.Printf("console: plan limits: sponsorship: %v", err) |
| + jobFailed(ctx, fmt.Errorf("plan limits: sponsorship: %w", err)) |
| + return |
| + } |
| + if _, err := s.store.EnsureDefaultPlans(cat.DefaultPlan, cat.SponsorCutoff(), now); err != nil { |
| log.Printf("console: plan limits: default plans: %v", err) |
| jobFailed(ctx, fmt.Errorf("plan limits: default plans: %w", err)) |
| return |
| @@ -130,8 +137,9 @@ func (s *Server) publishAccountLimits(ctx context.Context, row AccountPlanRow, n |
| } |
| // EffectiveLimits is acct's limits under the configured catalog, or nil |
| -// when plans are off or the account is exempt (planExempt). An account |
| -// with no row is on the default plan. A team plan is limited at |
| +// when plans are off, the account is exempt (planExempt), or it is owed |
| +// the launch sponsorship and has not got it yet (sponsorOwed). Any other |
| +// account with no row is on the default plan. A team plan is limited at |
| // planMembers' count. |
| func (s *Server) EffectiveLimits(acct *Account) (*plans.Limits, error) { |
| cat := s.cfg.PlanCatalog |
| @@ -142,6 +150,12 @@ func (s *Server) EffectiveLimits(acct *Account) (*plans.Limits, error) { |
| if err != nil { |
| return nil, err |
| } |
| + if row == nil { |
| + owed, err := s.sponsorOwedAccount(acct.ID) |
| + if err != nil || owed { |
| + return nil, err |
| + } |
| + } |
| plan, packs := cat.DefaultPlan, map[string]int(nil) |
| var sponsored *plans.Limits |
| if row != nil { |
diff --git a/internal/console/planlimits_test.go b/internal/console/planlimits_test.go| index a481f203c..e309bc6ae 100644 |
| --- a/internal/console/planlimits_test.go |
| +++ b/internal/console/planlimits_test.go |
| @@ -184,7 +184,7 @@ func TestPublishRetriesAfterABucketFailure(t *testing.T) { |
| acct := planAccount(t, fx, 501) |
| fp := &planFailingPuts{Store: fx.rel} |
| fx.srv.cfg.Releases = fp |
| - if _, err := fx.st.EnsureDefaultPlans("free", planNow); err != nil { |
| + if _, err := fx.st.EnsureDefaultPlans("free", time.Time{}, planNow); err != nil { |
| t.Fatal(err) |
| } |
| fp.n.Store(1000) // every Put fails during the first pass |
diff --git a/internal/console/planmembers.go b/internal/console/planmembers.go| index 02310e4ce..48f4f2fdf 100644 |
| --- a/internal/console/planmembers.go |
| +++ b/internal/console/planmembers.go |
| @@ -165,8 +165,9 @@ func (s *Server) membershipTransition(ctx context.Context, acct *Account, now ti |
| // checkMemberCap refuses adding more people to an account whose plan caps |
| // its members (max_members, Call 14) when they would pass the cap. Team |
| -// plans, sponsored rows, plans with no cap, the exempt account and consoles |
| -// with no catalog pass. Callers hold the account's member lock. |
| +// plans, sponsored rows, accounts owed the launch sponsorship |
| +// (sponsorOwed), plans with no cap, the exempt account and consoles with |
| +// no catalog pass. Callers hold the account's member lock. |
| func (s *Server) checkMemberCap(acct *Account, adding int) error { |
| cat := s.cfg.PlanCatalog |
| if cat == nil || s.store.planExempt(acct.ID) { |
| @@ -177,6 +178,11 @@ func (s *Server) checkMemberCap(acct *Account, adding int) error { |
| return err |
| } |
| plan := cat.DefaultPlan |
| + if row == nil { |
| + if owed, err := s.sponsorOwedAccount(acct.ID); err != nil || owed { |
| + return err |
| + } |
| + } |
| if row != nil { |
| if planRowSponsored(row) { |
| return nil |
diff --git a/internal/console/plansponsor.go b/internal/console/plansponsor.go| new file mode 100644 |
| index 000000000..fb1d0653e |
| --- /dev/null |
| +++ b/internal/console/plansponsor.go |
| @@ -0,0 +1,205 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "math" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/plans" |
| + "github.com/carlosframework/platform/internal/ratelimit" |
| +) |
| + |
| +// Accounts that already exist when plans go on are sponsored with no |
| +// limits (Paul, 2026-10-31), so no existing user meets a cap or has to |
| +// pay. A catalog opts in with sponsor_accounts_before. Every live account |
| +// created before that time (accounts.created_at, the store's own record of |
| +// the creation, to the second) that has no plan row is owed the |
| +// sponsorship, and sponsorOwed is the one predicate: |
| +// |
| +// - EffectiveLimits answers no limits for an owed account, as with plans |
| +// off, so no cap check, grace pass, mail pause or keep door acts on it; |
| +// checkMemberCap passes it as it passes a sponsored row; |
| +// - EnsureDefaultPlans never gives an account created before the cutoff |
| +// a default row, so an owed account has no row and no limits record |
| +// until the settlement writes its sponsored one; |
| +// - the settlement below writes that row through the plan transition. |
| +// |
| +// The ops account (planExempt) is never owed: it has no plan at all. |
| + |
| +// planSponsorReason is the reason a launch sponsorship's row carries. Its |
| +// writer is planDefaultActor, the system actor default rows name. |
| +const planSponsorReason = "existing account at plan launch" |
| + |
| +// sponsorSettleMargin is how long after the cutoff the settlement keeps |
| +// running. An account being minted at the cutoff gets its created_at when |
| +// the mint starts and its row only once the mint's bucket writes are done, |
| +// so a list run at the cutoff could miss it. |
| +const sponsorSettleMargin = 10 * time.Minute |
| + |
| +// sponsorUnlimited is the sponsored limits of an existing account: the |
| +// most generous value each field can take without overflowing anywhere it |
| +// is used. |
| +// |
| +// - Counts and sizes are math.MaxInt64/4. The grace levels compute |
| +// limit*4 and 2*limit (levelOf), and the mail pause 2*limit |
| +// (planMailPauseAt); int is 64-bit on every platform this builds for. |
| +// Packs and team scaling never touch a sponsored figure (Effective |
| +// merges it last). |
| +// - idle_seconds is the most a time.Duration holds in seconds: boxes |
| +// turn it into one (internal/host planIdleFor), and the idle hook can |
| +// only shorten a window, so it never does. |
| +// - history_days is the most a time.Duration holds in days. Nothing reads |
| +// it yet; that is the bound any reader would meet. |
| +// - min_schedule_seconds is 1, the smallest set value (0 is unset), and |
| +// the merge keeps the shorter interval. |
| +// - The rate ceilings are ratelimit.MaxValue, the most an instance owner |
| +// may set any rate field to, so the ceiling never clamps a setting. A |
| +// plan with no rate ceiling keeps none (generousRate). |
| +// - memory_tier is "default" and every switch is on. |
| +// |
| +// Two things no figure here can lift: the mail pause never goes above the |
| +// catalog's email ceiling, and the daemon and always-on refusals on shared |
| +// boxes apply to every account under a plan, whatever its limits. |
| +func sponsorUnlimited() plans.Limits { |
| + const most = math.MaxInt64 / 4 |
| + return plans.Limits{ |
| + RunningThings: most, |
| + SidecarsPerApp: most, |
| + IdleSeconds: int(math.MaxInt64 / int64(time.Second)), |
| + MemoryTier: plans.MemoryDefault, |
| + AwakeHoursMonth: most, |
| + DiskBytes: most, |
| + StorageBytes: most, |
| + StorageSelfServe: true, |
| + EmailPerDay: most, |
| + BandwidthBytesMonth: most, |
| + CustomDomains: true, |
| + Fleets: true, |
| + MinScheduleSeconds: 1, |
| + HistoryDays: int(math.MaxInt64 / int64(24*time.Hour)), |
| + RateClientShare: ratelimit.MaxValue, |
| + RatePerSecond: ratelimit.MaxValue, |
| + RateBurst: ratelimit.MaxValue, |
| + } |
| +} |
| + |
| +// sponsorOwed reports whether accountID is owed the launch sponsorship: |
| +// live, not exempt, created before cutoff, and with no plan row. A zero |
| +// cutoff owes nothing. |
| +func (s *Store) sponsorOwed(accountID int64, cutoff time.Time) (bool, error) { |
| + if cutoff.IsZero() || s.planExempt(accountID) { |
| + return false, nil |
| + } |
| + var n int |
| + err := s.db.QueryRow(`SELECT COUNT(*) FROM accounts WHERE id = ? AND deleted_at = 0 AND created_at < ? |
| + AND id NOT IN (SELECT account_id FROM account_plans)`, accountID, cutoff.Unix()).Scan(&n) |
| + return n > 0, err |
| +} |
| + |
| +// AccountsOwedSponsorship lists every account sponsorOwed holds for, in id |
| +// order. |
| +func (s *Store) AccountsOwedSponsorship(cutoff time.Time) ([]Account, error) { |
| + if cutoff.IsZero() { |
| + return nil, nil |
| + } |
| + rows, err := s.db.Query(`SELECT id, sqid, name, created_at FROM accounts |
| + WHERE deleted_at = 0 AND created_at < ? AND id != ? AND id NOT IN (SELECT account_id FROM account_plans) |
| + ORDER BY id`, cutoff.Unix(), s.planExemptID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []Account |
| + for rows.Next() { |
| + var a Account |
| + var created int64 |
| + if err := rows.Scan(&a.ID, &a.Sqid, &a.Name, &created); err != nil { |
| + return nil, err |
| + } |
| + a.CreatedAt = time.Unix(created, 0).UTC() |
| + out = append(out, a) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +// sponsorOwedAccount is sponsorOwed under the configured catalog. |
| +func (s *Server) sponsorOwedAccount(accountID int64) (bool, error) { |
| + cat := s.cfg.PlanCatalog |
| + if cat == nil { |
| + return false, nil |
| + } |
| + return s.store.sponsorOwed(accountID, cat.SponsorCutoff()) |
| +} |
| + |
| +// settleSponsoredAccounts gives every owed account its sponsored row. The |
| +// limits pass runs it first, and runs nothing else until it has succeeded: |
| +// a failure comes back, the rest of the pass waits, and the next pass |
| +// retries. One account's failure does not stop the others. It is done, |
| +// for this process, once a run succeeds at or after the cutoff plus |
| +// sponsorSettleMargin; before then accounts can still be created before |
| +// the cutoff, so every pass runs it again. Rerunning it is safe: an |
| +// account with a row is never owed. |
| +func (s *Server) settleSponsoredAccounts(ctx context.Context, now time.Time) error { |
| + if s.sponsorSettled.Load() { |
| + return nil |
| + } |
| + cutoff := s.cfg.PlanCatalog.SponsorCutoff() |
| + if cutoff.IsZero() { |
| + s.sponsorSettled.Store(true) |
| + return nil |
| + } |
| + owed, err := s.store.AccountsOwedSponsorship(cutoff) |
| + if err != nil { |
| + return fmt.Errorf("accounts owed sponsorship: %w", err) |
| + } |
| + var errs []error |
| + for i := range owed { |
| + if err := ctx.Err(); err != nil { |
| + return err |
| + } |
| + if err := s.sponsorExistingAccount(ctx, &owed[i], now); err != nil { |
| + errs = append(errs, fmt.Errorf("%s: %w", owed[i].Sqid, err)) |
| + } |
| + } |
| + if err := errors.Join(errs...); err != nil { |
| + return err |
| + } |
| + if !now.Before(cutoff.Add(sponsorSettleMargin)) { |
| + s.sponsorSettled.Store(true) |
| + } |
| + return nil |
| +} |
| + |
| +// sponsorExistingAccount writes acct's launch sponsorship: the default |
| +// plan, sponsored with sponsorUnlimited, through applyAccountPlanUnassigned, |
| +// so an account that got a row since the list (an operator, a checkout) |
| +// keeps it. An account deleted since the list is nothing to do. |
| +func (s *Server) sponsorExistingAccount(ctx context.Context, acct *Account, now time.Time) error { |
| + cat := s.cfg.PlanCatalog |
| + unlimited := sponsorUnlimited() |
| + members, err := s.planMembers(nil, acct.ID) |
| + if err != nil { |
| + return err |
| + } |
| + // The operator door's check: a row the catalog cannot price would |
| + // publish nothing. |
| + if _, err := cat.Effective(cat.DefaultPlan, nil, &unlimited, members); err != nil { |
| + return err |
| + } |
| + wrote, err := s.applyAccountPlanUnassigned(ctx, acct, cat.DefaultPlan, PlanSourceSponsored, &unlimited, |
| + planSponsorReason, planDefaultActor, now) |
| + if errors.Is(err, ErrAccountGone) { |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if wrote { |
| + log.Printf("console: plan limits: %s sponsored with no limits (created before %s)", acct.Sqid, |
| + cat.SponsorCutoff().UTC().Format(time.RFC3339)) |
| + } |
| + return nil |
| +} |
diff --git a/internal/console/plansponsor_test.go b/internal/console/plansponsor_test.go| new file mode 100644 |
| index 000000000..007311b59 |
| --- /dev/null |
| +++ b/internal/console/plansponsor_test.go |
| @@ -0,0 +1,415 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "math" |
| + "net/http" |
| + "os" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/plans" |
| + "github.com/carlosframework/platform/internal/ratelimit" |
| +) |
| + |
| +// Accounts that existed when plans went on are sponsored with no limits |
| +// (Paul, 2026-10-31): sponsor_accounts_before in the catalog. |
| + |
| +// sponsorCatalog is the example catalog with sponsor_accounts_before set |
| +// to cutoff. |
| +func sponsorCatalog(t *testing.T, cutoff time.Time) *plans.Catalog { |
| + t.Helper() |
| + b, err := os.ReadFile(exampleCatalogPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s := strings.Replace(string(b), `"default_plan": "free",`, |
| + `"default_plan": "free", "sponsor_accounts_before": "`+cutoff.UTC().Format(time.RFC3339)+`",`, 1) |
| + c, err := plans.ParseCatalog([]byte(s)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !c.SponsorCutoff().Equal(cutoff.Truncate(time.Second)) { |
| + t.Fatalf("cutoff %v, want %v", c.SponsorCutoff(), cutoff) |
| + } |
| + return c |
| +} |
| + |
| +// sponsorCutoffAt is the cutoff the settlement tests use: an hour before |
| +// planNow. planAccount's accounts (created 2023) are before it. |
| +var sponsorCutoffAt = planNow.Add(-time.Hour) |
| + |
| +// settledNow is a pass clock by which the settlement can finish. |
| +var settledNow = sponsorCutoffAt.Add(sponsorSettleMargin) |
| + |
| +// newPlanAccount is planAccount created at created. |
| +func newPlanAccount(t *testing.T, fx *consoleFixture, id int64, created time.Time) *Account { |
| + t.Helper() |
| + sqid := domains.Sqid(id) |
| + if err := fx.st.CreateAccount(id, sqid, "acct", "owner"+sqid+"@example.com", created); err != nil { |
| + t.Fatal(err) |
| + } |
| + acct, err := fx.st.AccountBySqid(sqid) |
| + if err != nil || acct == nil { |
| + t.Fatalf("account %s: %v", sqid, err) |
| + } |
| + return acct |
| +} |
| + |
| +func TestSponsorUnlimitedOverflowsNothing(t *testing.T) { |
| + l := sponsorUnlimited() |
| + // Every count and size: the grace levels (limit*4, 2*limit) and the |
| + // mail pause (2*limit) stay in range. |
| + for c, v := range map[capID]int64{ |
| + capRunningThings: int64(l.RunningThings), capAwakeHours: int64(l.AwakeHoursMonth), |
| + capBandwidth: l.BandwidthBytesMonth, capStorage: l.StorageBytes, capEmail: int64(l.EmailPerDay), |
| + } { |
| + if v <= 0 || v > math.MaxInt64/4 { |
| + t.Errorf("%s = %d, outside (0, MaxInt64/4]", c, v) |
| + } |
| + if got := levelOf(c, 1<<40, v); got != levelOK { |
| + t.Errorf("%s: level at a large real usage = %v", c, got) |
| + } |
| + if got := levelOf(c, v+1, v); got != levelOver { |
| + t.Errorf("%s: level just over the limit = %v (an overflow reads as under)", c, got) |
| + } |
| + } |
| + for name, v := range map[string]int64{"sidecars_per_app": int64(l.SidecarsPerApp), "disk_bytes": l.DiskBytes} { |
| + if v <= 0 || v > math.MaxInt64/4 { |
| + t.Errorf("%s = %d, outside (0, MaxInt64/4]", name, v) |
| + } |
| + } |
| + if at := planMailPauseAt(&l, plans.Limits{}); at != 2*int64(l.EmailPerDay) || at <= 0 { |
| + t.Errorf("mail pause at %d, want 2 x %d", at, l.EmailPerDay) |
| + } |
| + // The box turns idle_seconds into a duration (internal/host planIdleFor). |
| + if d := time.Duration(l.IdleSeconds) * time.Second; d <= 0 || d/time.Second != time.Duration(l.IdleSeconds) { |
| + t.Errorf("idle_seconds %d overflows a duration: %v", l.IdleSeconds, d) |
| + } |
| + if d := time.Duration(l.HistoryDays) * 24 * time.Hour; d <= 0 || d/(24*time.Hour) != time.Duration(l.HistoryDays) { |
| + t.Errorf("history_days %d overflows a duration: %v", l.HistoryDays, d) |
| + } |
| + if l.MinScheduleSeconds != 1 || l.MemoryTier != plans.MemoryDefault || |
| + !l.StorageSelfServe || !l.CustomDomains || !l.Fleets { |
| + t.Errorf("schedule, tier or switches not the most generous: %+v", l) |
| + } |
| + for name, v := range map[string]int{"rate_client_share": l.RateClientShare, "rate_per_second": l.RatePerSecond, "rate_burst": l.RateBurst} { |
| + if v != ratelimit.MaxValue { |
| + t.Errorf("%s = %d, want ratelimit.MaxValue %d", name, v, ratelimit.MaxValue) |
| + } |
| + } |
| + // A plan carrying exactly these limits is one the catalog accepts. |
| + raw, err := json.Marshal(l) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := plans.ParseCatalog([]byte(`{"version": "v", "default_plan": "all", "plans": {"all": {"paid": false, "limits": ` + string(raw) + `}}}`)); err != nil { |
| + t.Errorf("the catalog refuses the unlimited limits: %v", err) |
| + } |
| + // Merged over every plan of the example catalog, nothing is held back. |
| + cat := examplePlanCatalog(t) |
| + for name, p := range cat.Plans { |
| + members := 0 |
| + if p.Team != nil { |
| + members = 2 |
| + } |
| + got, err := cat.Effective(name, nil, &l, members) |
| + if err != nil { |
| + t.Fatalf("%s: %v", name, err) |
| + } |
| + want := l |
| + // A rate field the plan leaves at zero has no ceiling at all, which |
| + // is more generous still (generousRate). |
| + if p.Limits.RateClientShare == 0 { |
| + want.RateClientShare = got.RateClientShare |
| + } |
| + if p.Limits.RatePerSecond == 0 { |
| + want.RatePerSecond = got.RatePerSecond |
| + } |
| + if p.Limits.RateBurst == 0 { |
| + want.RateBurst = got.RateBurst |
| + } |
| + if got != want { |
| + t.Errorf("%s: effective %+v, want %+v", name, got, want) |
| + } |
| + } |
| +} |
| + |
| +// TestSponsorSettlementSponsorsExistingAccounts: one limits pass gives |
| +// every account created before the cutoff with no plan row a sponsored row |
| +// on the default plan with no limits, publishes it, and leaves every other |
| +// account as the default pass would. |
| +func TestSponsorSettlementSponsorsExistingAccounts(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = sponsorCatalog(t, sponsorCutoffAt) |
| + ctx := context.Background() |
| + old := planAccount(t, fx, 501) |
| + assigned := planAccount(t, fx, 502) |
| + if err := fx.srv.applyAccountPlan(ctx, assigned, "personal", nil, 0, PlanSourceOperator, nil, "upgraded", "ops@example.com", planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + assignedRow, _ := fx.st.AccountPlan(assigned.ID) |
| + gone := planAccount(t, fx, 503) |
| + if _, err := fx.st.db.Exec(`UPDATE accounts SET deleted_at = ? WHERE id = ?`, planNow.Unix(), gone.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + fresh := newPlanAccount(t, fx, 504, sponsorCutoffAt) // at the cutoff: not before it |
| + // ops was created at the fixture's start, before the cutoff, and is exempt. |
| + ops := opsPlanAccount(t, fx, "paul@example.com") |
| + if !ops.CreatedAt.Before(sponsorCutoffAt) || !fx.st.planExempt(ops.ID) { |
| + t.Fatalf("fixture: ops created %v, exempt %v", ops.CreatedAt, fx.st.planExempt(ops.ID)) |
| + } |
| + |
| + fx.srv.planLimitsPass(ctx, settledNow) |
| + if !fx.srv.sponsorSettled.Load() { |
| + t.Fatal("settlement did not finish") |
| + } |
| + row, err := fx.st.AccountPlan(old.ID) |
| + if err != nil || row == nil { |
| + t.Fatalf("old account row: %+v, %v", row, err) |
| + } |
| + unlimited := sponsorUnlimited() |
| + if row.Plan != "free" || row.Source != PlanSourceSponsored || row.Reason != planSponsorReason || |
| + row.UpdatedBy != planDefaultActor || row.Sponsored == nil || *row.Sponsored != unlimited { |
| + t.Fatalf("old account row = %+v", row) |
| + } |
| + rec, _ := readLimits(t, fx, old.Sqid) |
| + if rec == nil || rec.Source != PlanSourceSponsored || rec.Revision != row.Revision { |
| + t.Fatalf("old account record = %+v", rec) |
| + } |
| + if rec.Limits.RunningThings != unlimited.RunningThings || rec.Limits.IdleSeconds != unlimited.IdleSeconds || |
| + !rec.Limits.CustomDomains || rec.Limits.MemoryTier != plans.MemoryDefault || rec.Limits.MinScheduleSeconds != 1 { |
| + t.Fatalf("old account's published limits = %+v", rec.Limits) |
| + } |
| + if l, err := fx.srv.EffectiveLimits(old); err != nil || l == nil || l.RunningThings != unlimited.RunningThings { |
| + t.Fatalf("old account's effective limits = %+v, %v", l, err) |
| + } |
| + if got, _ := fx.st.AccountPlan(assigned.ID); got == nil || got.Revision != assignedRow.Revision || got.Source != PlanSourceOperator { |
| + t.Fatalf("an account with a plan of its own changed: %+v, was %+v", got, assignedRow) |
| + } |
| + if got, _ := fx.st.AccountPlan(fresh.ID); got == nil || got.Source != PlanSourceDefault || got.Sponsored != nil { |
| + t.Fatalf("an account created at the cutoff = %+v, want the default plan", got) |
| + } |
| + if got, _ := fx.st.AccountPlan(gone.ID); got != nil { |
| + t.Fatalf("a deleted account got a row: %+v", got) |
| + } |
| + if got, _ := fx.st.AccountPlan(ops.ID); got != nil { |
| + t.Fatalf("ops got a row: %+v", got) |
| + } |
| + |
| + // A console start runs it again and changes nothing. |
| + fx.srv.sponsorSettled.Store(false) |
| + fx.srv.planLimitsPass(ctx, settledNow.Add(time.Minute)) |
| + if !fx.srv.sponsorSettled.Load() { |
| + t.Fatal("a second settlement did not finish") |
| + } |
| + if again, _ := fx.st.AccountPlan(old.ID); again == nil || again.Revision != row.Revision { |
| + t.Fatalf("the rerun rewrote the sponsored row: %+v, was %+v", again, row) |
| + } |
| +} |
| + |
| +// TestSponsorCapBeforeSettlementDoesNotRefuse: before any limits pass, an |
| +// account created before the cutoff with no plan row meets no limit at a |
| +// real door, while an account created after the cutoff does. |
| +func TestSponsorCapBeforeSettlementDoesNotRefuse(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + cutoff time.Time |
| + want int |
| + }{ |
| + {"created before the cutoff", time.Now().Add(time.Hour), http.StatusOK}, |
| + {"created after the cutoff", time.Now().Add(-time.Hour), http.StatusConflict}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + atRunningCap(t, fx, 3) // the fixture's account, governed, at the free plan's 3 |
| + fx.srv.cfg.PlanCatalog = sponsorCatalog(t, tc.cutoff) |
| + acct, _ := fx.st.AccountBySqid(fx.sqid) |
| + // atRunningCap gave it a row; an existing account at switch-on has none. |
| + if _, err := fx.st.db.Exec(`DELETE FROM account_plans WHERE account_id = ?`, acct.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if fx.srv.sponsorSettled.Load() { |
| + t.Fatal("settled before any pass") |
| + } |
| + token := cliToken(t, fx, "paul@keymail.dev", "code-sponsor-cap") |
| + status, out := postJSON(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/new", map[string]string{"name": "onemore"}, token) |
| + if status != tc.want { |
| + t.Fatalf("create past the free plan's cap = %d %v, want %d", status, out, tc.want) |
| + } |
| + ctx := context.Background() |
| + for name, err := range map[string]error{ |
| + "custom domains": fx.srv.checkCustomDomains(acct), |
| + "fleets": fx.srv.checkFleets(acct), |
| + "members": fx.srv.checkMemberCap(acct, 10), |
| + } { |
| + if refused := isCap(err); refused != (tc.want != http.StatusOK) || (err != nil && !refused) { |
| + t.Errorf("%s: %v", name, err) |
| + } |
| + } |
| + l, err := fx.srv.EffectiveLimits(acct) |
| + if err != nil || (l == nil) != (tc.want == http.StatusOK) { |
| + t.Fatalf("effective limits = %+v, %v", l, err) |
| + } |
| + // Nor does the grace pass measure it, or the mail pause act on it. |
| + if err := fx.srv.planGraceAccount(ctx, acct, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if states, _ := fx.st.CapStates(acct.ID); (len(states) == 0) != (tc.want == http.StatusOK) { |
| + t.Fatalf("cap rows = %+v", states) |
| + } |
| + if paused, err := fx.srv.enforceAccountMail(ctx, acct.Sqid, planNow); err != nil || paused { |
| + t.Fatalf("mail pause = %v, %v", paused, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// failPlanWrite makes the store refuse every plan row write for accountID |
| +// (a disk-full INSERT, say) until the returned func is called. |
| +func failPlanWrite(t *testing.T, fx *consoleFixture, accountID int64) func() { |
| + t.Helper() |
| + name := fmt.Sprintf("fail_plan_%d", accountID) |
| + if _, err := fx.st.db.Exec(fmt.Sprintf(`CREATE TRIGGER %s BEFORE INSERT ON account_plans |
| + WHEN NEW.account_id = %d BEGIN SELECT RAISE(ABORT, 'database or disk is full'); END`, name, accountID)); err != nil { |
| + t.Fatal(err) |
| + } |
| + return func() { |
| + if _, err := fx.st.db.Exec(`DROP TRIGGER ` + name); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +// TestSponsorFailedWriteLeavesSettlementNotDone: a failed write leaves the |
| +// account unsponsored and unlimited, the settlement not done and the rest |
| +// of the limits pass held off; the next pass retries and finishes. |
| +func TestSponsorFailedWriteLeavesSettlementNotDone(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = sponsorCatalog(t, sponsorCutoffAt) |
| + ctx := context.Background() |
| + first := planAccount(t, fx, 501) |
| + stuck := planAccount(t, fx, 502) |
| + fresh := newPlanAccount(t, fx, 503, planNow) |
| + heal := failPlanWrite(t, fx, stuck.ID) |
| + |
| + fx.srv.planLimitsPass(ctx, settledNow) |
| + if fx.srv.sponsorSettled.Load() { |
| + t.Fatal("settlement finished with an account unsponsored") |
| + } |
| + if row, _ := fx.st.AccountPlan(first.ID); row == nil || row.Source != PlanSourceSponsored { |
| + t.Fatalf("the account that could be written = %+v", row) |
| + } |
| + if row, _ := fx.st.AccountPlan(stuck.ID); row != nil { |
| + t.Fatalf("the failed account has a row: %+v", row) |
| + } |
| + if rec, _ := readLimits(t, fx, stuck.Sqid); rec != nil { |
| + t.Fatalf("the failed account has a limits record: %+v", rec) |
| + } |
| + if l, err := fx.srv.EffectiveLimits(stuck); err != nil || l != nil { |
| + t.Fatalf("the failed account's limits = %+v, %v; want none", l, err) |
| + } |
| + if err := fx.srv.checkRunningThings(ctx, stuck, 100); err != nil { |
| + t.Fatalf("a cap check on the failed account: %v", err) |
| + } |
| + // The rest of the pass held off: no default rows, no records. |
| + if row, _ := fx.st.AccountPlan(fresh.ID); row != nil { |
| + t.Fatalf("the default pass ran past a failed settlement: %+v", row) |
| + } |
| + |
| + heal() |
| + fx.srv.planLimitsPass(ctx, settledNow.Add(time.Minute)) |
| + if !fx.srv.sponsorSettled.Load() { |
| + t.Fatal("settlement did not finish on the retry") |
| + } |
| + row, _ := fx.st.AccountPlan(stuck.ID) |
| + if row == nil || row.Source != PlanSourceSponsored || row.Sponsored == nil || *row.Sponsored != sponsorUnlimited() { |
| + t.Fatalf("the retried account = %+v", row) |
| + } |
| + if rec, _ := readLimits(t, fx, stuck.Sqid); rec == nil || rec.Revision != row.Revision { |
| + t.Fatalf("the retried account's record = %+v", rec) |
| + } |
| + if row, _ := fx.st.AccountPlan(fresh.ID); row == nil || row.Source != PlanSourceDefault { |
| + t.Fatalf("the new account after settlement = %+v", row) |
| + } |
| +} |
| + |
| +// TestSponsorSettlementWaitsForTheCutoff: a cutoff still ahead sponsors the |
| +// accounts there are and stays open; an account created before the cutoff |
| +// later never gets a default row and is sponsored by the next pass; once |
| +// the cutoff has passed by the margin, the settlement finishes. |
| +func TestSponsorSettlementWaitsForTheCutoff(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + cutoff := planNow.Add(time.Hour) |
| + fx.srv.cfg.PlanCatalog = sponsorCatalog(t, cutoff) |
| + ctx := context.Background() |
| + early := planAccount(t, fx, 501) |
| + fx.srv.planLimitsPass(ctx, planNow) |
| + if fx.srv.sponsorSettled.Load() { |
| + t.Fatal("settled before the cutoff") |
| + } |
| + if row, _ := fx.st.AccountPlan(early.ID); row == nil || row.Source != PlanSourceSponsored { |
| + t.Fatalf("early account = %+v", row) |
| + } |
| + late := newPlanAccount(t, fx, 502, planNow.Add(30*time.Minute)) |
| + if n, err := fx.st.EnsureDefaultPlans("free", cutoff, planNow); err != nil || n != 0 { |
| + t.Fatalf("default rows before the cutoff = %d, %v; want none", n, err) |
| + } |
| + fx.srv.planLimitsPass(ctx, planNow.Add(31*time.Minute)) |
| + if row, _ := fx.st.AccountPlan(late.ID); row == nil || row.Source != PlanSourceSponsored { |
| + t.Fatalf("account created before the cutoff, after the first pass = %+v", row) |
| + } |
| + fx.srv.planLimitsPass(ctx, cutoff) |
| + if fx.srv.sponsorSettled.Load() { |
| + t.Fatal("settled inside the margin") |
| + } |
| + fx.srv.planLimitsPass(ctx, cutoff.Add(sponsorSettleMargin)) |
| + if !fx.srv.sponsorSettled.Load() { |
| + t.Fatal("not settled after the margin") |
| + } |
| +} |
| + |
| +// TestSponsorLeavesARowWrittenSinceTheList: a plan written between the |
| +// settlement's list and its write (an operator, or a checkout) is kept. |
| +func TestSponsorLeavesARowWrittenSinceTheList(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = sponsorCatalog(t, sponsorCutoffAt) |
| + ctx := context.Background() |
| + acct := planAccount(t, fx, 501) |
| + if err := fx.srv.applyAccountPlan(ctx, acct, "personal", nil, 0, PlanSourceOperator, nil, "upgraded", "ops@example.com", planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + before, _ := fx.st.AccountPlan(acct.ID) |
| + if err := fx.srv.sponsorExistingAccount(ctx, acct, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if after, _ := fx.st.AccountPlan(acct.ID); after == nil || after.Revision != before.Revision || after.Source != PlanSourceOperator { |
| + t.Fatalf("row = %+v, was %+v", after, before) |
| + } |
| + // And an account deleted since the list is nothing to do. |
| + gone := planAccount(t, fx, 502) |
| + if _, err := fx.st.db.Exec(`UPDATE accounts SET deleted_at = ? WHERE id = ?`, planNow.Unix(), gone.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.srv.sponsorExistingAccount(ctx, gone, planNow); err != nil { |
| + t.Fatalf("a deleted account: %v", err) |
| + } |
| +} |
| + |
| +// Without the field nothing changes: the default pass runs as it did. |
| +func TestSponsorOffWithoutTheField(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + acct := planAccount(t, fx, 501) |
| + fx.srv.planLimitsPass(context.Background(), planNow) |
| + if row, _ := fx.st.AccountPlan(acct.ID); row == nil || row.Source != PlanSourceDefault { |
| + t.Fatalf("row = %+v, want the default plan", row) |
| + } |
| + if !fx.srv.sponsorSettled.Load() { |
| + t.Fatal("nothing to settle, but not settled") |
| + } |
| +} |
diff --git a/internal/console/server.go b/internal/console/server.go| index 97316bf34..abf8f0929 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -979,6 +979,10 @@ type Server struct { |
| // planExemptSettled is set once settlePlanExempt has cleared what plans |
| // left on the exempt account in this process (planexempt.go). |
| planExemptSettled atomic.Bool |
| + // sponsorSettled is set once settleSponsoredAccounts has sponsored |
| + // every account owed the launch sponsorship in this process |
| + // (plansponsor.go). |
| + sponsorSettled atomic.Bool |
| claimLossPageMu sync.Mutex |
| claimLossPageDone chan struct{} |
diff --git a/internal/plans/catalog.go b/internal/plans/catalog.go| index e3c3842e2..0867675f8 100644 |
| --- a/internal/plans/catalog.go |
| +++ b/internal/plans/catalog.go |
| @@ -17,6 +17,7 @@ import ( |
| "math" |
| "os" |
| "slices" |
| + "time" |
| "github.com/carlosframework/platform/internal/ratelimit" |
| ) |
| @@ -90,8 +91,16 @@ type Catalog struct { |
| Plans map[string]Plan `json:"plans"` |
| Packs map[string]Pack `json:"packs"` |
| Ceilings Limits `json:"ceilings"` |
| + // SponsorAccountsBefore, when set, is an RFC 3339 time: every account |
| + // the console created before it, and that has no plan of its own, is |
| + // sponsored with no limits when plans go on (Paul, 2026-10-31). The |
| + // console does it (internal/console/plansponsor.go). Empty is unset, and |
| + // is left out of the ID's canonical form, so a catalog without it keeps |
| + // the ID it had. |
| + SponsorAccountsBefore string `json:"sponsor_accounts_before,omitempty"` |
| - id string |
| + id string |
| + sponsorCutoff time.Time |
| } |
| var ( |
| @@ -140,6 +149,10 @@ func ParseCatalog(b []byte) (*Catalog, error) { |
| // can never claim a version whose content it does not carry. |
| func (c *Catalog) ID() string { return c.id } |
| +// SponsorCutoff is SponsorAccountsBefore as a time, or the zero time when |
| +// it is unset. |
| +func (c *Catalog) SponsorCutoff() time.Time { return c.sponsorCutoff } |
| + |
| func (c *Catalog) validate() error { |
| if c.Version == "" { |
| return errors.New("version is required") |
| @@ -153,6 +166,13 @@ func (c *Catalog) validate() error { |
| if c.FreeAccountsPerPerson < 0 { |
| return errors.New("free_accounts_per_person is negative") |
| } |
| + if c.SponsorAccountsBefore != "" { |
| + t, err := time.Parse(time.RFC3339, c.SponsorAccountsBefore) |
| + if err != nil { |
| + return fmt.Errorf("sponsor_accounts_before %q is not an RFC 3339 time, like 2026-11-01T09:00:00Z", c.SponsorAccountsBefore) |
| + } |
| + c.sponsorCutoff = t |
| + } |
| if err := c.Ceilings.nonNegative(); err != nil { |
| return fmt.Errorf("ceilings: %w", err) |
| } |
diff --git a/internal/plans/catalog_test.go b/internal/plans/catalog_test.go| index 5cc6e854c..036f95804 100644 |
| --- a/internal/plans/catalog_test.go |
| +++ b/internal/plans/catalog_test.go |
| @@ -1,10 +1,12 @@ |
| package plans |
| import ( |
| + "encoding/json" |
| "errors" |
| "os" |
| "strings" |
| "testing" |
| + "time" |
| ) |
| const examplePath = "testdata/example-catalog.json" |
| @@ -216,3 +218,47 @@ func TestEffectiveRefusesOverflow(t *testing.T) { |
| t.Fatalf("err %v (limits %+v), want ErrPackQuantity", err, got) |
| } |
| } |
| + |
| +// sponsor_accounts_before (Paul, 2026-10-31): optional, RFC 3339, and a |
| +// catalog without it keeps the ID it had. |
| +func TestCatalogSponsorAccountsBefore(t *testing.T) { |
| + base := exampleBytes(t) |
| + plain, err := ParseCatalog([]byte(base)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !plain.SponsorCutoff().IsZero() { |
| + t.Fatalf("unset cutoff = %v", plain.SponsorCutoff()) |
| + } |
| + // The ID of a catalog without the field is the one it had before the |
| + // field existed, so turning this code on republishes nothing. |
| + canon, err := json.Marshal(plain) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if strings.Contains(string(canon), "sponsor") { |
| + t.Fatalf("the canonical form of a catalog without the field names it: %s", canon) |
| + } |
| + withField := strings.Replace(base, `"default_plan": "free",`, `"default_plan": "free", "sponsor_accounts_before": "2026-11-01T09:00:00Z",`, 1) |
| + c, err := ParseCatalog([]byte(withField)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := c.SponsorCutoff(); !got.Equal(time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)) { |
| + t.Fatalf("cutoff = %v", got) |
| + } |
| + if c.ID() == plain.ID() { |
| + t.Fatal("adding the cutoff did not change the catalog ID") |
| + } |
| + for name, v := range map[string]string{ |
| + "not a time": `"tomorrow"`, |
| + "no zone": `"2026-11-01T09:00:00"`, |
| + "date only": `"2026-11-01"`, |
| + "a number": `1793523600`, |
| + } { |
| + body := strings.Replace(base, `"default_plan": "free",`, `"default_plan": "free", "sponsor_accounts_before": `+v+`,`, 1) |
| + if _, err := ParseCatalog([]byte(body)); err == nil { |
| + t.Errorf("%s: ParseCatalog accepted %s", name, v) |
| + } |
| + } |
| +} |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 79e107881..e7e121a84 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -46,3 +46,4 @@ plan14-root-reads-fleet-routes-followups.tsv 1379d066c8dd2335d95d5f6e9c7bce65ff5 |
| plan14-root-reads-tunnel-websockets.tsv 949bc734a293366e6b2700244af5110dd6e84b5432023e991c09e806afd62483 |
| plan14-root-reads-console-protection-tab.tsv eaeb153ab7a7a849edc9c6e92f2ac5c709c6e39044a647971cf1fa5ebcb660c8 |
| plan14-root-reads-devbox-mode.tsv 43d1824141f0ce7024cc3740ab5feac3f3539322f8afb856c9ca2f10d5095e95 |
| +plan14-root-reads-sponsor-existing-accounts.tsv 43d1824141f0ce7024cc3740ab5feac3f3539322f8afb856c9ca2f10d5095e95 |
diff --git a/internal/provision/testdata/plan14-root-reads-sponsor-existing-accounts.tsv b/internal/provision/testdata/plan14-root-reads-sponsor-existing-accounts.tsv| new file mode 100644 |
| index 000000000..09c07be35 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-sponsor-existing-accounts.tsv |
| @@ -0,0 +1,3 @@ |
| +# Census overlay sponsor-existing-accounts, written by census-propose (#369). census-ruling-sponsor-existing-accounts, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-sponsor-existing-accounts.md. |
| +# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@coverage internal/plans 89708b02410cd2ffa1276544a166249ed7a464a0e3d69e83afd58160d4b653f3 |