plans: sponsor on insert, one rule in the store (Astra R2)
Astra round 2 found the startup scan could still miss an account: a CLI mint captures a pre-cutoff creation time but publishes its manifest after the scan, and NewServer or `console member` then materializes it with no row, so it met default caps and could check out (P1, settlement completeness and the payment boundary, stopping rule 2). Paul chose the structural fix: sponsor on insert. - The rule is recorded in the database (new table plan_launch_sponsorship, classified NonApp in claimSQLTables). SettleLaunchSponsorship, still run in serve() before NewServer, records it and applies it to every account already there, in one transaction. A start with plans off (no catalog, no cutoff, a refused cutoff or a failed write) clears it. - Every account insert applies the recorded rule in its own transaction: CreateAccount, EnsureAccount (now a transaction: NewServer's and `console member`'s materialization, late-published manifests) and the ops backfill. An account and its sponsored row commit together. - `console member` loads no catalog and takes no lock; it reads the rule from the database, so it applies it too. - The startup materialize-and-refuse-on-unread step is gone (materialize.go is back to main): late arrivals are sponsored on insert. - Invariant, stated in plansponsor.go and checked by assertSponsorInvariant: while plans are on with a cutoff, no account created before the cutoff is visible without a plan row, and the rule's row is the sponsored one. - P2: sponsor_accounts_before with any '.' (a fraction) is refused before parsing; Go drops digits past the ninth. Tests: late manifest via NewServer and MaterializeAccounts, then the limits pass and a restart; the built `console member` binary with no catalog; plans off then on; insert and sponsorship as one commit (a failed row leaves no account); the rule under the host-claim gate. Census: internal/plans envelope re-pinned (catalog.go); overlay re-proposed, census clean.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
13 files changed,
+470
−168
cmd/console/main.go+8 −8cmd/console/member_test.go+54 −0cmd/console/plansponsor.go+13 −8cmd/console/plansponsor_test.go+2 −5internal/console/accountplans.go+38 −25internal/console/materialize.go+6 −16internal/console/plansponsor.go+102 −44internal/console/plansponsor_test.go+187 −54internal/console/store.go+46 −4internal/console/store_gate.go+3 −0internal/plans/catalog.go+6 −3internal/plans/catalog_test.go+4 −0internal/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 c413182a1..86586044d 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -365,20 +365,17 @@ 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()) |
| + // 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. |
| + catalog, plansOff := sponsorAtStart(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 := billingConfigFor(os.Getenv, catalog, plansOff) |
| @@ -415,6 +412,9 @@ 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/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| index 33e6401a7..f0d88de27 100644 |
| --- a/cmd/console/plansponsor.go |
| +++ b/cmd/console/plansponsor.go |
| @@ -1,23 +1,28 @@ |
| 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) |
| +// (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. |
| +func sponsorAtStart(st *console.Store, cat *plans.Catalog, now time.Time) (_ *plans.Catalog, plansOff bool) { |
| + n, err := console.SettleLaunchSponsorship(st, cat, now) |
| + if err != nil && (cat == nil || cat.SponsorCutoff().IsZero()) { |
| + // Only the clearing of an old rule failed; plans are as configured. |
| + log.Printf("console: clearing the launch sponsorship rule: %v", err) |
| + return cat, false |
| + } |
| 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; "+ |
diff --git a/cmd/console/plansponsor_test.go b/cmd/console/plansponsor_test.go| index 59c0dbddf..bc5038fd2 100644 |
| --- a/cmd/console/plansponsor_test.go |
| +++ b/cmd/console/plansponsor_test.go |
| @@ -1,7 +1,6 @@ |
| package main |
| import ( |
| - "context" |
| "go/ast" |
| "go/parser" |
| "go/token" |
| @@ -14,7 +13,6 @@ 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" |
| ) |
| func sponsorTestCatalog(t *testing.T, cutoff time.Time) *plans.Catalog { |
| @@ -41,7 +39,6 @@ func TestSponsorAtStart(t *testing.T) { |
| 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) |
| @@ -53,7 +50,7 @@ func TestSponsorAtStart(t *testing.T) { |
| return "" |
| } |
| - cat, off := sponsorAtStart(context.Background(), rel, st, sponsorTestCatalog(t, now.Add(time.Hour)), now) |
| + cat, off := sponsorAtStart(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) |
| } |
| @@ -65,7 +62,7 @@ func TestSponsorAtStart(t *testing.T) { |
| } |
| want := sponsorTestCatalog(t, now.Add(-time.Hour)) |
| - cat, off = sponsorAtStart(context.Background(), rel, st, want, now) |
| + cat, off = sponsorAtStart(st, want, now) |
| if cat != want || off { |
| t.Fatalf("past cutoff: catalog kept %v, plans off %v", cat == want, off) |
| } |
diff --git a/internal/console/accountplans.go b/internal/console/accountplans.go| index 12edf2265..f9c8d0dfb 100644 |
| --- a/internal/console/accountplans.go |
| +++ b/internal/console/accountplans.go |
| @@ -256,21 +256,22 @@ func (s *Store) EnsureDefaultPlans(defaultPlan string, now time.Time) (int, erro |
| 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. |
| +// 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) SponsorExistingAccounts(cat *plans.Catalog, cutoff time.Time, sponsored plans.Limits, reason, by string, now time.Time) (int, error) { |
| +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") |
| } |
| @@ -278,49 +279,61 @@ func (s *Store) SponsorExistingAccounts(cat *plans.Catalog, cutoff time.Time, sp |
| 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() |
| - 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 := 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 ids []int64 |
| + var all []candidate |
| for rows.Next() { |
| - var id int64 |
| - if err := rows.Scan(&id); err != nil { |
| + var c candidate |
| + if err := rows.Scan(&c.id, &c.created); err != nil { |
| rows.Close() |
| return 0, err |
| } |
| - ids = append(ids, id) |
| + all = append(all, c) |
| } |
| 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) }) |
| + 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", id, err) |
| + return 0, fmt.Errorf("account %d: %w", c.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) |
| + 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 len(ids), nil |
| + return n, nil |
| } |
| // PlansToPublish lists live accounts whose bucket record is behind their |
diff --git a/internal/console/materialize.go b/internal/console/materialize.go| index 235d3dacd..1e9dca1fc 100644 |
| --- a/internal/console/materialize.go |
| +++ b/internal/console/materialize.go |
| @@ -39,23 +39,14 @@ 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, 0, nil |
| + return 0, nil |
| } |
| keys, err := s.List(ctx, "accounts/") |
| if err != nil { |
| - return 0, 0, err |
| + return 0, err |
| } |
| + n := 0 |
| for _, key := range keys { |
| sqid, ok := domains.AccountManifestSqid(key) |
| if !ok { |
| @@ -68,7 +59,7 @@ func materializeAccounts(ctx context.Context, s release.Store, st *Store) (n, un |
| // forgetting it is a takeover (see the switch below). |
| a, deleted, err := st.AccountAnyBySqid(sqid) |
| if err != nil { |
| - return n, unread, err |
| + return n, err |
| } |
| // Read UNCONDITIONALLY now, including for accounts we already know. |
| // This is the accepted cost of reaping: tombstone state lives in the |
| @@ -78,7 +69,6 @@ func materializeAccounts(ctx context.Context, s release.Store, st *Store) (n, un |
| body, _, err := s.Get(ctx, key) |
| if err != nil { |
| log.Printf("console: skipping %s: read failed: %v", key, err) |
| - unread++ |
| continue |
| } |
| var m accountManifest |
| @@ -159,7 +149,7 @@ func materializeAccounts(ctx context.Context, s release.Store, st *Store) (n, un |
| } |
| added, err := st.EnsureAccount(m.ID, m.Sqid, m.Name, created) |
| if err != nil { |
| - return n, unread, err |
| + return n, err |
| } |
| if !added { |
| // The sqid was free but the id was not: some other row already |
| @@ -195,7 +185,7 @@ func materializeAccounts(ctx context.Context, s release.Store, st *Store) (n, un |
| // ONLY here — on the pass that created the row, never on a later one. |
| materializeOwner(st, key, m, created) |
| } |
| - return n, unread, nil |
| + return n, nil |
| } |
| // materializeOwner turns the manifest's `owner` into the account's first owner |
diff --git a/internal/console/plansponsor.go b/internal/console/plansponsor.go| index 937f960ac..34e9b49a1 100644 |
| --- a/internal/console/plansponsor.go |
| +++ b/internal/console/plansponsor.go |
| @@ -1,41 +1,47 @@ |
| package console |
| import ( |
| - "context" |
| + "database/sql" |
| + "errors" |
| "fmt" |
| "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. |
| // |
| -// 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 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): |
| // |
| -// - 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. |
| +// - 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 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. |
| +// 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. |
| @@ -93,38 +99,90 @@ func sponsorUnlimited() plans.Limits { |
| } |
| } |
| -// 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 0, nil |
| +// 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. |
| +func SettleLaunchSponsorship(st *Store, cat *plans.Catalog, now time.Time) (int, error) { |
| + if cat == nil || cat.SponsorCutoff().IsZero() { |
| + return 0, st.ClearLaunchSponsorship() |
| } |
| cutoff := cat.SponsorCutoff() |
| - if cutoff.IsZero() { |
| - return 0, nil |
| - } |
| 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)) |
| + 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)), st.ClearLaunchSponsorship()) |
| } |
| - _, unread, err := materializeAccounts(ctx, rel, st) |
| + n, err := st.StartLaunchSponsorship(cat, cutoff, sponsorUnlimited(), planSponsorReason, planDefaultActor, now) |
| if err != nil { |
| - return 0, fmt.Errorf("reading the bucket's accounts: %w", err) |
| + return 0, errors.Join(fmt.Errorf("writing the sponsored plans: %w", err), st.ClearLaunchSponsorship()) |
| } |
| - if unread > 0 { |
| - return 0, fmt.Errorf("%d account manifests in the bucket could not be read, so not every account is known", unread) |
| + return n, 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 |
| } |
| - 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, err |
| } |
| - return n, nil |
| + 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 |
diff --git a/internal/console/plansponsor_test.go b/internal/console/plansponsor_test.go| index a4da0e787..64c9d97e8 100644 |
| --- a/internal/console/plansponsor_test.go |
| +++ b/internal/console/plansponsor_test.go |
| @@ -3,7 +3,6 @@ package console |
| import ( |
| "context" |
| "encoding/json" |
| - "errors" |
| "fmt" |
| "math" |
| "net/http" |
| @@ -15,7 +14,6 @@ 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 |
| @@ -167,7 +165,7 @@ func TestSettleLaunchSponsorship(t *testing.T) { |
| t.Fatalf("fixture: ops created %v, exempt %v", ops.CreatedAt, fx.st.planExempt(ops.ID)) |
| } |
| - n, err := SettleLaunchSponsorship(ctx, fx.rel, fx.st, cat, planNow) |
| + n, err := SettleLaunchSponsorship(fx.st, cat, planNow) |
| if err != nil || n != 1 { |
| t.Fatalf("settle = %d, %v; want 1 account", n, err) |
| } |
| @@ -212,7 +210,7 @@ func TestSettleLaunchSponsorship(t *testing.T) { |
| } |
| // 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 { |
| + 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 { |
| @@ -224,7 +222,7 @@ 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 { |
| + if n, err := SettleLaunchSponsorship(fx.st, cat, planNow); err != nil || n != 0 { |
| t.Fatalf("%s: %d, %v", name, n, err) |
| } |
| } |
| @@ -238,7 +236,7 @@ func TestSettleLaunchSponsorshipNothingToDo(t *testing.T) { |
| 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) |
| + _, 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) |
| } |
| @@ -246,7 +244,7 @@ func TestSettleLaunchSponsorshipRefusesAFutureCutoff(t *testing.T) { |
| 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 { |
| + if n, err := SettleLaunchSponsorship(fx.st, sponsorCatalog(t, planNow), planNow); err != nil || n != 1 { |
| t.Fatalf("cutoff at the start = %d, %v", n, err) |
| } |
| } |
| @@ -275,7 +273,7 @@ func TestSettleLaunchSponsorshipIsOneTransaction(t *testing.T) { |
| first := planAccount(t, fx, 501) |
| stuck := planAccount(t, fx, 502) |
| heal := failPlanWrite(t, fx, stuck.ID) |
| - if _, err := SettleLaunchSponsorship(context.Background(), fx.rel, fx.st, cat, planNow); err == nil { |
| + if _, err := SettleLaunchSponsorship(fx.st, cat, planNow); err == nil { |
| t.Fatal("settled with a write failing") |
| } |
| for _, a := range []*Account{first, stuck} { |
| @@ -284,61 +282,27 @@ func TestSettleLaunchSponsorshipIsOneTransaction(t *testing.T) { |
| } |
| } |
| heal() |
| - if n, err := SettleLaunchSponsorship(context.Background(), fx.rel, fx.st, cat, planNow); err != nil || n != 2 { |
| + if n, err := SettleLaunchSponsorship(fx.st, cat, planNow); err != nil || n != 2 { |
| t.Fatalf("retry = %d, %v; want 2", n, err) |
| } |
| } |
| -// 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") |
| - } |
| - 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 a, _ := fx.st.AccountBySqid(sqid); a != nil { |
| - t.Fatal("setup: the console already knows the minted account") |
| - } |
| - _, 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) |
| - } |
| - if n, err := SettleLaunchSponsorship(ctx, fx.rel, fx.st, cat, planNow); err != nil || n != 1 { |
| - t.Fatalf("settle = %d, %v", n, err) |
| - } |
| - if row, _ := fx.st.AccountPlan(id); row == nil || row.Source != PlanSourceSponsored { |
| - t.Fatalf("the minted account = %+v", row) |
| - } |
| -} |
| - |
| -// The settlement's write passes the host-claim store's SQL gate. |
| -func TestSponsorExistingAccountsUnderTheGate(t *testing.T) { |
| +// 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 := s.SponsorExistingAccounts(sponsorCatalog(t, sponsorCutoffAt), sponsorCutoffAt, sponsorUnlimited(), |
| - planSponsorReason, planDefaultActor, planNow); err != nil || n != 1 { |
| + 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) |
| @@ -347,7 +311,7 @@ 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 { |
| + if _, err := SettleLaunchSponsorship(fx.st, cat, time.Now().Add(2*time.Hour)); err != nil { |
| t.Fatal(err) |
| } |
| fx.srv.cfg.PlanCatalog = cat |
| @@ -430,3 +394,172 @@ func TestBillingShowsTheSponsorshipAsUnlimited(t *testing.T) { |
| 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 c6643a55d..d023b84ab 100644 |
| --- a/internal/console/store.go |
| +++ b/internal/console/store.go |
| @@ -422,6 +422,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 |
| @@ -896,9 +908,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 |
| @@ -1105,6 +1127,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() |
| } |
| @@ -1127,14 +1153,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 3a1bf127e..f49a9b36d 100644 |
| --- a/internal/console/store_gate.go |
| +++ b/internal/console/store_gate.go |
| @@ -247,6 +247,9 @@ var claimSQLTables = map[string]claimSQLTable{ |
| "billing_retirements": {NonApp: "accounts whose deletion is in progress, keyed by account; names no app"}, |
| "billing_restore_checks": {NonApp: "an account's late-restore verification obligations; names no app"}, |
| "billing_operations": {NonApp: "an account's billing operations, each one prepared provider request and its outcome, keyed by subscription; names no app"}, |
| + |
| + // 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 aec5851ce..6ea1fd546 100644 |
| --- a/internal/plans/catalog.go |
| +++ b/internal/plans/catalog.go |
| @@ -17,6 +17,7 @@ import ( |
| "math" |
| "os" |
| "slices" |
| + "strings" |
| "time" |
| "github.com/carlosframework/platform/internal/ratelimit" |
| @@ -167,10 +168,12 @@ func (c *Catalog) validate() error { |
| return errors.New("free_accounts_per_person is negative") |
| } |
| if c.SponsorAccountsBefore != "" { |
| + // Whole seconds only, refused on the syntax before parsing: accounts |
| + // record their creation to the second, so a fraction would be |
| + // compared truncated, and Go's parser silently drops digits past |
| + // the ninth. RFC 3339 has a '.' only before a fraction. |
| t, err := time.Parse(time.RFC3339, 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. |
| + if err != nil || strings.Contains(c.SponsorAccountsBefore, ".") { |
| 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 40024a82b..cb9031cee 100644 |
| --- a/internal/plans/catalog_test.go |
| +++ b/internal/plans/catalog_test.go |
| @@ -258,6 +258,10 @@ func TestCatalogSponsorAccountsBefore(t *testing.T) { |
| // 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"`, |
| } { |
| 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 b17846def..2d7e3c9f0 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 d8c151d6c0a2cd609ce824206be3d0843ebcf60dcdb5fe76bd2f2a88ce6db6db |
| +@coverage internal/plans 93d0b45241a247a6f6d3c7c67e12c8f5e4f230d0335f0fb4ab31ef58ca683f37 |