carlos / platform Public

plans: settle the launch sponsorship at console start, before it serves (Astra R1)

Astra round 1 found that "owed but not yet sponsored" existed while the
console served: an enforcement read could race the settlement (P1), an
owed account could open a paid checkout (P1), and the latch could miss a
late mint (P2). This removes that state instead of patching each read.

- console.SettleLaunchSponsorship runs in serve() after planCatalog and
  before billing, console.NewServer, every worker, the listener and
  NotifyReady (pinned by TestServeSettlesTheSponsorshipBeforeItServes). It
  refuses a cutoff after the start, materializes the bucket's account
  manifests first and refuses if any could not be read, then writes every
  owed row in one transaction (Store.SponsorExistingAccounts: insert-only,
  each row priced at its member count first; all or nothing).
- On any refusal, sponsorAtStart runs the start with no catalog: plans
  off as if none were configured, billing off too (billingConfigFor), and
  a loud log line. The next start retries. A past cutoff means anything
  minted while serving is post-cutoff.
- Removed the derived gate: sponsorOwed in EffectiveLimits and
  checkMemberCap, the limits-pass settlement and its 10-minute latch, the
  EnsureDefaultPlans exclusion, applyAccountPlanUnassigned. Those files
  are back to main.
- sponsor_accounts_before must be whole seconds (R1 P2 #4).
- Paul, 2026-10-31: a sponsored account is exempt from the daemon and
  always-on refusals on shared boxes (planSponsored in checkDaemon,
  checkDaemonVersion, rollbackDaemonGuard, checkAlwaysOnCreate,
  checkAlwaysOn). The mail-pause email ceiling and the free-account count
  are unchanged.
- Billing page: a count or size at the sponsorship's figure reads
  "Unlimited" (billingCopy limit.unlimited, DRAFT); usage against it reads
  "You use N"; an idle window at it is left out; a sponsored row lists no
  member cap.

Census: internal/plans envelope re-pinned again (catalog.go); overlay
re-proposed, census clean.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 86c616ec953d5ee79f9cd969dd87d2bb77d254ac parent 61d530b
21 files changed, +646 −442
  • cmd/console/main.go +10 −4
  • cmd/console/plansponsor.go +46 −0
  • cmd/console/plansponsor_test.go +140 −0
  • docs/site/plans.md +1 −1
  • internal/console/accountplans.go +72 −11
  • internal/console/accountplans_test.go +6 −6
  • internal/console/billingpage.go +16 −3
  • internal/console/billingpage_copy.go +1 −0
  • internal/console/billingusage.go +4 −0
  • internal/console/materialize.go +16 −6
  • internal/console/plancaps.go +18 −1
  • internal/console/planlapse.go +16 −42
  • internal/console/planlimits.go +6 −20
  • internal/console/planlimits_test.go +1 −1
  • internal/console/planmembers.go +2 −8
  • internal/console/plansponsor.go +69 −135
  • internal/console/plansponsor_test.go +208 −191
  • internal/console/server.go +0 −4
  • internal/plans/catalog.go +10 −8
  • internal/plans/catalog_test.go +3 −0
  • internal/provision/testdata/plan14-root-reads-sponsor-existing-accounts.tsv +1 −1

CI cancelled — superseded by a newer push — run details

diff --git a/cmd/console/main.go b/cmd/console/main.go
index 6a3ddddcd..c413182a1 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -365,14 +365,23 @@ func serve() {
rec := new(perf.Recorder)
storeProvisioner, storeDeployment := storeBackend(rec)
storeScanner, seedAntivirus := storeScannerFor(storeDeployment)
+ // One release.Store, named, because the senders sweep below and the
+ // launch sponsorship need the same one the server got.
+ rel := openStore(rec)
catalog, err := planCatalog()
if err != nil {
// 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, every worker and the listener, so no account
+ // is ever owed it while the console serves. One that does not settle
+ // runs this start with plans and billing off, never with plans on and
+ // the sponsorship unsettled.
+ catalog, plansOff := sponsorAtStart(context.Background(), rel, st, catalog, time.Now())
// 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)
}
@@ -406,9 +415,6 @@ func serve() {
return mail.NewAWSProvisioner(ctx, region, mailBoundary)
}
mailProvisioner, dnsWriter := mailBackends(mailDep, newMailProvisioner, dnsrec.NewRoute53Writer)
- // One release.Store, named, because the senders sweep below needs the
- // same one the server got.
- rel := openStore(rec)
consoleMail, ensureConsoleMail := consoleMailer(mailDep, rel, mailProvisioner, dnsWriter, mail.NewSESEmailSender, hostClaim)
dbBucket, dbRegion, dbPrefix, placement := dbDoorWiring()
var dbVersions lease.VersionedStore
diff --git a/cmd/console/plansponsor.go b/cmd/console/plansponsor.go
new file mode 100644
index 000000000..33e6401a7
--- /dev/null
+++ b/cmd/console/plansponsor.go
@@ -0,0 +1,46 @@
+package main
+
+import (
+ "context"
+ "log"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/console"
+ "github.com/carlosframework/platform/internal/plans"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// sponsorAtStart settles the catalog's launch sponsorship
+// (console.SettleLaunchSponsorship) and returns the catalog to serve with.
+// When it 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.
+func sponsorAtStart(ctx context.Context, rel release.Store, st *console.Store, cat *plans.Catalog, now time.Time) (_ *plans.Catalog, plansOff bool) {
+ n, err := console.SettleLaunchSponsorship(ctx, rel, st, cat, now)
+ 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
+ }
+ 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
+}
+
+// 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..59c0dbddf
--- /dev/null
+++ b/cmd/console/plansponsor_test.go
@@ -0,0 +1,140 @@
+package main
+
+import (
+ "context"
+ "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"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+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() })
+ rel := release.NewDirStore(t.TempDir())
+ 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 := sponsorAtStart(context.Background(), rel, st, sponsorTestCatalog(t, now.Add(time.Hour)), now)
+ if cat != nil || !off {
+ 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 = sponsorAtStart(context.Background(), rel, st, want, now)
+ if cat != want || off {
+ t.Fatalf("past cutoff: catalog kept %v, plans off %v", cat == want, off)
+ }
+}
+
+// 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 count["billingConfig"] != 0 {
+ t.Error("serve() calls billingConfig directly; billing must go through billingConfigFor so a start with plans off keeps billing off")
+ }
+}
diff --git a/docs/site/plans.md b/docs/site/plans.md
index 62e546dc1..53dd875bd 100644
--- a/docs/site/plans.md
+++ b/docs/site/plans.md
@@ -58,7 +58,7 @@ 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.
+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
diff --git a/internal/console/accountplans.go b/internal/console/accountplans.go
index aa4896c82..12edf2265 100644
--- a/internal/console/accountplans.go
+++ b/internal/console/accountplans.go
@@ -4,7 +4,7 @@ import (
"database/sql"
"encoding/json"
"errors"
- "math"
+ "fmt"
"slices"
"strings"
"time"
@@ -242,19 +242,13 @@ 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, 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()
- }
+// (planExempt) gets none.
+func (s *Store) EnsureDefaultPlans(defaultPlan string, now time.Time) (int, error) {
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 created_at >= ? AND id NOT IN (SELECT account_id FROM account_plans)`,
- defaultPlan, PlanSourceDefault, planDefaultActor, now.Unix(), s.planExemptID, from)
+ WHERE deleted_at = 0 AND id != ? AND id NOT IN (SELECT account_id FROM account_plans)`,
+ defaultPlan, PlanSourceDefault, planDefaultActor, now.Unix(), s.planExemptID)
if err != nil {
return 0, err
}
@@ -262,6 +256,73 @@ func (s *Store) EnsureDefaultPlans(defaultPlan string, sponsorCutoff time.Time,
return int(n), err
}
+// SponsorExistingAccounts is the launch sponsorship's write
+// (plansponsor.go), in one transaction: every live account created before
+// cutoff with no plan row, the exempt account aside, gets cat's default
+// plan, source sponsored, with sponsored, reason and by. Insert-only: a row
+// already there is never touched. Each new 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.
+// 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) SponsorExistingAccounts(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
+ }
+ tx, err := s.db.Begin()
+ if err != nil {
+ return 0, err
+ }
+ defer tx.Rollback()
+ rows, err := tx.Query(`SELECT id FROM accounts
+ WHERE deleted_at = 0 AND id != ? AND created_at < ? AND id NOT IN (SELECT account_id FROM account_plans)
+ ORDER BY id`, s.planExemptID, cutoff.Unix())
+ if err != nil {
+ return 0, err
+ }
+ var ids []int64
+ for rows.Next() {
+ var id int64
+ if err := rows.Scan(&id); err != nil {
+ rows.Close()
+ return 0, err
+ }
+ ids = append(ids, id)
+ }
+ rows.Close()
+ if err := rows.Err(); err != nil {
+ return 0, err
+ }
+ for _, id := range ids {
+ members, err := teamMembers(cat, cat.DefaultPlan, 0, func() (int, error) { return memberCountOn(tx, 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", id, err)
+ }
+ if _, 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`,
+ id, cat.DefaultPlan, PlanSourceSponsored, string(sj), reason, by, now.Unix()); err != nil {
+ return 0, fmt.Errorf("account %d: %w", id, err)
+ }
+ }
+ if err := tx.Commit(); err != nil {
+ return 0, err
+ }
+ return len(ids), 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/accountplans_test.go b/internal/console/accountplans_test.go
index 45b7bc49b..a3e5bc5d2 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", time.Time{}, planNow)
+ n, err := st.EnsureDefaultPlans("free", 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", time.Time{}, planNow); err != nil || n != 0 {
+ if n, err := st.EnsureDefaultPlans("free", 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", time.Time{}, planNow); err != nil || n != 1 {
+ if n, err := st.EnsureDefaultPlans("free", 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", time.Time{}, planNow); err != nil {
+ if _, err := st.EnsureDefaultPlans("free", 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", time.Time{}, planNow); err != nil {
+ if _, err := st.EnsureDefaultPlans("free", 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", time.Time{}, planNow); err != nil {
+ if _, err := st2.EnsureDefaultPlans("free", 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/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/materialize.go b/internal/console/materialize.go
index 1e9dca1fc..235d3dacd 100644
--- a/internal/console/materialize.go
+++ b/internal/console/materialize.go
@@ -39,14 +39,23 @@ import (
// unreachable bucket must never be what stops an operator removing a
// membership, which is the emergency this whole verb family exists for.
func MaterializeAccounts(ctx context.Context, s release.Store, st *Store) (int, error) {
+ n, _, err := materializeAccounts(ctx, s, st)
+ return n, err
+}
+
+// materializeAccounts is MaterializeAccounts, also counting the manifests
+// it could not read. Those are the ones a later pass may still bring in;
+// a malformed or corrupt manifest never will, and is not counted. The
+// launch sponsorship (plansponsor.go) needs every account in before it
+// settles, so it refuses on any.
+func materializeAccounts(ctx context.Context, s release.Store, st *Store) (n, unread int, err error) {
if s == nil {
- return 0, nil
+ return 0, 0, nil
}
keys, err := s.List(ctx, "accounts/")
if err != nil {
- return 0, err
+ return 0, 0, err
}
- n := 0
for _, key := range keys {
sqid, ok := domains.AccountManifestSqid(key)
if !ok {
@@ -59,7 +68,7 @@ func MaterializeAccounts(ctx context.Context, s release.Store, st *Store) (int,
// forgetting it is a takeover (see the switch below).
a, deleted, err := st.AccountAnyBySqid(sqid)
if err != nil {
- return n, err
+ return n, unread, err
}
// Read UNCONDITIONALLY now, including for accounts we already know.
// This is the accepted cost of reaping: tombstone state lives in the
@@ -69,6 +78,7 @@ func MaterializeAccounts(ctx context.Context, s release.Store, st *Store) (int,
body, _, err := s.Get(ctx, key)
if err != nil {
log.Printf("console: skipping %s: read failed: %v", key, err)
+ unread++
continue
}
var m accountManifest
@@ -149,7 +159,7 @@ func MaterializeAccounts(ctx context.Context, s release.Store, st *Store) (int,
}
added, err := st.EnsureAccount(m.ID, m.Sqid, m.Name, created)
if err != nil {
- return n, err
+ return n, unread, err
}
if !added {
// The sqid was free but the id was not: some other row already
@@ -185,7 +195,7 @@ func MaterializeAccounts(ctx context.Context, s release.Store, st *Store) (int,
// ONLY here — on the pass that created the row, never on a later one.
materializeOwner(st, key, m, created)
}
- return n, nil
+ return n, unread, nil
}
// materializeOwner turns the manifest's `owner` into the account's first owner
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/planlapse.go b/internal/console/planlapse.go
index 8cd82d650..4523e3bc0 100644
--- a/internal/console/planlapse.go
+++ b/internal/console/planlapse.go
@@ -127,51 +127,25 @@ 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) {
- 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
+ // 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
}
- 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
+ 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
+ }
}
}
- }
- return nil
+ return true, 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 566a249d6..3e5e61b44 100644
--- a/internal/console/planlimits.go
+++ b/internal/console/planlimits.go
@@ -36,22 +36,15 @@ func (s *Server) StartPlanLimitsPass(ctx context.Context) {
}
}
-// 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.
+// 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.
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.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 {
+ if _, err := s.store.EnsureDefaultPlans(cat.DefaultPlan, now); err != nil {
log.Printf("console: plan limits: default plans: %v", err)
jobFailed(ctx, fmt.Errorf("plan limits: default plans: %w", err))
return
@@ -137,9 +130,8 @@ 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, 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
+// 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
// planMembers' count.
func (s *Server) EffectiveLimits(acct *Account) (*plans.Limits, error) {
cat := s.cfg.PlanCatalog
@@ -150,12 +142,6 @@ 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 e309bc6ae..a481f203c 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", time.Time{}, planNow); err != nil {
+ if _, err := fx.st.EnsureDefaultPlans("free", 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 48f4f2fdf..02310e4ce 100644
--- a/internal/console/planmembers.go
+++ b/internal/console/planmembers.go
@@ -165,9 +165,8 @@ 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, 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.
+// plans, sponsored rows, 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) {
@@ -178,11 +177,6 @@ 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
index fb1d0653e..937f960ac 100644
--- a/internal/console/plansponsor.go
+++ b/internal/console/plansponsor.go
@@ -2,42 +2,50 @@ package console
import (
"context"
- "errors"
"fmt"
- "log"
"math"
"time"
"github.com/carlosframework/platform/internal/plans"
"github.com/carlosframework/platform/internal/ratelimit"
+ "github.com/carlosframework/platform/internal/release"
)
// 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:
+// pay. A catalog opts in with sponsor_accounts_before.
//
-// - 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 sponsorship is settled once per console start, by
+// SettleLaunchSponsorship, before the console has a Server: before the
+// listener, any door, worker or plan pass (cmd/console serve; Astra R1).
+// So while the console serves there is no account that is owed the
+// sponsorship and has not got it:
//
-// The ops account (planExempt) is never owed: it has no plan at all.
+// - every account the console knows at start is in: the settlement first
+// materializes the bucket's account manifests and refuses if it could
+// not read one;
+// - the cutoff is not after the start (a later one is refused), so an
+// account the console mints while serving is after the cutoff and gets
+// the default plan like any new account;
+// - the rows are written in one transaction: all of them, or none;
+// - any refusal leaves the console with no catalog, plans off as if none
+// were configured, and the next start tries again.
+//
+// The serve lock (cmd/console servelock_*.go) keeps one serving console per
+// database. One path stays open: `console member`, an offline verb that
+// takes no lock, materializes manifests it finds, so a manifest no start
+// could read and that it reads while the console serves arrives with the
+// default 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"
-// 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
+// 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
@@ -60,22 +68,21 @@ const sponsorSettleMargin = 10 * time.Minute
// 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.
+// 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 {
- const most = math.MaxInt64 / 4
return plans.Limits{
- RunningThings: most,
- SidecarsPerApp: most,
- IdleSeconds: int(math.MaxInt64 / int64(time.Second)),
+ RunningThings: sponsorMost,
+ SidecarsPerApp: sponsorMost,
+ IdleSeconds: sponsorUnlimitedIdle,
MemoryTier: plans.MemoryDefault,
- AwakeHoursMonth: most,
- DiskBytes: most,
- StorageBytes: most,
+ AwakeHoursMonth: sponsorMost,
+ DiskBytes: sponsorMost,
+ StorageBytes: sponsorMost,
StorageSelfServe: true,
- EmailPerDay: most,
- BandwidthBytesMonth: most,
+ EmailPerDay: sponsorMost,
+ BandwidthBytesMonth: sponsorMost,
CustomDomains: true,
Fleets: true,
MinScheduleSeconds: 1,
@@ -86,120 +93,47 @@ func sponsorUnlimited() plans.Limits {
}
}
-// 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
+// SettleLaunchSponsorship settles cat's launch sponsorship on st at the
+// console's start, and must finish before the console serves. With no
+// catalog, or a catalog without sponsor_accounts_before, it does nothing.
+// Otherwise it refuses a cutoff after now, then materializes the account
+// manifests in rel (nil: none) and refuses if any could not be read, then
+// writes every owed row in one transaction (Store.SponsorExistingAccounts).
+// It reports how many accounts it sponsored. On any error the caller must
+// run with no catalog: plans off, and the next start retries.
+func SettleLaunchSponsorship(ctx context.Context, rel release.Store, st *Store, cat *plans.Catalog, now time.Time) (int, error) {
if cat == nil {
- return false, nil
+ return 0, 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()
+ cutoff := cat.SponsorCutoff()
if cutoff.IsZero() {
- s.sponsorSettled.Store(true)
- return nil
+ return 0, nil
}
- owed, err := s.store.AccountsOwedSponsorship(cutoff)
- if err != nil {
- return fmt.Errorf("accounts owed sponsorship: %w", err)
+ if cutoff.After(now) {
+ return 0, 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))
}
- 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))
- }
+ _, unread, err := materializeAccounts(ctx, rel, st)
+ if err != nil {
+ return 0, fmt.Errorf("reading the bucket's accounts: %w", err)
}
- if err := errors.Join(errs...); err != nil {
- return err
+ if unread > 0 {
+ return 0, fmt.Errorf("%d account manifests in the bucket could not be read, so not every account is known", unread)
}
- if !now.Before(cutoff.Add(sponsorSettleMargin)) {
- s.sponsorSettled.Store(true)
+ n, err := st.SponsorExistingAccounts(cat, cutoff, sponsorUnlimited(), planSponsorReason, planDefaultActor, now)
+ if err != nil {
+ return 0, fmt.Errorf("writing the sponsored plans: %w", err)
}
- return nil
+ return n, 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)
+// 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 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 false, err
}
- return nil
+ return row != nil && planRowSponsored(row), nil
}
diff --git a/internal/console/plansponsor_test.go b/internal/console/plansponsor_test.go
index 007311b59..a4da0e787 100644
--- a/internal/console/plansponsor_test.go
+++ b/internal/console/plansponsor_test.go
@@ -3,6 +3,7 @@ package console
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"math"
"net/http"
@@ -14,13 +15,15 @@ import (
"github.com/carlosframework/platform/internal/domains"
"github.com/carlosframework/platform/internal/plans"
"github.com/carlosframework/platform/internal/ratelimit"
+ "github.com/carlosframework/platform/internal/release"
)
// Accounts that existed when plans went on are sponsored with no limits
-// (Paul, 2026-10-31): sponsor_accounts_before in the catalog.
+// (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.
+// to cutoff, in whole seconds.
func sponsorCatalog(t *testing.T, cutoff time.Time) *plans.Catalog {
t.Helper()
b, err := os.ReadFile(exampleCatalogPath)
@@ -33,19 +36,14 @@ func sponsorCatalog(t *testing.T, cutoff time.Time) *plans.Catalog {
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.
+// 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)
-// 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()
@@ -60,6 +58,13 @@ func newPlanAccount(t *testing.T, fx *consoleFixture, id int64, created time.Tim
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
@@ -139,34 +144,32 @@ func TestSponsorUnlimitedOverflowsNothing(t *testing.T) {
}
}
-// 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) {
+// 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)
- fx.srv.cfg.PlanCatalog = sponsorCatalog(t, sponsorCutoffAt)
+ cat := 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 {
+ 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)
- if _, err := fx.st.db.Exec(`UPDATE accounts SET deleted_at = ? WHERE id = ?`, planNow.Unix(), gone.ID); err != nil {
- t.Fatal(err)
- }
+ markDeleted(t, fx, gone)
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")
+ n, err := SettleLaunchSponsorship(ctx, fx.rel, 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 {
@@ -174,98 +177,77 @@ func TestSponsorSettlementSponsorsExistingAccounts(t *testing.T) {
}
unlimited := sponsorUnlimited()
if row.Plan != "free" || row.Source != PlanSourceSponsored || row.Reason != planSponsorReason ||
- row.UpdatedBy != planDefaultActor || row.Sponsored == nil || *row.Sponsored != unlimited {
+ row.UpdatedBy != planDefaultActor || row.Revision != 1 || 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 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 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)
+ 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)
}
- 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 i := range 5 {
+ capsApp(t, fx, old, fmt.Sprintf("app%d", i))
}
- 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 err := fx.srv.checkRunningThings(ctx, old, 1); err != nil {
+ t.Fatalf("running-things check past the free plan's 3: %v", err)
}
- if got, _ := fx.st.AccountPlan(gone.ID); got != nil {
- t.Fatalf("a deleted account got a row: %+v", got)
+ 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(ops.ID); got != nil {
- t.Fatalf("ops got a row: %+v", got)
+ 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 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")
+ // A second start sponsors nothing and rewrites nothing.
+ if n, err := SettleLaunchSponsorship(ctx, fx.rel, 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 rerun rewrote the sponsored row: %+v, was %+v", again, row)
+ t.Fatalf("the second start 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)
- }
- })
+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(context.Background(), fx.rel, 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(context.Background(), fx.rel, 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(context.Background(), fx.rel, fx.st, sponsorCatalog(t, planNow), planNow); err != nil || n != 1 {
+ t.Fatalf("cutoff at the start = %d, %v", n, err)
}
}
@@ -285,131 +267,166 @@ func failPlanWrite(t *testing.T, fx *consoleFixture, accountID int64) func() {
}
}
-// 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) {
+// One transaction: a failed write leaves no account sponsored, and the
+// next start writes them all.
+func TestSettleLaunchSponsorshipIsOneTransaction(t *testing.T) {
fx := newConsoleFixture(t)
- fx.srv.cfg.PlanCatalog = sponsorCatalog(t, sponsorCutoffAt)
- ctx := context.Background()
+ cat := sponsorCatalog(t, sponsorCutoffAt)
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 _, err := SettleLaunchSponsorship(context.Background(), fx.rel, fx.st, cat, planNow); err == nil {
+ t.Fatal("settled with a write failing")
}
- if row, _ := fx.st.AccountPlan(first.ID); row == nil || row.Source != PlanSourceSponsored {
- t.Fatalf("the account that could be written = %+v", row)
+ 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)
+ }
}
- if row, _ := fx.st.AccountPlan(stuck.ID); row != nil {
- t.Fatalf("the failed account has a row: %+v", row)
+ heal()
+ if n, err := SettleLaunchSponsorship(context.Background(), fx.rel, fx.st, cat, planNow); err != nil || n != 2 {
+ t.Fatalf("retry = %d, %v; want 2", n, err)
}
- if rec, _ := readLimits(t, fx, stuck.Sqid); rec != nil {
- t.Fatalf("the failed account has a limits record: %+v", rec)
+}
+
+// getFails fails Get of one key.
+type getFails struct {
+ release.Store
+ key string
+}
+
+func (g getFails) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if key == g.key {
+ return nil, "", errors.New("bucket unavailable")
}
- if l, err := fx.srv.EffectiveLimits(stuck); err != nil || l != nil {
- t.Fatalf("the failed account's limits = %+v, %v; want none", l, err)
+ return g.Store.Get(ctx, key)
+}
+
+// The settlement brings in the bucket's accounts first, so an account
+// minted elsewhere before the cutoff is sponsored at this start, not
+// materialized later with the default plan; and a manifest it cannot read
+// refuses the settlement rather than leave an account out.
+func TestSettleLaunchSponsorshipMaterializesFirst(t *testing.T) {
+ fx := newConsoleFixture(t)
+ cat := sponsorCatalog(t, sponsorCutoffAt)
+ ctx := context.Background()
+ id, sqid, err := domains.MintAccount(ctx, fx.rel, "elsewhere", "owner@example.com", sponsorCutoffAt.Add(-24*time.Hour))
+ if err != nil {
+ t.Fatal(err)
}
- if err := fx.srv.checkRunningThings(ctx, stuck, 100); err != nil {
- t.Fatalf("a cap check on the failed account: %v", err)
+ if a, _ := fx.st.AccountBySqid(sqid); a != nil {
+ t.Fatal("setup: the console already knows the minted account")
}
- // 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)
+ _, err = SettleLaunchSponsorship(ctx, getFails{Store: fx.rel, key: domains.AccountManifestKey(sqid)}, fx.st, cat, planNow)
+ if err == nil || !strings.Contains(err.Error(), "could not be read") {
+ t.Fatalf("an unreadable manifest = %v, want a refusal", err)
}
-
- heal()
- fx.srv.planLimitsPass(ctx, settledNow.Add(time.Minute))
- if !fx.srv.sponsorSettled.Load() {
- t.Fatal("settlement did not finish on the retry")
+ if n, err := SettleLaunchSponsorship(ctx, fx.rel, fx.st, cat, planNow); err != nil || n != 1 {
+ t.Fatalf("settle = %d, %v", n, err)
}
- 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 row, _ := fx.st.AccountPlan(id); row == nil || row.Source != PlanSourceSponsored {
+ t.Fatalf("the minted 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)
+}
+
+// The settlement's write passes the host-claim store's SQL gate.
+func TestSponsorExistingAccountsUnderTheGate(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 row, _ := fx.st.AccountPlan(fresh.ID); row == nil || row.Source != PlanSourceDefault {
- t.Fatalf("the new account after settlement = %+v", row)
+ if n, err := s.SponsorExistingAccounts(sponsorCatalog(t, sponsorCutoffAt), sponsorCutoffAt, sponsorUnlimited(),
+ planSponsorReason, planDefaultActor, planNow); err != nil || n != 1 {
+ t.Fatalf("under the gate = %d, %v", n, err)
}
}
-// 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")
+// 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(context.Background(), fx.rel, fx.st, cat, time.Now().Add(2*time.Hour)); err != nil {
+ t.Fatal(err)
}
- if row, _ := fx.st.AccountPlan(early.ID); row == nil || row.Source != PlanSourceSponsored {
- t.Fatalf("early account = %+v", row)
+ 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)
}
- 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)
+}
+
+// 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)
+ }
}
- 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)
+ 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)
}
- fx.srv.planLimitsPass(ctx, cutoff)
- if fx.srv.sponsorSettled.Load() {
- t.Fatal("settled inside the margin")
+}
+
+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)
}
- fx.srv.planLimitsPass(ctx, cutoff.Add(sponsorSettleMargin))
- if !fx.srv.sponsorSettled.Load() {
- t.Fatal("not settled after the margin")
+ if h := sidecarHibernate(t, fx); h == nil || *h {
+ t.Fatalf("hibernate = %v, want false", h)
}
}
-// 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)
+// 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)
- 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 {
+ if _, err := fx.st.EnsureDefaultPlans("free", planNow); err != nil {
t.Fatal(err)
}
- before, _ := fx.st.AccountPlan(acct.ID)
- if err := fx.srv.sponsorExistingAccount(ctx, acct, planNow); err != nil {
+ 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)
}
- if after, _ := fx.st.AccountPlan(acct.ID); after == nil || after.Revision != before.Revision || after.Source != PlanSourceOperator {
- t.Fatalf("row = %+v, was %+v", after, before)
+ var got []string
+ for _, inc := range planIncludes(l, 0) {
+ got = append(got, inc.Text)
}
- // 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)
+ 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 err := fx.srv.sponsorExistingAccount(ctx, gone, planNow); err != nil {
- t.Fatalf("a deleted account: %v", err)
+ if u := useOfLimit(map[capID]int64{capRunningThings: 4}, capRunningThings, int64(l.RunningThings)); u == nil || u.Text != "You use 4" {
+ t.Fatalf("use = %+v", u)
}
-}
-
-// 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 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)
}
- if !fx.srv.sponsorSettled.Load() {
- t.Fatal("nothing to settle, but not settled")
+ // 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)
}
}
diff --git a/internal/console/server.go b/internal/console/server.go
index abf8f0929..97316bf34 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -979,10 +979,6 @@ 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 0867675f8..aec5851ce 100644
--- a/internal/plans/catalog.go
+++ b/internal/plans/catalog.go
@@ -91,12 +91,12 @@ 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, 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
@@ -168,8 +168,10 @@ func (c *Catalog) validate() error {
}
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)
+ if err != nil || t.Nanosecond() != 0 {
+ // Whole seconds only: accounts record their creation to the
+ // second, so a fraction would be compared truncated.
+ 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
}
diff --git a/internal/plans/catalog_test.go b/internal/plans/catalog_test.go
index 036f95804..40024a82b 100644
--- a/internal/plans/catalog_test.go
+++ b/internal/plans/catalog_test.go
@@ -255,6 +255,9 @@ func TestCatalogSponsorAccountsBefore(t *testing.T) {
"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"`,
} {
body := strings.Replace(base, `"default_plan": "free",`, `"default_plan": "free", "sponsor_accounts_before": `+v+`,`, 1)
if _, err := ParseCatalog([]byte(body)); err == nil {
diff --git a/internal/provision/testdata/plan14-root-reads-sponsor-existing-accounts.tsv b/internal/provision/testdata/plan14-root-reads-sponsor-existing-accounts.tsv
index 09c07be35..b17846def 100644
--- a/internal/provision/testdata/plan14-root-reads-sponsor-existing-accounts.tsv
+++ b/internal/provision/testdata/plan14-root-reads-sponsor-existing-accounts.tsv
@@ -1,3 +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
+@coverage internal/plans d8c151d6c0a2cd609ce824206be3d0843ebcf60dcdb5fe76bd2f2a88ce6db6db