carlos / platform Public

plans: sponsor_accounts_before sponsors every account that existed before plans went on, with no limits (settled at console start and on every account insert); sponsored accounts may ship daemon and always-on releases; Billing shows Unlimited

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from sponsor-existing-accounts into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 6f1f6ca6eb436b03dad13ee9e4f4bced33cce3c9 parent 8294a52
20 files changed, +1,431 −10
  • cmd/console/main.go +12 −1
  • cmd/console/member_test.go +54 −0
  • cmd/console/plansponsor.go +55 −0
  • cmd/console/plansponsor_test.go +212 −0
  • docs/site/plans.md +2 −0
  • docs/superpowers/notes/census-proposal-sponsor-existing-accounts.md +11 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-sponsor-existing-accounts.md +34 −0
  • internal/console/accountplans.go +81 −0
  • internal/console/billingpage.go +16 −3
  • internal/console/billingpage_copy.go +1 −0
  • internal/console/billingusage.go +4 −0
  • internal/console/plancaps.go +18 −1
  • internal/console/plansponsor.go +214 −0
  • internal/console/plansponsor_test.go +565 −0
  • internal/console/store.go +46 −4
  • internal/console/store_gate.go +3 −0
  • internal/plans/catalog.go +37 −1
  • internal/plans/catalog_test.go +62 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-sponsor-existing-accounts.tsv +3 −0

CI passed — run details

diff --git a/cmd/console/main.go b/cmd/console/main.go
index ceda10c5a..e13fd40cd 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -370,9 +370,20 @@ func serve() {
// A broken catalog must never quietly mean "no limits".
log.Fatalf("console: CARLOS_PLAN_CATALOG: %v", err)
}
+ // The launch sponsorship (internal/console/plansponsor.go), settled
+ // HERE: before NewServer materializes the bucket's accounts, and before
+ // any worker or the listener. It records the rule every account insert
+ // applies from then on. One that does not settle runs this start with
+ // plans and billing off, never with plans on and the rule unrecorded.
+ // An old rule that could not be removed stops the start: systemd
+ // restarts the console, and no stale rule outlives a start.
+ catalog, plansOff, err := sponsorAtStart(st, catalog, time.Now())
+ if err != nil {
+ log.Fatalf("console: launch sponsorship: %v", err)
+ }
// Billing (plans 6a): dormant unless CARLOS_BILLING is test or live.
// Every failure names the variable, never its value.
- billingCfg, err := billingConfig(os.Getenv, catalog)
+ billingCfg, err := billingConfigFor(os.Getenv, catalog, plansOff)
if err != nil {
log.Fatal(err)
}
diff --git a/cmd/console/member_test.go b/cmd/console/member_test.go
index 86cfe264d..84781388b 100644
--- a/cmd/console/member_test.go
+++ b/cmd/console/member_test.go
@@ -2,6 +2,7 @@ package main_test
import (
"fmt"
+ "os"
"path/filepath"
"strings"
"testing"
@@ -9,6 +10,7 @@ import (
"github.com/carlosframework/platform/internal/console"
"github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/plans"
"github.com/carlosframework/platform/internal/release"
)
@@ -393,3 +395,55 @@ func TestCLIMembershipTransition(t *testing.T) {
t.Fatalf("members = %d, %v; want 13", n, err)
}
}
+
+// `console member` loads no catalog and takes no lock, yet it materializes
+// accounts. A manifest a CLI mint published after the console's start,
+// created before the launch sponsorship's cutoff, still arrives with its
+// sponsored row: the rule is in the database (internal/console
+// plansponsor.go), and the verb's insert applies it (Astra R2 finding 1).
+func TestMemberVerbMaterializesALateAccountSponsored(t *testing.T) {
+ bin := buildConsole(t)
+ tmp := t.TempDir()
+ dbPath := filepath.Join(tmp, "console.db")
+ bucket := filepath.Join(tmp, "bucket")
+ run := runner(t, bin, "CONSOLE_DB="+dbPath, "CARLOS_DEPLOYMENT_DIR="+bucket, "CARLOS_PLAN_CATALOG=")
+
+ // The console's start: the catalog's rule recorded on the database.
+ cutoff := time.Now().Add(-time.Hour).Truncate(time.Second)
+ b, err := os.ReadFile("../../internal/plans/testdata/example-catalog.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ cat, err := plans.ParseCatalog([]byte(strings.Replace(string(b), `"default_plan": "free",`,
+ `"default_plan": "free", "sponsor_accounts_before": "`+cutoff.UTC().Format(time.RFC3339)+`",`, 1)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ st, err := console.Open(dbPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := console.SettleLaunchSponsorship(st, cat, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ st.Close()
+
+ // Then a manifest created before the cutoff lands in the bucket.
+ const id = int64(42)
+ sqid := domains.Sqid(id)
+ if err := console.WriteAccountManifest(t.Context(), release.NewDirStore(bucket), id, sqid, "Late", cutoff.Add(-time.Minute)); err != nil {
+ t.Fatal(err)
+ }
+ if out, err := run("member", "-add", "paul@keymail.dev", sqid, "-role", "owner"); err != nil {
+ t.Fatalf("member -add: %v\n%s", err, out)
+ }
+ st, err = console.Open(dbPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer st.Close()
+ row, err := st.AccountPlan(id)
+ if err != nil || row == nil || row.Source != console.PlanSourceSponsored || row.Sponsored == nil {
+ t.Fatalf("the late account's plan row = %+v, %v; want the launch sponsorship", row, err)
+ }
+}
diff --git a/cmd/console/plansponsor.go b/cmd/console/plansponsor.go
new file mode 100644
index 000000000..e4b1d66d8
--- /dev/null
+++ b/cmd/console/plansponsor.go
@@ -0,0 +1,55 @@
+package main
+
+import (
+ "errors"
+ "log"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/console"
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+// sponsorAtStart settles the catalog's launch sponsorship
+// (console.SettleLaunchSponsorship): it records the rule every account
+// insert applies, and applies it to the accounts already here. It returns
+// the catalog to serve with. When a cutoff does not settle, plans are off
+// for this start: no catalog, as if none were configured, said loudly, and
+// plansOff is true so billing is left off rather than refusing the start.
+// The next start tries again.
+//
+// When an old rule could not be removed (console.ErrLaunchRuleNotCleared)
+// it returns the error and the console must not start: the stale rule
+// would go on sponsoring every account inserted under a catalog that no
+// longer asks for it. systemd restarts the console.
+func sponsorAtStart(st *console.Store, cat *plans.Catalog, now time.Time) (_ *plans.Catalog, plansOff bool, _ error) {
+ n, err := console.SettleLaunchSponsorship(st, cat, now)
+ if errors.Is(err, console.ErrLaunchRuleNotCleared) {
+ return nil, true, err
+ }
+ if err != nil {
+ log.Printf("console: PLANS ARE OFF: CARLOS_PLAN_CATALOG is set, but its launch sponsorship "+
+ "(sponsor_accounts_before) did not settle: %v. This console runs with no plans and no billing; "+
+ "fix it and restart, and the next start tries again", err)
+ return nil, true, nil
+ }
+ if n > 0 {
+ log.Printf("console: sponsored %d existing accounts with no limits (created before %s)", n,
+ cat.SponsorCutoff().UTC().Format(time.RFC3339))
+ }
+ return cat, false, nil
+}
+
+// billingConfigFor is billingConfig, except that billing stays off,
+// loudly, on a start whose plans sponsorAtStart turned off: billing needs a
+// catalog, and refusing the start would take the whole console down for a
+// sponsorship the next start retries.
+func billingConfigFor(getenv func(string) string, cat *plans.Catalog, plansOff bool) (*console.BillingConfig, error) {
+ if plansOff {
+ if mode := strings.TrimSpace(getenv("CARLOS_BILLING")); mode != "" && mode != "off" {
+ log.Print("console: BILLING IS OFF: CARLOS_BILLING is set, but billing needs plans, which are off for this start")
+ }
+ return nil, nil
+ }
+ return billingConfig(getenv, cat)
+}
diff --git a/cmd/console/plansponsor_test.go b/cmd/console/plansponsor_test.go
new file mode 100644
index 000000000..e7f58abf8
--- /dev/null
+++ b/cmd/console/plansponsor_test.go
@@ -0,0 +1,212 @@
+package main
+
+import (
+ "database/sql"
+ "errors"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/console"
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+func sponsorTestCatalog(t *testing.T, cutoff time.Time) *plans.Catalog {
+ t.Helper()
+ b, err := os.ReadFile("../../internal/plans/testdata/example-catalog.json")
+ 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)
+ }
+ return c
+}
+
+// A sponsorship that does not settle leaves this start with plans off and
+// billing off, never with plans on: the account it was for never sees the
+// default plan's limits. One that settles keeps the catalog.
+func TestSponsorAtStart(t *testing.T) {
+ st, err := console.Open(filepath.Join(t.TempDir(), "console.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { st.Close() })
+ now := time.Unix(1_800_000_000, 0)
+ if err := st.CreateAccount(501, domains.Sqid(501), "acct", "owner@example.com", now.Add(-48*time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ env := func(k string) string {
+ if k == "CARLOS_BILLING" {
+ return "test" // and nothing else set: billingConfig would refuse
+ }
+ return ""
+ }
+
+ cat, off, err := sponsorAtStart(st, sponsorTestCatalog(t, now.Add(time.Hour)), now)
+ if cat != nil || !off || err != nil {
+ t.Fatalf("future cutoff: catalog %v, plans off %v; want none, off", cat != nil, off)
+ }
+ if b, err := billingConfigFor(env, cat, off); b != nil || err != nil {
+ t.Fatalf("billing with plans off = %v, %v; want off, no error", b, err)
+ }
+ if _, err := billingConfigFor(env, nil, false); err == nil {
+ t.Fatal("billing with no catalog configured at all no longer refuses")
+ }
+
+ want := sponsorTestCatalog(t, now.Add(-time.Hour))
+ cat, off, err = sponsorAtStart(st, want, now)
+ if cat != want || off || err != nil {
+ t.Fatalf("past cutoff: catalog kept %v, plans off %v", cat == want, off)
+ }
+}
+
+// An old rule that cannot be removed stops the start (Astra R3): left in
+// place, it would go on sponsoring every account inserted, whatever this
+// start's catalog says.
+func TestSponsorAtStartStopsWhenTheOldRuleStays(t *testing.T) {
+ dbPath := filepath.Join(t.TempDir(), "console.db")
+ st, err := console.Open(dbPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { st.Close() })
+ now := time.Unix(1_800_000_000, 0)
+ if _, _, err := sponsorAtStart(st, sponsorTestCatalog(t, now.Add(-time.Hour)), now); err != nil {
+ t.Fatal(err)
+ }
+ // The database refuses the delete (a failing disk, say).
+ raw, err := sql.Open("sqlite", dbPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { raw.Close() })
+ if _, err := raw.Exec(`CREATE TRIGGER keep_rule BEFORE DELETE ON plan_launch_sponsorship
+ BEGIN SELECT RAISE(ABORT, 'disk I/O error'); END`); err != nil {
+ t.Fatal(err)
+ }
+ noCutoff, err := plans.LoadCatalog("../../internal/plans/testdata/example-catalog.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for name, cat := range map[string]*plans.Catalog{
+ "plans off": nil,
+ "no cutoff": noCutoff,
+ "a refused cutoff": sponsorTestCatalog(t, now.Add(time.Hour)),
+ } {
+ got, off, err := sponsorAtStart(st, cat, now)
+ if !errors.Is(err, console.ErrLaunchRuleNotCleared) || got != nil || !off {
+ t.Errorf("%s: catalog %v, plans off %v, err %v; want the start stopped", name, got != nil, off, err)
+ }
+ }
+}
+
+// serve() is not callable from a test, so this reads main.go: serve()
+// settles the sponsorship (sponsorAtStart) once, on the catalog
+// planCatalog loaded, and before billing, console.NewServer, every
+// worker, the listener and Serve. That ordering is what makes "owed and
+// not yet sponsored" impossible while the console serves.
+func TestServeSettlesTheSponsorshipBeforeItServes(t *testing.T) {
+ f, err := parser.ParseFile(token.NewFileSet(), "main.go", nil, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var serve *ast.FuncDecl
+ for _, d := range f.Decls {
+ if fn, ok := d.(*ast.FuncDecl); ok && fn.Name.Name == "serve" {
+ serve = fn
+ }
+ }
+ if serve == nil {
+ t.Fatal("no serve() in main.go")
+ }
+ first := map[string]token.Pos{}
+ count := map[string]int{}
+ ast.Inspect(serve.Body, func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ name := ""
+ switch fun := call.Fun.(type) {
+ case *ast.Ident:
+ name = fun.Name
+ case *ast.SelectorExpr:
+ if x, ok := fun.X.(*ast.Ident); ok {
+ name = x.Name + "." + fun.Sel.Name
+ } else {
+ name = "." + fun.Sel.Name
+ }
+ }
+ if name == "" {
+ return true
+ }
+ count[name]++
+ if _, seen := first[name]; !seen {
+ first[name] = call.Pos()
+ }
+ return true
+ })
+ if count["sponsorAtStart"] != 1 {
+ t.Fatalf("serve() calls sponsorAtStart %d times, want once", count["sponsorAtStart"])
+ }
+ at := first["sponsorAtStart"]
+ if p, ok := first["planCatalog"]; !ok || p > at {
+ t.Error("sponsorAtStart runs before planCatalog loads the catalog")
+ }
+ for _, later := range []string{"billingConfigFor", "console.NewServer", "srv.RunClaimWorker", "net.Listen", "httpSrv.Serve", "NotifyReady"} {
+ p, ok := first[later]
+ if !ok {
+ t.Errorf("serve() no longer calls %s; update this test", later)
+ continue
+ }
+ if p < at {
+ t.Errorf("%s runs before the sponsorship settles", later)
+ }
+ }
+ if !fatalsOnSponsorError(serve.Body) {
+ t.Error("serve() does not stop with log.Fatal when sponsorAtStart returns an error")
+ }
+ if count["billingConfig"] != 0 {
+ t.Error("serve() calls billingConfig directly; billing must go through billingConfigFor so a start with plans off keeps billing off")
+ }
+}
+
+// fatalsOnSponsorError reports whether body has `..., err := sponsorAtStart(...)`
+// followed at once by `if err != nil { log.Fatalf(...) }`.
+func fatalsOnSponsorError(body *ast.BlockStmt) bool {
+ for i, st := range body.List {
+ as, ok := st.(*ast.AssignStmt)
+ if !ok || len(as.Rhs) != 1 || len(as.Lhs) != 3 || i+1 >= len(body.List) {
+ continue
+ }
+ call, ok := as.Rhs[0].(*ast.CallExpr)
+ if !ok || !isIdent(call.Fun, "sponsorAtStart") || !isIdent(as.Lhs[2], "err") {
+ continue
+ }
+ ifs, ok := body.List[i+1].(*ast.IfStmt)
+ if !ok || len(ifs.Body.List) == 0 {
+ return false
+ }
+ es, ok := ifs.Body.List[0].(*ast.ExprStmt)
+ if !ok {
+ return false
+ }
+ fatal, ok := es.X.(*ast.CallExpr)
+ if !ok {
+ return false
+ }
+ sel, ok := fatal.Fun.(*ast.SelectorExpr)
+ return ok && isIdent(sel.X, "log") && sel.Sel.Name == "Fatalf"
+ }
+ return false
+}
diff --git a/docs/site/plans.md b/docs/site/plans.md
index 05715b662..5f7e15dd1 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 no later than the console's start, 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. If the console can't do that when it starts, it runs with plans off and logs why.
+
## 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..b214f9381
--- /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: `7570ca617863882780c1c5a7d04430b578a297ee4d72ca25acc1cdc5288ca283` → `7570ca617863882780c1c5a7d04430b578a297ee4d72ca25acc1cdc5288ca283`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-sponsor-existing-accounts.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-sponsor-existing-accounts.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-sponsor-existing-accounts.md
new file mode 100644
index 000000000..5a0207cae
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-sponsor-existing-accounts.md
@@ -0,0 +1,34 @@
+# Review brief: branch sponsor-existing-accounts, round 3 of 3
+
+Repo carlos/platform, branch `sponsor-existing-accounts`, the commit that adds this brief (named in your prompt).
+Under review: the diff `origin/main...HEAD`. Paul's ruling (2026-10-31): every account that exists when plan limits switch on is sponsored with no limits, so no existing user hits a cap or has to pay; new accounts get normal plans. A new optional catalog field `sponsor_accounts_before` (RFC 3339) names the cutoff. Round 1 (findings in `~/.cache/sponsor-existing-accounts/review-r1.md`, all four addressed) led to a redesign. Settlement is now synchronous at console startup (`sponsorAtStart` / `SettleLaunchSponsorship` / `Store.SponsorExistingAccounts`), before billing, NewServer, workers and the listener. It writes every sponsored row in one transaction. A future cutoff, an unreadable account manifest or a failed write makes that start run with plans and billing off. The derived `sponsorOwed` gate was removed. Paul's rulings, added in this round: sponsored rows are exempt from the plan 3b daemon and always-on refusals; the billing page shows "Unlimited" for sponsored values.
+
+## Invariant
+
+No limit, cap, grace step, mail pause, throttle or limits record acts on an account that is owed a sponsorship, at any point, including before settlement, during a failed settlement, and across console restarts. Settlement never overwrites a row written by an operator or a checkout.
+
+## Round 3 (final)
+
+Round 2 (`~/.cache/sponsor-existing-accounts/review-r2.md`) found a P1, late materialization escaping sponsorship, and a P2, fractional cutoffs. Paul chose the structural fix for the P1: **sponsor on insert.** The rule lives in a one-row table, `plan_launch_sponsorship`. `SettleLaunchSponsorship` records the rule at startup and sponsors the existing accounts in the same transaction. A start with plans off clears it. Every account insert (`CreateAccount`, `EnsureAccount` used by NewServer materialization, `console member` and late CLI mints, and the ops backfill) applies the rule in its own transaction. The invariant is stated in `internal/console/plansponsor.go`. Fractional cutoffs are refused before parsing.
+
+## What to check
+
+1. The invariant holds on every path that makes an account row exist. Hunt for any insert into `accounts` that bypasses the rule, and for any way an account becomes visible to enforcement or checkout before its row commits.
+2. Clearing and recording the rule can't leave it stale or wrong: a plans-off start clears it, and a `console member` run concurrent with a console start is safe.
+3. The P2 fix is complete.
+4. Earlier rounds' fault families don't recur (enforcement consistency, the payment boundary, settlement completeness, cutoff precision).
+5. Census: the `internal/plans` envelope was re-pinned at this commit. Approve or reject it. Also check that the new table's classification in the claim SQL gate is right.
+
+This is the final round. Report only real defects. P3s go on a follow-up list.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round.
+
+## Output
+
+Findings ranked P1, P2, P3 with file:line, failure scenario and fix, then the census verdict. End with exactly one verdict: **READY**, **READY AFTER FIXES**, or **NOT READY**.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
diff --git a/internal/console/accountplans.go b/internal/console/accountplans.go
index 87a84d482..f9c8d0dfb 100644
--- a/internal/console/accountplans.go
+++ b/internal/console/accountplans.go
@@ -4,6 +4,7 @@ import (
"database/sql"
"encoding/json"
"errors"
+ "fmt"
"slices"
"strings"
"time"
@@ -255,6 +256,86 @@ func (s *Store) EnsureDefaultPlans(defaultPlan string, now time.Time) (int, erro
return int(n), err
}
+// StartLaunchSponsorship records the launch sponsorship rule
+// (plansponsor.go) and applies it to every account already in the
+// database, in one transaction: cat's default plan, source sponsored, with
+// sponsored, reason and by, for every live account created before cutoff
+// with no plan row, the exempt account aside. Insert-only. Each row is
+// priced first, at the account's member count, as the operator door
+// prices one; an account the catalog cannot price fails the whole
+// transaction, and nothing is written, the rule included. It reports how
+// many rows it wrote.
+//
+// It runs before the console serves, so nothing else writes plans then.
+// Of the plan transition (transitionAccountPlan) nothing is owed: an
+// account with no row has no lapse to start, no throttle or cap rows to
+// reset, and nothing published; the first limits pass publishes the rows
+// (revision 1, published 0) and the first grace pass measures them.
+func (s *Store) StartLaunchSponsorship(cat *plans.Catalog, cutoff time.Time, sponsored plans.Limits, reason, by string, now time.Time) (int, error) {
+ if cutoff.IsZero() {
+ return 0, errors.New("console: launch sponsorship with no cutoff")
+ }
+ sj, err := json.Marshal(sponsored)
+ if err != nil {
+ return 0, err
+ }
+ rule := &launchRule{cutoff: cutoff.Unix(), plan: cat.DefaultPlan, sponsored: string(sj), reason: reason, by: by}
+ tx, err := s.db.Begin()
+ if err != nil {
+ return 0, err
+ }
+ defer tx.Rollback()
+ if _, err := tx.Exec(`INSERT INTO plan_launch_sponsorship (id, cutoff, plan, sponsored, reason, updated_by, updated_at)
+ VALUES (1, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET cutoff = excluded.cutoff, plan = excluded.plan,
+ sponsored = excluded.sponsored, reason = excluded.reason, updated_by = excluded.updated_by, updated_at = excluded.updated_at`,
+ rule.cutoff, rule.plan, rule.sponsored, rule.reason, rule.by, now.Unix()); err != nil {
+ return 0, err
+ }
+ type candidate struct{ id, created int64 }
+ rows, err := tx.Query(`SELECT id, created_at FROM accounts
+ WHERE deleted_at = 0 AND id NOT IN (SELECT account_id FROM account_plans) ORDER BY id`)
+ if err != nil {
+ return 0, err
+ }
+ var all []candidate
+ for rows.Next() {
+ var c candidate
+ if err := rows.Scan(&c.id, &c.created); err != nil {
+ rows.Close()
+ return 0, err
+ }
+ all = append(all, c)
+ }
+ rows.Close()
+ if err := rows.Err(); err != nil {
+ return 0, err
+ }
+ n := 0
+ for _, c := range all {
+ if c.id == s.planExemptID || c.created >= rule.cutoff {
+ continue
+ }
+ members, err := teamMembers(cat, cat.DefaultPlan, 0, func() (int, error) { return memberCountOn(tx, c.id) })
+ if err != nil {
+ return 0, err
+ }
+ if _, err := cat.Effective(cat.DefaultPlan, nil, &sponsored, members); err != nil {
+ return 0, fmt.Errorf("account %d: %w", c.id, err)
+ }
+ wrote, err := rule.apply(tx, s.planExemptID, c.id, c.created, now)
+ if err != nil {
+ return 0, fmt.Errorf("account %d: %w", c.id, err)
+ }
+ if wrote {
+ n++
+ }
+ }
+ if err := tx.Commit(); err != nil {
+ return 0, err
+ }
+ return n, nil
+}
+
// PlansToPublish lists live accounts whose bucket record is behind their
// row (an unpublished revision, or a record from another catalog), in
// account order after afterAccountID, so a caller can page past rows it
diff --git a/internal/console/billingpage.go b/internal/console/billingpage.go
index dc027c2c3..30340c519 100644
--- a/internal/console/billingpage.go
+++ b/internal/console/billingpage.go
@@ -439,7 +439,11 @@ func (s *Server) billingViewFor(r *http.Request, in billingPageInput, st billing
// when billing wrote some, as enforcement counts them (teamMembers).
limitedAt, _ := teamMembers(cat, plan, seats, func() (int, error) { return members, nil })
if l, err := cat.Effective(plan, held, sponsored, limitedAt); err == nil {
- v.Includes = planIncludes(l, p.MaxMembers)
+ maxMembers := p.MaxMembers
+ if in.Row != nil && planRowSponsored(in.Row) {
+ maxMembers = 0 // checkMemberCap passes a sponsored row
+ }
+ v.Includes = planIncludes(l, maxMembers)
v.limits = &l
}
}
@@ -730,14 +734,17 @@ func billingDate(t time.Time) string { return t.UTC().Format("2 January 2006") }
// planIncludes is a few of l's limits as a plan card lists them, in the
// words `carlos accounts plan` uses: apps and instances, sleeps after,
// disk per app, custom domains, and the member cap of a plan that has one
-// (maxMembers, 0 for none). A limit of 0 is left out.
+// (maxMembers, 0 for none). A limit of 0 is left out, and so is an idle
+// window at the launch sponsorship's figure: the plan then sets none, and
+// apps sleep when the deployment's own idle window says. A count or size
+// at that figure reads "Unlimited" (billingCount, billingBytes).
func planIncludes(l plans.Limits, maxMembers int) []billingInclude {
var out []billingInclude
add := func(text string) { out = append(out, billingInclude{Text: text}) }
if l.RunningThings > 0 {
out = append(out, billingInclude{Text: fmt.Sprintf(billingCopy["limit.running"], billingCount(int64(l.RunningThings))), running: true})
}
- if l.IdleSeconds > 0 {
+ if l.IdleSeconds > 0 && l.IdleSeconds != sponsorUnlimitedIdle {
add(fmt.Sprintf(billingCopy["limit.idle"], billingDuration(l.IdleSeconds)))
}
if l.DiskBytes > 0 {
@@ -781,6 +788,9 @@ func packAdds(a plans.Limits) string {
// the catalog's numbers are written in (as accounts_plan.go's planBytes).
func billingBytes(b int64) string {
const mb, gb = 1 << 20, 1 << 30
+ if b == sponsorMost {
+ return billingCopy["limit.unlimited"]
+ }
if b >= gb {
if b%gb == 0 {
return billingCount(b/gb) + " GB"
@@ -792,6 +802,9 @@ func billingBytes(b int64) string {
// billingCount is n with its thousands grouped: 1000 is "1,000".
func billingCount(n int64) string {
+ if n == sponsorMost {
+ return billingCopy["limit.unlimited"]
+ }
if n < 0 {
return "-" + billingCount(-n)
}
diff --git a/internal/console/billingpage_copy.go b/internal/console/billingpage_copy.go
index 9f8f33381..52facf5c7 100644
--- a/internal/console/billingpage_copy.go
+++ b/internal/console/billingpage_copy.go
@@ -136,6 +136,7 @@ var billingCopy = map[string]string{
"limit.bandwidth": "%s bandwidth a month",
"limit.domains": "Custom domains",
"limit.members": "Up to %d members",
+ "limit.unlimited": "Unlimited", // in place of a number at the launch sponsorship's figure (plansponsor.go); DRAFT 2026-10-31
"duration.second": "%d second",
"duration.seconds": "%d seconds",
"duration.minute": "%d minute",
diff --git a/internal/console/billingusage.go b/internal/console/billingusage.go
index 4f3f7a949..5c14518b4 100644
--- a/internal/console/billingusage.go
+++ b/internal/console/billingusage.go
@@ -123,6 +123,10 @@ func useOfLimit(used map[capID]int64, c capID, limit int64) *billingUse {
case capBandwidth:
key = "usage.of_month"
}
+ if limit == sponsorMost {
+ // No limit to be "of": the launch sponsorship's figure.
+ return &billingUse{Text: fmt.Sprintf(billingCopy["usage.you_use"], capAmount(c, n))}
+ }
return &billingUse{Text: fmt.Sprintf(billingCopy[key], capAmount(c, n), capAmount(c, limit)), Level: useLevel(c, n, limit)}
}
diff --git a/internal/console/plancaps.go b/internal/console/plancaps.go
index 3a76cedfb..412745eee 100644
--- a/internal/console/plancaps.go
+++ b/internal/console/plancaps.go
@@ -16,7 +16,9 @@ import (
"github.com/carlosframework/platform/internal/schedule"
)
-// Creation caps (plans-caps-packs spec §5.1, §8.1, §8.4; plans 3a). Every
+// Creation caps (plans-caps-packs spec §5.1, §8.1, §8.4; plans 3a). The
+// daemon and always-on refusals on shared boxes (plans 3b) pass a
+// sponsored account (planSponsored; Paul, 2026-10-31). Every
// check passes when plans are off (EffectiveLimits nil), so a deployment
// without a catalog sees no change. A refusal is a *planCapError carrying
// approved copy; JSON doors answer it 409 {"code":"cap"} and browser doors
@@ -319,6 +321,9 @@ func (s *Server) checkDaemon(acct *Account, app string) error {
if err != nil || l == nil {
return err
}
+ if sp, err := s.planSponsored(acct); err != nil || sp {
+ return err
+ }
if own, err := s.onOwnBoxes(acct, app); err != nil || own {
return err
}
@@ -346,6 +351,9 @@ func (s *Server) checkDaemonVersion(ctx context.Context, acct *Account, app, ver
if err != nil || l == nil {
return err
}
+ if sp, err := s.planSponsored(acct); err != nil || sp {
+ return err
+ }
if own, err := s.onOwnBoxes(acct, app); err != nil || own {
return err
}
@@ -380,6 +388,9 @@ func (s *Server) rollbackDaemonGuard(ctx context.Context, acct *Account, app, ch
if err != nil || l == nil {
return nil, err
}
+ if sp, err := s.planSponsored(acct); err != nil || sp {
+ return nil, err
+ }
if own, err := s.onOwnBoxes(acct, app); err != nil || own {
return nil, err
}
@@ -426,6 +437,9 @@ func (s *Server) checkAlwaysOnCreate(acct *Account, app string) error {
if err != nil || l == nil {
return err
}
+ if sp, err := s.planSponsored(acct); err != nil || sp {
+ return err
+ }
if own, err := s.onOwnBoxes(acct, app); err != nil || own {
return err
}
@@ -448,6 +462,9 @@ func (s *Server) checkAlwaysOn(ctx context.Context, acct *Account, app string) e
if l == nil {
return nil
}
+ if sp, err := s.planSponsored(acct); err != nil || sp {
+ return err
+ }
recs, err := provision.ListSidecarRecordsStrict(ctx, s.cfg.Releases, acct.Sqid, app)
if err != nil {
return err
diff --git a/internal/console/plansponsor.go b/internal/console/plansponsor.go
new file mode 100644
index 000000000..7439dcd89
--- /dev/null
+++ b/internal/console/plansponsor.go
@@ -0,0 +1,214 @@
+package console
+
+import (
+ "database/sql"
+ "errors"
+ "fmt"
+ "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.
+//
+// THE INVARIANT: while plans are on with a cutoff, no account created
+// before the cutoff is ever visible without a plan row, and the row the
+// rule gives it is the sponsored one. (An account that already had a row
+// of its own when the rule reached it, an operator's or billing's, keeps
+// it.) It is held by one rule, in the store, enforced where accounts are
+// inserted (Paul's ruling after Astra R2, stopping rule 2):
+//
+// - At start, before the console has a Server (cmd/console serve:
+// before NewServer, any door, worker, pass or listener),
+// SettleLaunchSponsorship records the rule in plan_launch_sponsorship
+// and, in the same transaction, applies it to every account already in
+// the database. It refuses a cutoff after the start.
+// - Every account insert reads the recorded rule inside its own
+// transaction and applies it there (Store.sponsorOnInsertTx): a
+// console mint (CreateAccount), materialization from a bucket manifest
+// (EnsureAccount: NewServer's, `console member`'s, a manifest a CLI
+// mint published late), and the ops backfill. An account and its
+// sponsored row commit together, so no reader sees one without the
+// other.
+// - The rule lives in the database, not in the process, so `console
+// member`, an offline verb that loads no catalog and takes no lock,
+// applies it too.
+// - A start with plans off (no catalog, no cutoff, or a sponsorship that
+// did not settle) clears the rule. Accounts inserted then get no row,
+// and the next start with the cutoff sponsors them, before it serves.
+//
+// The ops account (planExempt) is never sponsored: it has no plan.
+
+// 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"
+
+// sponsorMost is sponsorUnlimited's figure for every count and size.
+const sponsorMost = math.MaxInt64 / 4
+
+// sponsorUnlimitedIdle is sponsorUnlimited's idle_seconds.
+const sponsorUnlimitedIdle = int(math.MaxInt64 / int64(time.Second))
+
+// 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.
+//
+// The mail pause still never goes above the catalog's email ceiling
+// (Paul, 2026-10-31). The daemon and always-on refusals on shared boxes do
+// not apply to a sponsored account (planSponsored).
+func sponsorUnlimited() plans.Limits {
+ return plans.Limits{
+ RunningThings: sponsorMost,
+ SidecarsPerApp: sponsorMost,
+ IdleSeconds: sponsorUnlimitedIdle,
+ MemoryTier: plans.MemoryDefault,
+ AwakeHoursMonth: sponsorMost,
+ DiskBytes: sponsorMost,
+ StorageBytes: sponsorMost,
+ StorageSelfServe: true,
+ EmailPerDay: sponsorMost,
+ BandwidthBytesMonth: sponsorMost,
+ CustomDomains: true,
+ Fleets: true,
+ MinScheduleSeconds: 1,
+ HistoryDays: int(math.MaxInt64 / int64(24*time.Hour)),
+ RateClientShare: ratelimit.MaxValue,
+ RatePerSecond: ratelimit.MaxValue,
+ RateBurst: ratelimit.MaxValue,
+ }
+}
+
+// SettleLaunchSponsorship records cat's launch sponsorship rule on st and
+// applies it to every account already there, in one transaction
+// (Store.StartLaunchSponsorship). It must finish before the console
+// serves. It reports how many accounts it sponsored. With no catalog, or a
+// catalog without sponsor_accounts_before, it clears the rule and
+// sponsors nothing. A cutoff after now is refused. On any error the rule
+// is cleared and the caller must run with no catalog: plans off, and the
+// next start retries.
+//
+// An error that wraps ErrLaunchRuleNotCleared means the clearing itself
+// failed, so an old rule may still be recorded and would go on sponsoring
+// every account inserted. The console must not start then (Astra R3).
+func SettleLaunchSponsorship(st *Store, cat *plans.Catalog, now time.Time) (int, error) {
+ if cat == nil || cat.SponsorCutoff().IsZero() {
+ return 0, clearLaunchRule(st)
+ }
+ cutoff := cat.SponsorCutoff()
+ if cutoff.After(now) {
+ return 0, errors.Join(fmt.Errorf("sponsor_accounts_before %s is after the console's start (%s): set it to when plans go on, not later",
+ cutoff.UTC().Format(time.RFC3339), now.UTC().Format(time.RFC3339)), clearLaunchRule(st))
+ }
+ n, err := st.StartLaunchSponsorship(cat, cutoff, sponsorUnlimited(), planSponsorReason, planDefaultActor, now)
+ if err != nil {
+ return 0, errors.Join(fmt.Errorf("writing the sponsored plans: %w", err), clearLaunchRule(st))
+ }
+ return n, nil
+}
+
+// ErrLaunchRuleNotCleared marks a SettleLaunchSponsorship error in which
+// the recorded rule could not be removed.
+var ErrLaunchRuleNotCleared = errors.New("the recorded launch sponsorship rule could not be removed")
+
+// clearLaunchRule is ClearLaunchSponsorship, its failure marked
+// ErrLaunchRuleNotCleared.
+func clearLaunchRule(st *Store) error {
+ if err := st.ClearLaunchSponsorship(); err != nil {
+ return fmt.Errorf("%w: %w", ErrLaunchRuleNotCleared, err)
+ }
+ return nil
+}
+
+// launchRule is the recorded launch sponsorship rule.
+type launchRule struct {
+ cutoff int64 // unix seconds; accounts created before it are sponsored
+ plan string
+ sponsored string // the sponsored limits, JSON
+ reason string
+ by string
+}
+
+// launchRuleOn reads the recorded rule, nil when there is none.
+func launchRuleOn(q sqlQueryRower) (*launchRule, error) {
+ var r launchRule
+ err := q.QueryRow(`SELECT cutoff, plan, sponsored, reason, updated_by FROM plan_launch_sponsorship WHERE id = 1`).
+ Scan(&r.cutoff, &r.plan, &r.sponsored, &r.reason, &r.by)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return &r, nil
+}
+
+// apply is the rule for one account, inside tx: an account other than
+// exemptID created before the cutoff gets the sponsored row, unless it
+// already has a row. It reports whether it wrote one.
+func (r *launchRule) apply(tx *sql.Tx, exemptID, accountID, created int64, now time.Time) (bool, error) {
+ if accountID == exemptID || created >= r.cutoff {
+ return false, nil
+ }
+ res, err := tx.Exec(`INSERT INTO account_plans
+ (account_id, plan, packs, seats, source, sponsored, reason, revision, updated_by, updated_at)
+ VALUES (?, ?, '{}', 0, ?, ?, ?, 1, ?, ?) ON CONFLICT(account_id) DO NOTHING`,
+ accountID, r.plan, PlanSourceSponsored, r.sponsored, r.reason, r.by, now.Unix())
+ if err != nil {
+ return false, err
+ }
+ n, err := res.RowsAffected()
+ return n > 0, err
+}
+
+// sponsorOnInsertTx applies the recorded rule to an account inserted in tx
+// at created. Every account insert calls it before it commits. The row is
+// not priced here: an account being inserted has at most its first owner,
+// and only a team plan's member count can make a sponsored assignment
+// unpriceable.
+func (s *Store) sponsorOnInsertTx(tx *sql.Tx, accountID int64, created time.Time) error {
+ r, err := launchRuleOn(tx)
+ if err != nil || r == nil {
+ return err
+ }
+ _, err = r.apply(tx, s.planExemptID, accountID, created.Unix(), time.Now())
+ return err
+}
+
+// ClearLaunchSponsorship removes the recorded rule: plans are off, or run
+// without a cutoff.
+func (s *Store) ClearLaunchSponsorship() error {
+ _, err := s.db.Exec(`DELETE FROM plan_launch_sponsorship`)
+ return err
+}
+
+// planSponsored reports whether acct's plan row is sponsored (an operator's
+// sponsorship or the launch's). The daemon and always-on refusals on
+// shared boxes (plans 3b) do not apply to it (Paul, 2026-10-31).
+func (s *Server) planSponsored(acct *Account) (bool, error) {
+ row, err := s.store.AccountPlan(acct.ID)
+ if err != nil {
+ return false, err
+ }
+ return row != nil && planRowSponsored(row), nil
+}
diff --git a/internal/console/plansponsor_test.go b/internal/console/plansponsor_test.go
new file mode 100644
index 000000000..64c9d97e8
--- /dev/null
+++ b/internal/console/plansponsor_test.go
@@ -0,0 +1,565 @@
+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, settled at
+// the console's start before it serves (SettleLaunchSponsorship).
+
+// sponsorCatalog is the example catalog with sponsor_accounts_before set
+// to cutoff, in whole seconds.
+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)
+ }
+ return c
+}
+
+// sponsorCutoffAt is the cutoff most tests use: an hour before planNow.
+// planAccount's accounts (created 2023) and the fixture's ops account
+// (created when the test starts, 2026) are before it.
+var sponsorCutoffAt = planNow.Add(-time.Hour)
+
+// 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 markDeleted(t *testing.T, fx *consoleFixture, acct *Account) {
+ t.Helper()
+ if _, err := fx.st.db.Exec(`UPDATE accounts SET deleted_at = ? WHERE id = ?`, planNow.Unix(), acct.ID); err != nil {
+ t.Fatal(err)
+ }
+}
+
+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)
+ }
+ }
+}
+
+// TestSettleLaunchSponsorship: the start sponsors every account created
+// before the cutoff with no plan row, and nothing else; from the first
+// read on, such an account's limits are the sponsored ones, never the
+// default plan's; the first limits pass publishes them; a second start
+// changes nothing.
+func TestSettleLaunchSponsorship(t *testing.T) {
+ fx := newConsoleFixture(t)
+ cat := sponsorCatalog(t, sponsorCutoffAt)
+ ctx := context.Background()
+ old := planAccount(t, fx, 501)
+ assigned := planAccount(t, fx, 502)
+ if _, err := fx.st.SetAccountPlan(assigned.ID, "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)
+ markDeleted(t, fx, gone)
+ fresh := newPlanAccount(t, fx, 504, sponsorCutoffAt) // at the cutoff: not before it
+ 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))
+ }
+
+ n, err := SettleLaunchSponsorship(fx.st, cat, planNow)
+ if err != nil || n != 1 {
+ t.Fatalf("settle = %d, %v; want 1 account", n, err)
+ }
+ 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.Revision != 1 || row.Sponsored == nil || *row.Sponsored != unlimited {
+ t.Fatalf("old account row = %+v", row)
+ }
+ 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)
+ }
+ for name, a := range map[string]*Account{"created at the cutoff": fresh, "deleted": gone, "ops": ops} {
+ if got, _ := fx.st.AccountPlan(a.ID); got != nil {
+ t.Fatalf("%s got a row: %+v", name, got)
+ }
+ }
+
+ // The server the start then builds sees the sponsorship on its first
+ // read: the old account never meets the free plan's caps.
+ fx.srv.cfg.PlanCatalog = cat
+ 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)
+ }
+ for i := range 5 {
+ capsApp(t, fx, old, fmt.Sprintf("app%d", i))
+ }
+ if err := fx.srv.checkRunningThings(ctx, old, 1); err != nil {
+ t.Fatalf("running-things check past the free plan's 3: %v", err)
+ }
+ fx.srv.planLimitsPass(ctx, planNow)
+ rec, _ := readLimits(t, fx, old.Sqid)
+ if rec == nil || rec.Source != PlanSourceSponsored || rec.Revision != row.Revision ||
+ rec.Limits.RunningThings != unlimited.RunningThings || rec.Limits.IdleSeconds != unlimited.IdleSeconds {
+ t.Fatalf("old account's record = %+v", rec)
+ }
+ if got, _ := fx.st.AccountPlan(fresh.ID); got == nil || got.Source != PlanSourceDefault {
+ t.Fatalf("the account created at the cutoff after the pass = %+v, want the default plan", got)
+ }
+
+ // A second start sponsors nothing and rewrites nothing.
+ if n, err := SettleLaunchSponsorship(fx.st, cat, planNow.Add(time.Hour)); err != nil || n != 0 {
+ t.Fatalf("second settle = %d, %v", n, err)
+ }
+ if again, _ := fx.st.AccountPlan(old.ID); again == nil || again.Revision != row.Revision {
+ t.Fatalf("the second start rewrote the sponsored row: %+v, was %+v", again, row)
+ }
+}
+
+func TestSettleLaunchSponsorshipNothingToDo(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ for name, cat := range map[string]*plans.Catalog{"no catalog": nil, "no cutoff": examplePlanCatalog(t)} {
+ if n, err := SettleLaunchSponsorship(fx.st, cat, planNow); err != nil || n != 0 {
+ t.Fatalf("%s: %d, %v", name, n, err)
+ }
+ }
+ if row, _ := fx.st.AccountPlan(acct.ID); row != nil {
+ t.Fatalf("row written: %+v", row)
+ }
+}
+
+// A cutoff after the start would let an account be created before it
+// while the console serves; it is refused and nothing is written.
+func TestSettleLaunchSponsorshipRefusesAFutureCutoff(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ _, err := SettleLaunchSponsorship(fx.st, sponsorCatalog(t, planNow.Add(time.Second)), planNow)
+ if err == nil || !strings.Contains(err.Error(), "after the console's start") {
+ t.Fatalf("future cutoff = %v, want a refusal", err)
+ }
+ if row, _ := fx.st.AccountPlan(acct.ID); row != nil {
+ t.Fatalf("row written: %+v", row)
+ }
+ // The cutoff at the start itself is fine.
+ if n, err := SettleLaunchSponsorship(fx.st, sponsorCatalog(t, planNow), planNow); err != nil || n != 1 {
+ t.Fatalf("cutoff at the start = %d, %v", n, 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)
+ }
+ }
+}
+
+// One transaction: a failed write leaves no account sponsored, and the
+// next start writes them all.
+func TestSettleLaunchSponsorshipIsOneTransaction(t *testing.T) {
+ fx := newConsoleFixture(t)
+ cat := sponsorCatalog(t, sponsorCutoffAt)
+ first := planAccount(t, fx, 501)
+ stuck := planAccount(t, fx, 502)
+ heal := failPlanWrite(t, fx, stuck.ID)
+ if _, err := SettleLaunchSponsorship(fx.st, cat, planNow); err == nil {
+ t.Fatal("settled with a write failing")
+ }
+ for _, a := range []*Account{first, stuck} {
+ if row, _ := fx.st.AccountPlan(a.ID); row != nil {
+ t.Fatalf("%s has a row after a failed settlement: %+v", a.Sqid, row)
+ }
+ }
+ heal()
+ if n, err := SettleLaunchSponsorship(fx.st, cat, planNow); err != nil || n != 2 {
+ t.Fatalf("retry = %d, %v; want 2", n, err)
+ }
+}
+
+// The settlement and the insert rule pass the host-claim store's SQL gate.
+func TestLaunchSponsorshipUnderTheGate(t *testing.T) {
+ s := openGatedStore(t)
+ if err := s.CreateAccount(501, domains.Sqid(501), "acct", "owner@example.com", time.Unix(1_700_000_000, 0)); err != nil {
+ t.Fatal(err)
+ }
+ if n, err := SettleLaunchSponsorship(s, sponsorCatalog(t, sponsorCutoffAt), planNow); err != nil || n != 1 {
+ t.Fatalf("under the gate = %d, %v", n, err)
+ }
+ // And an insert under the gate applies the rule.
+ if _, err := s.EnsureAccount(502, domains.Sqid(502), "late", time.Unix(1_700_000_000, 0)); err != nil {
+ t.Fatal(err)
+ }
+ if row, err := s.AccountPlan(502); err != nil || row == nil || row.Source != PlanSourceSponsored {
+ t.Fatalf("inserted under the gate = %+v, %v", row, err)
+ }
+}
+
+// sponsorFixtureAccount sponsors the fixture's own account (ops, governed)
+// as the start would.
+func sponsorFixtureAccount(t *testing.T, fx *consoleFixture) {
+ t.Helper()
+ governOps(fx) // the fixture account is ops
+ cat := sponsorCatalog(t, time.Now().Add(time.Hour))
+ if _, err := SettleLaunchSponsorship(fx.st, cat, time.Now().Add(2*time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ fx.srv.cfg.PlanCatalog = cat
+ if sp, err := fx.srv.planSponsored(&Account{ID: OpsAccountID}); err != nil || !sp {
+ t.Fatalf("fixture account sponsored = %v, %v", sp, err)
+ }
+}
+
+// Paul, 2026-10-31: a sponsored account is exempt from the daemon and
+// always-on refusals on shared boxes.
+func TestSponsoredAccountShipsADaemon(t *testing.T) {
+ fx, token := daemonFixture(t, "code-sponsor-daemon")
+ sponsorFixtureAccount(t, fx)
+ if status, out := shipDaemon(t, fx, token, "dmn00010"); status != http.StatusCreated {
+ t.Fatalf("daemon ship on a sponsored account = %d %v", status, out)
+ }
+ acct, _ := fx.st.AccountBySqid(fx.sqid)
+ for name, err := range map[string]error{
+ "version": fx.srv.checkDaemonVersion(context.Background(), acct, "relayapp", "dmn00010"),
+ "always on": fx.srv.checkAlwaysOnCreate(acct, "relayapp"),
+ } {
+ if err != nil {
+ t.Errorf("%s: %v", name, err)
+ }
+ }
+ if guard, err := fx.srv.rollbackDaemonGuard(context.Background(), acct, "relayapp", "edge"); err != nil || guard != nil {
+ t.Errorf("rollback guard = %v, %v; want none", guard != nil, err)
+ }
+}
+
+func TestSponsoredAccountSidecarsMayStayAwake(t *testing.T) {
+ fx, token := instanceFixture(t, "code-sponsor-alwayson")
+ enableSidecars(t, fx, "titogo", titoSidecarManifest())
+ sponsorFixtureAccount(t, fx)
+ status, _, out := rawReq(t, http.MethodPut, sidecarEnableURL(fx, "bab", "titogo"), token, `{"hibernate":false}`)
+ if status != http.StatusOK {
+ t.Fatalf("hibernate:false on a sponsored account = %d %s", status, out)
+ }
+ if h := sidecarHibernate(t, fx); h == nil || *h {
+ t.Fatalf("hibernate = %v, want false", h)
+ }
+}
+
+// An account on the default plan is still refused (the control).
+func TestDefaultPlanAccountStillRefusedADaemon(t *testing.T) {
+ fx, token := daemonFixture(t, "code-sponsor-daemon-control")
+ governOps(fx)
+ fx.srv.cfg.PlanCatalog = sponsorCatalog(t, sponsorCutoffAt)
+ if _, err := fx.st.EnsureDefaultPlans("free", planNow); err != nil {
+ t.Fatal(err)
+ }
+ if status, out := shipDaemon(t, fx, token, "dmn00011"); status != http.StatusConflict || out["code"] != "cap" {
+ t.Fatalf("daemon ship on the default plan = %d %v, want 409 cap", status, out)
+ }
+}
+
+// The billing page writes the sponsorship's figure as "Unlimited".
+func TestBillingShowsTheSponsorshipAsUnlimited(t *testing.T) {
+ sponsored := sponsorUnlimited()
+ l, err := sponsorCatalog(t, sponsorCutoffAt).Effective("free", nil, &sponsored, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got []string
+ for _, inc := range planIncludes(l, 0) {
+ got = append(got, inc.Text)
+ }
+ want := []string{"Unlimited apps and instances", "Unlimited disk per app", "Custom domains"}
+ if strings.Join(got, "|") != strings.Join(want, "|") {
+ t.Fatalf("includes = %q, want %q", got, want)
+ }
+ if u := useOfLimit(map[capID]int64{capRunningThings: 4}, capRunningThings, int64(l.RunningThings)); u == nil || u.Text != "You use 4" {
+ t.Fatalf("use = %+v", u)
+ }
+ if u := useOfLimit(map[capID]int64{capStorage: 1 << 30}, capStorage, l.StorageBytes); u == nil || u.Text != "You use 1 GB" {
+ t.Fatalf("storage use = %+v", u)
+ }
+ // An ordinary limit is unchanged.
+ if u := useOfLimit(map[capID]int64{capRunningThings: 2}, capRunningThings, 3); u == nil || u.Text != "2 of 3 used" {
+ t.Fatalf("ordinary use = %+v", u)
+ }
+}
+
+// assertSponsorInvariant checks THE INVARIANT (plansponsor.go) on st with
+// the rule for cutoff recorded: no live, non-exempt account created before
+// the cutoff is without a plan row.
+func assertSponsorInvariant(t *testing.T, st *Store, cutoff time.Time) {
+ t.Helper()
+ rows, err := st.db.Query(`SELECT sqid FROM accounts WHERE deleted_at = 0 AND id != ? AND created_at < ?
+ AND id NOT IN (SELECT account_id FROM account_plans)`, st.planExemptID, cutoff.Unix())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var sqid string
+ if err := rows.Scan(&sqid); err != nil {
+ t.Fatal(err)
+ }
+ t.Errorf("account %s was created before the cutoff and is visible without a plan row", sqid)
+ }
+}
+
+func assertSponsoredRow(t *testing.T, st *Store, id int64) {
+ t.Helper()
+ row, err := st.AccountPlan(id)
+ if err != nil || row == nil || row.Source != PlanSourceSponsored || row.Reason != planSponsorReason ||
+ row.Sponsored == nil || *row.Sponsored != sponsorUnlimited() {
+ t.Fatalf("account %d row = %+v, %v; want the launch sponsorship", id, row, err)
+ }
+}
+
+// Astra R2 finding 1: a CLI mint captures a creation time before the
+// cutoff but publishes its manifest after the start's settlement. Whoever
+// materializes it (the server the start then builds, or `console member`'s
+// MaterializeAccounts) inserts it with its sponsored row in the same
+// commit; the limits pass then gives it no default row; and a later start
+// keeps it.
+func TestLateManifestIsSponsoredWhereverItIsMaterialized(t *testing.T) {
+ fx := newConsoleFixture(t)
+ cat := sponsorCatalog(t, sponsorCutoffAt)
+ ctx := context.Background()
+ if _, err := SettleLaunchSponsorship(fx.st, cat, planNow); err != nil {
+ t.Fatal(err)
+ }
+ assertSponsorInvariant(t, fx.st, sponsorCutoffAt)
+ early := sponsorCutoffAt.Add(-time.Minute)
+
+ // Published after the settlement, materialized by a server built on
+ // the same store, as serve() builds one.
+ if err := WriteAccountManifest(ctx, fx.rel, 601, domains.Sqid(601), "late one", early); err != nil {
+ t.Fatal(err)
+ }
+ cfg := fx.srv.cfg
+ cfg.PlanCatalog = cat
+ srv, err := NewServer(cfg, fx.st)
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertSponsoredRow(t, fx.st, 601)
+ assertSponsorInvariant(t, fx.st, sponsorCutoffAt)
+
+ // Published later still, materialized as `console member` does.
+ if err := WriteAccountManifest(ctx, fx.rel, 602, domains.Sqid(602), "late two", early); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := MaterializeAccounts(ctx, fx.rel, fx.st); err != nil {
+ t.Fatal(err)
+ }
+ assertSponsoredRow(t, fx.st, 602)
+ assertSponsorInvariant(t, fx.st, sponsorCutoffAt)
+
+ // The limits pass gives neither a default row, and publishes both.
+ srv.planLimitsPass(ctx, planNow)
+ for _, id := range []int64{601, 602} {
+ assertSponsoredRow(t, fx.st, id)
+ if rec, _ := readLimits(t, fx, domains.Sqid(id)); rec == nil || rec.Source != PlanSourceSponsored {
+ t.Fatalf("account %d record = %+v", id, rec)
+ }
+ }
+ // A restart: nothing changes, and the rule is still recorded.
+ if n, err := SettleLaunchSponsorship(fx.st, cat, planNow.Add(time.Hour)); err != nil || n != 0 {
+ t.Fatalf("restart settle = %d, %v", n, err)
+ }
+ if r, err := launchRuleOn(fx.st.db); err != nil || r == nil || r.cutoff != sponsorCutoffAt.Unix() {
+ t.Fatalf("rule after restart = %+v, %v", r, err)
+ }
+ // An account minted after the cutoff gets nothing from the rule.
+ if err := WriteAccountManifest(ctx, fx.rel, 603, domains.Sqid(603), "new", planNow); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := MaterializeAccounts(ctx, fx.rel, fx.st); err != nil {
+ t.Fatal(err)
+ }
+ if row, _ := fx.st.AccountPlan(603); row != nil {
+ t.Fatalf("an account after the cutoff got %+v at insert", row)
+ }
+}
+
+// A start with plans off clears the rule, so an account materialized
+// while plans are off gets no row; the next start with the cutoff
+// sponsors it before it serves.
+func TestRestartWithPlansOffThenOn(t *testing.T) {
+ fx := newConsoleFixture(t)
+ cat := sponsorCatalog(t, sponsorCutoffAt)
+ ctx := context.Background()
+ if _, err := SettleLaunchSponsorship(fx.st, cat, planNow); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := SettleLaunchSponsorship(fx.st, nil, planNow); err != nil { // plans off
+ t.Fatal(err)
+ }
+ if r, err := launchRuleOn(fx.st.db); err != nil || r != nil {
+ t.Fatalf("rule with plans off = %+v, %v; want none", r, err)
+ }
+ if err := WriteAccountManifest(ctx, fx.rel, 601, domains.Sqid(601), "while off", sponsorCutoffAt.Add(-time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := MaterializeAccounts(ctx, fx.rel, fx.st); err != nil {
+ t.Fatal(err)
+ }
+ if row, _ := fx.st.AccountPlan(601); row != nil {
+ t.Fatalf("plans off, but the insert wrote %+v", row)
+ }
+ if n, err := SettleLaunchSponsorship(fx.st, cat, planNow); err != nil || n != 1 {
+ t.Fatalf("plans back on = %d, %v", n, err)
+ }
+ assertSponsoredRow(t, fx.st, 601)
+ assertSponsorInvariant(t, fx.st, sponsorCutoffAt)
+ // A refused start clears the rule too.
+ if _, err := SettleLaunchSponsorship(fx.st, sponsorCatalog(t, planNow.Add(time.Hour)), planNow); err == nil {
+ t.Fatal("future cutoff settled")
+ }
+ if r, _ := launchRuleOn(fx.st.db); r != nil {
+ t.Fatalf("rule after a refused start = %+v", r)
+ }
+}
+
+// The console's own mint applies the rule in CreateAccount's commit, and
+// an insert whose sponsored row cannot be written leaves no account
+// behind: the two are one commit.
+func TestAccountInsertAndItsSponsorshipAreOneCommit(t *testing.T) {
+ fx := newConsoleFixture(t)
+ if _, err := SettleLaunchSponsorship(fx.st, sponsorCatalog(t, sponsorCutoffAt), planNow); err != nil {
+ t.Fatal(err)
+ }
+ minted := newPlanAccount(t, fx, 601, sponsorCutoffAt.Add(-time.Second))
+ assertSponsoredRow(t, fx.st, minted.ID)
+ if after := newPlanAccount(t, fx, 602, sponsorCutoffAt); after != nil {
+ if row, _ := fx.st.AccountPlan(after.ID); row != nil {
+ t.Fatalf("an account at the cutoff got %+v at insert", row)
+ }
+ }
+
+ heal := failPlanWrite(t, fx, 603)
+ if _, err := fx.st.EnsureAccount(603, domains.Sqid(603), "x", sponsorCutoffAt.Add(-time.Hour)); err == nil {
+ t.Fatal("materialized with its sponsored row failing")
+ }
+ if err := fx.st.CreateAccount(603, domains.Sqid(603), "x", "owner@example.com", sponsorCutoffAt.Add(-time.Hour)); err == nil {
+ t.Fatal("minted with its sponsored row failing")
+ }
+ if a, _, _ := fx.st.AccountAnyBySqid(domains.Sqid(603)); a != nil {
+ t.Fatalf("the account is visible without its row: %+v", a)
+ }
+ heal()
+ if _, err := fx.st.EnsureAccount(603, domains.Sqid(603), "x", sponsorCutoffAt.Add(-time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ assertSponsoredRow(t, fx.st, 603)
+ assertSponsorInvariant(t, fx.st, sponsorCutoffAt)
+}
diff --git a/internal/console/store.go b/internal/console/store.go
index d72e3ebbd..5aa9f0f52 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -423,6 +423,18 @@ func (s *Store) migrate() error {
published_catalog TEXT NOT NULL DEFAULT '',
updated_by TEXT NOT NULL,
updated_at INTEGER NOT NULL
+);`,
+ // The launch sponsorship rule (plansponsor.go): one row while the
+ // console runs plans with sponsor_accounts_before, none otherwise.
+ // Every account insert reads it in its own transaction.
+ `CREATE TABLE IF NOT EXISTS plan_launch_sponsorship (
+ id INTEGER PRIMARY KEY CHECK (id = 1),
+ cutoff INTEGER NOT NULL,
+ plan TEXT NOT NULL,
+ sponsored TEXT NOT NULL,
+ reason TEXT NOT NULL,
+ updated_by TEXT NOT NULL,
+ updated_at INTEGER NOT NULL
);`,
// Pending lifetimes (lifetimes_store.go): the console's intents on a
// claims-off host's incarnation slot, written before the bucket step
@@ -901,9 +913,19 @@ func (s *Store) BackfillOpsMemberships(now time.Time) ([]GrantHolder, error) {
return nil, err
}
defer tx.Rollback()
- if _, err := tx.Exec(`INSERT OR IGNORE INTO accounts (id, sqid, name, created_at)
-VALUES (?, ?, 'ops', ?)`, OpsAccountID, opsSqid, now.Unix()); err != nil {
+ res, err := tx.Exec(`INSERT OR IGNORE INTO accounts (id, sqid, name, created_at)
+VALUES (?, ?, 'ops', ?)`, OpsAccountID, opsSqid, now.Unix())
+ if err != nil {
+ return nil, err
+ }
+ if added, err := res.RowsAffected(); err != nil {
return nil, err
+ } else if added > 0 {
+ // The launch sponsorship's rule, as at every account insert
+ // (plansponsor.go); ops is exempt, so it writes nothing.
+ if err := s.sponsorOnInsertTx(tx, OpsAccountID, now); err != nil {
+ return nil, err
+ }
}
// OR IGNORE, never OR REPLACE or UPDATE: an address that is already a
// member keeps whatever role it has. This is the only membership write in
@@ -1110,6 +1132,10 @@ func (s *Store) CreateAccount(id int64, sqid, name, ownerAddress string, now tim
id, ownerAddress, RoleOwner, now.Unix()); err != nil {
return err
}
+ // The launch sponsorship's rule, in the same commit (plansponsor.go).
+ if err := s.sponsorOnInsertTx(tx, id, now); err != nil {
+ return err
+ }
return tx.Commit()
}
@@ -1132,14 +1158,30 @@ func (s *Store) CreateAccount(id int64, sqid, name, ownerAddress string, now tim
//
// INSERT OR IGNORE, never REPLACE: an account the console already knows must
// keep its id, its name and its members.
+//
+// A new row gets the launch sponsorship's rule in the same commit
+// (plansponsor.go): an account materialized from a manifest, whenever and
+// by whichever process, is never visible without the sponsored row it is
+// owed.
func (s *Store) EnsureAccount(id int64, sqid, name string, created time.Time) (added bool, err error) {
- res, err := s.db.Exec(`INSERT OR IGNORE INTO accounts (id, sqid, name, created_at) VALUES (?, ?, ?, ?)`,
+ tx, err := s.db.Begin()
+ if err != nil {
+ return false, err
+ }
+ defer tx.Rollback()
+ res, err := tx.Exec(`INSERT OR IGNORE INTO accounts (id, sqid, name, created_at) VALUES (?, ?, ?, ?)`,
id, sqid, name, created.Unix())
if err != nil {
return false, err
}
n, err := res.RowsAffected()
- return n > 0, err
+ if err != nil || n == 0 {
+ return false, err
+ }
+ if err := s.sponsorOnInsertTx(tx, id, created); err != nil {
+ return false, err
+ }
+ return true, tx.Commit()
}
// AdoptManifestOwner turns an account manifest's `owner` field into the owner
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go
index b0f536d85..afd308024 100644
--- a/internal/console/store_gate.go
+++ b/internal/console/store_gate.go
@@ -259,6 +259,9 @@ var claimSQLTables = map[string]claimSQLTable{
"alert_tokens": {NonApp: "alert confirm, unsubscribe and snooze links, keyed by token hash; names no app"},
"alert_snoozes": {NonApp: "alert snoozes per scope, rule and subject; no app state"},
"alert_meta": {NonApp: "the alert engine's one-shot markers"},
+
+ // The launch sponsorship rule (plansponsor.go).
+ "plan_launch_sponsorship": {NonApp: "the launch sponsorship rule the console started with (cutoff, plan, sponsored limits); one row, names no app"},
}
// claimSQLReservedName is the TEMP permit table. A main-schema table by that
diff --git a/internal/plans/catalog.go b/internal/plans/catalog.go
index e3c3842e2..f863d9f85 100644
--- a/internal/plans/catalog.go
+++ b/internal/plans/catalog.go
@@ -16,7 +16,9 @@ import (
"fmt"
"math"
"os"
+ "regexp"
"slices"
+ "time"
"github.com/carlosframework/platform/internal/ratelimit"
)
@@ -90,8 +92,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 in whole
+ // seconds: every account created before it that has no plan of its own
+ // is sponsored with no limits when plans go on (Paul, 2026-10-31). The
+ // console does it at start, before it serves
+ // (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 +150,16 @@ 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 }
+// sponsorCutoffShape is the only shape sponsor_accounts_before may take:
+// RFC 3339 in whole seconds, upper-case T, Z or a +hh:mm/-hh:mm offset.
+var sponsorCutoffShape = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(Z|[+-]\d{2}:\d{2})$`)
+
+var errSponsorCutoffShape = errors.New("not whole seconds")
+
+// 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 +173,22 @@ func (c *Catalog) validate() error {
if c.FreeAccountsPerPerson < 0 {
return errors.New("free_accounts_per_person is negative")
}
+ if c.SponsorAccountsBefore != "" {
+ // Whole seconds only, checked on the raw string against one strict
+ // shape before parsing: accounts record their creation to the
+ // second, so any fraction would be compared truncated, and Go's
+ // parser takes '.' and ',' fractions and drops digits past the
+ // ninth. Anything the pattern lets through is a whole second.
+ var t time.Time
+ err := errSponsorCutoffShape
+ if sponsorCutoffShape.MatchString(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 in whole seconds, 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..eb1127ecf 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,63 @@ 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")
+ }
+ offset, err := ParseCatalog([]byte(strings.Replace(base, `"default_plan": "free",`, `"default_plan": "free", "sponsor_accounts_before": "2026-11-01T10:00:00+01:00",`, 1)))
+ if err != nil || !offset.SponsorCutoff().Equal(c.SponsorCutoff()) {
+ t.Fatalf("an offset cutoff = %v, %v", offset, err)
+ }
+ 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`,
+ // Accounts store their creation to the second; a fraction would
+ // compare against a truncated cutoff (Astra R1 finding 4).
+ "fractional second": `"2026-11-01T09:00:00.5Z"`,
+ // Go's parser drops digits past the ninth, so this parses with zero
+ // nanoseconds; the syntax itself is refused (Astra R2 finding 2).
+ "a fraction past nine digits": `"2026-11-01T09:00:00.0000000001Z"`,
+ "a zero fraction": `"2026-11-01T09:00:00.000Z"`,
+ // Go's RFC 3339 parser takes a comma fraction too (Astra R3).
+ "a comma fraction": `"2026-11-01T09:00:00,5Z"`,
+ "a comma fraction past nine": `"2026-11-01T09:00:00,0000000001Z"`,
+ "a lower-case t": `"2026-11-01t09:00:00Z"`,
+ "an offset without a colon": `"2026-11-01T09:00:00+0100"`,
+ } {
+ 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 1b1d17037..8b34eea8b 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -49,3 +49,4 @@ plan14-root-reads-devbox-mode.tsv 43d1824141f0ce7024cc3740ab5feac3f3539322f8afb8
plan14-root-reads-first-deploy-493.tsv 6b9aa3f2b21250d40b910ad1d29362687ec57ba5e895157670b785c0c3978f52
plan14-root-reads-fleet-alerts-1.tsv 8653544a508c745b01d4bbe2a89a3fb11f6da6b9ba683d90261dd7ef033e5d83
plan14-root-reads-managed-fleets-1b.tsv 7570ca617863882780c1c5a7d04430b578a297ee4d72ca25acc1cdc5288ca283
+plan14-root-reads-sponsor-existing-accounts.tsv 7570ca617863882780c1c5a7d04430b578a297ee4d72ca25acc1cdc5288ca283
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..8aacc34e9
--- /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 15dfe16c49f24d0dbfaf835aea07eb98e198a89b4dc103868967ad2ddf756800