carlos / platform Public

console: carry launch rows in the transaction that writes the rule

Astra's open P2 on Task 6, second round on the launch-sponsorship
invariant: the carry committed before the stored rule was rewritten, so
`console member` could materialize an old account between the two with
the old figures, and the start's candidate query then skipped it.

The carry (carryLaunchFiguresTx) now runs inside
StartLaunchSponsorship's transaction right after the rule write, or
with the rule's DELETE when the catalog has no cutoff. The invariant is
stated at SettleLaunchSponsorship: every launch-sponsored account has
the current unlimited figures before plans serve.
TestLaunchCarryAndRuleAreOneTransaction materializes an account at the
old gap (launchSettledHook) and fails against the two-transaction code.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 1623b85adbdf2fffad56b959bf2ccb1803926fde parent c74e3c9
3 files changed, +177 −45
  • internal/console/accountplans.go +21 −14
  • internal/console/planmedia_test.go +81 −2
  • internal/console/plansponsor.go +75 −29

CI failed — run details

diff --git a/internal/console/accountplans.go b/internal/console/accountplans.go
index fcf78c4b5..f25d2392b 100644
--- a/internal/console/accountplans.go
+++ b/internal/console/accountplans.go
@@ -266,52 +266,59 @@ func (s *Store) EnsureDefaultPlans(defaultPlan string, now time.Time) (int, erro
// 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.
+// transaction, and nothing is written, the rule included. In the same
+// transaction, right after the rule, it carries the launch rows written
+// before the current figures (carryLaunchFiguresTx; the carry invariant,
+// SettleLaunchSponsorship). It reports how many rows it wrote and how many
+// it carried.
//
// It runs before the console serves, so nothing else writes plans then.
// Of the plan transition (transitionAccountPlan) nothing is owed: an
// account with no row has no lapse to start, no throttle or cap rows to
// reset, and nothing published; the first limits pass publishes the rows
// (revision 1, published 0) and the first grace pass measures them.
-func (s *Store) StartLaunchSponsorship(cat *plans.Catalog, cutoff time.Time, sponsored plans.Limits, reason, by string, now time.Time) (int, error) {
+func (s *Store) StartLaunchSponsorship(cat *plans.Catalog, cutoff time.Time, sponsored plans.Limits, reason, by string, now time.Time) (int, int, error) {
if cutoff.IsZero() {
- return 0, errors.New("console: launch sponsorship with no cutoff")
+ return 0, 0, errors.New("console: launch sponsorship with no cutoff")
}
sj, err := json.Marshal(sponsored)
if err != nil {
- return 0, err
+ return 0, 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
+ return 0, 0, err
}
defer tx.Rollback()
if _, err := tx.Exec(`INSERT INTO plan_launch_sponsorship (id, cutoff, plan, sponsored, reason, updated_by, updated_at)
VALUES (1, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET cutoff = excluded.cutoff, plan = excluded.plan,
sponsored = excluded.sponsored, reason = excluded.reason, updated_by = excluded.updated_by, updated_at = excluded.updated_at`,
rule.cutoff, rule.plan, rule.sponsored, rule.reason, rule.by, now.Unix()); err != nil {
- return 0, err
+ return 0, 0, err
+ }
+ carried, err := carryLaunchFiguresTx(tx, sponsored, reason, by, now)
+ if err != nil {
+ return 0, 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
+ return 0, 0, err
}
var all []candidate
for rows.Next() {
var c candidate
if err := rows.Scan(&c.id, &c.created); err != nil {
rows.Close()
- return 0, err
+ return 0, 0, err
}
all = append(all, c)
}
rows.Close()
if err := rows.Err(); err != nil {
- return 0, err
+ return 0, 0, err
}
n := 0
for _, c := range all {
@@ -319,20 +326,20 @@ func (s *Store) StartLaunchSponsorship(cat *plans.Catalog, cutoff time.Time, spo
continue
}
if _, err := cat.Effective(cat.DefaultPlan, nil, &sponsored); err != nil {
- return 0, fmt.Errorf("account %d: %w", c.id, err)
+ return 0, 0, fmt.Errorf("account %d: %w", c.id, err)
}
wrote, err := rule.apply(tx, s.planExemptID, c.id, c.created, now)
if err != nil {
- return 0, fmt.Errorf("account %d: %w", c.id, err)
+ return 0, 0, fmt.Errorf("account %d: %w", c.id, err)
}
if wrote {
n++
}
}
if err := tx.Commit(); err != nil {
- return 0, err
+ return 0, 0, err
}
- return n, nil
+ return n, carried, nil
}
// PlansToPublish lists live accounts whose bucket record is behind their
diff --git a/internal/console/planmedia_test.go b/internal/console/planmedia_test.go
index 3ffd5cec1..d698815fe 100644
--- a/internal/console/planmedia_test.go
+++ b/internal/console/planmedia_test.go
@@ -486,8 +486,13 @@ func TestLaunchSponsorshipCarriesMedia(t *testing.T) {
if n, err := SettleLaunchSponsorship(fx.st, cat, planNow.Add(time.Hour)); err != nil || n != 0 {
t.Fatalf("second settle = %d, %v", n, err)
}
- if n, err := fx.st.carryLaunchFigures(sponsorUnlimited(), planNow.Add(2*time.Hour)); err != nil || n != 0 {
- t.Fatalf("second carry = %d, %v", n, err)
+ tx, err := fx.st.db.Begin()
+ if err != nil {
+ t.Fatal(err)
+ }
+ n, err := carryLaunchFiguresTx(tx, sponsorUnlimited(), planSponsorReason, planDefaultActor, planNow.Add(2*time.Hour))
+ if cerr := tx.Commit(); err != nil || cerr != nil || n != 0 {
+ t.Fatalf("second carry = %d, %v, %v", n, err, cerr)
}
for id, r := range planRowsNow(t, fx.st) {
if r != settled[id] {
@@ -511,3 +516,77 @@ func TestLaunchSponsorshipCarriesMediaWithoutCutoffAndUnderTheGate(t *testing.T)
t.Fatalf("row = %+v, %v", row, err)
}
}
+
+// TestLaunchCarryAndRuleAreOneTransaction (Task 6 fix round 2, Astra's
+// open P2): the stored rule is an old console's, without the PDF and media
+// figures. `console member` materializes an account created before the
+// cutoff at the point between carrying the launch rows and writing the
+// rule, were those two transactions (launchSettledHook). It must end with
+// the current unlimited figures, like every launch-sponsored account,
+// before plans serve.
+func TestLaunchCarryAndRuleAreOneTransaction(t *testing.T) {
+ for _, name := range []string{"with a cutoff", "without a cutoff"} {
+ t.Run(name, func(t *testing.T) {
+ fx := newConsoleFixture(t)
+ ctx := t.Context()
+ cat := mediaSponsorCatalog(t, sponsorCutoffAt)
+ if name == "without a cutoff" {
+ cat = mediaPlanCatalog(t)
+ }
+ // What an older console recorded: the rule and one launch row,
+ // both with the figures of their day.
+ old, err := json.Marshal(prePDFLaunch())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.db.Exec(`INSERT INTO plan_launch_sponsorship (id, cutoff, plan, sponsored, reason, updated_by, updated_at)
+ VALUES (1, ?, 'free', ?, ?, ?, ?)`, sponsorCutoffAt.Unix(), string(old), planSponsorReason, planDefaultActor, planNow.Add(-24*time.Hour).Unix()); err != nil {
+ t.Fatal(err)
+ }
+ // An account inserted under that rule gets its launch row.
+ existing := planAccount(t, fx, 501)
+ if row, _ := fx.st.AccountPlan(existing.ID); row == nil || row.Sponsored == nil || *row.Sponsored != prePDFLaunch() {
+ t.Fatalf("fixture: launch row under the old rule = %+v", row)
+ }
+ // Minted by the CLI before the cutoff, its manifest not yet
+ // materialized.
+ early := sponsorCutoffAt.Add(-time.Minute)
+ if err := WriteAccountManifest(ctx, fx.rel, 601, domains.Sqid(601), "late", early); err != nil {
+ t.Fatal(err)
+ }
+ ran := false
+ launchSettledHook = func() {
+ ran = true
+ if _, err := MaterializeAccounts(ctx, fx.rel, fx.st); err != nil {
+ t.Error(err)
+ }
+ }
+ t.Cleanup(func() { launchSettledHook = nil })
+ if _, err := SettleLaunchSponsorship(fx.st, cat, planNow); err != nil {
+ t.Fatal(err)
+ }
+ if !ran {
+ t.Fatal("the hook did not run")
+ }
+ want := sponsorUnlimited()
+ if row, err := fx.st.AccountPlan(existing.ID); err != nil || row == nil || row.Sponsored == nil || *row.Sponsored != want {
+ t.Fatalf("existing launch row = %+v, %v", row, err)
+ }
+ row, err := fx.st.AccountPlan(601)
+ if name == "without a cutoff" {
+ // No rule: the late account has no launch row to be stale.
+ if err != nil || row != nil {
+ t.Fatalf("materialized with the rule cleared = %+v, %v", row, err)
+ }
+ return
+ }
+ if err != nil || row == nil || row.Source != PlanSourceSponsored || row.Sponsored == nil || *row.Sponsored != want {
+ t.Fatalf("account materialized between the steps = %+v, %v; want the current launch figures", row, err)
+ }
+ // And the next start finds nothing left to do.
+ if n, err := SettleLaunchSponsorship(fx.st, cat, planNow.Add(time.Hour)); err != nil || n != 0 {
+ t.Fatalf("restart = %d, %v", n, err)
+ }
+ })
+ }
+}
diff --git a/internal/console/plansponsor.go b/internal/console/plansponsor.go
index 2e6dab838..60bcdfe9e 100644
--- a/internal/console/plansponsor.go
+++ b/internal/console/plansponsor.go
@@ -118,32 +118,81 @@ func sponsorUnlimited() plans.Limits {
// failed, so an old rule may still be recorded and would go on sponsoring
// every account inserted. The console must not start then (Astra R3).
//
-// With a catalog, it first carries launch sponsorships written before
-// the PDF service or media conversion forward (Store.carryLaunchFigures),
-// cutoff or not: such rows still sponsor their accounts.
+// THE CARRY INVARIANT (Task 6 fix round 2, enforced here and only here):
+// before plans serve, every launch-sponsored account has the current
+// unlimited figures. With a catalog, launch sponsorships written before
+// the PDF service or media conversion are carried forward
+// (carryLaunchFiguresTx) in the same transaction that records or clears
+// the rule (Store.StartLaunchSponsorship, Store.clearLaunchRuleCarrying),
+// and that transaction's first statement is the rule write, so it holds
+// SQLite's write lock throughout. An account insert (CreateAccount,
+// EnsureAccount: NewServer's or `console member`'s MaterializeAccounts)
+// reads the rule inside its own transaction, so it either commits before
+// this one, and its row is carried here, or after, and it reads the new
+// rule or none. No insert can see the old rule once any row is carried,
+// and no row is left uncarried once the new rule is visible.
func SettleLaunchSponsorship(st *Store, cat *plans.Catalog, now time.Time) (int, error) {
- if cat != nil {
- carried, err := st.carryLaunchFigures(sponsorUnlimited(), now)
+ if cat == nil {
+ return 0, clearLaunchRule(st)
+ }
+ n, carried, err := settleLaunchRule(st, cat, now)
+ if err != nil {
+ return 0, err
+ }
+ if carried > 0 {
+ log.Printf("console: plans: %d launch sponsorships now include PDFs and media minutes", carried)
+ }
+ if launchSettledHook != nil {
+ launchSettledHook()
+ }
+ return n, nil
+}
+
+// launchSettledHook, when set (tests only), runs once the carried rows
+// are committed: the point where, were the carry and the rule write ever
+// two transactions, an account insert could read the old rule.
+var launchSettledHook func()
+
+// settleLaunchRule is SettleLaunchSponsorship with a catalog: the rule
+// recorded or cleared, and the launch rows carried, in one transaction.
+func settleLaunchRule(st *Store, cat *plans.Catalog, now time.Time) (int, int, error) {
+ launch := sponsorUnlimited()
+ if cat.SponsorCutoff().IsZero() {
+ carried, err := st.clearLaunchRuleCarrying(launch, planSponsorReason, planDefaultActor, now)
if err != nil {
- return 0, errors.Join(fmt.Errorf("carrying the launch sponsorships forward: %w", err), clearLaunchRule(st))
- }
- if carried > 0 {
- log.Printf("console: plans: %d launch sponsorships now include PDFs and media minutes", carried)
+ return 0, 0, errors.Join(fmt.Errorf("carrying the launch sponsorships forward: %w", err), clearLaunchRule(st))
}
- }
- if cat == nil || cat.SponsorCutoff().IsZero() {
- return 0, clearLaunchRule(st)
+ return 0, carried, nil
}
cutoff := cat.SponsorCutoff()
if cutoff.After(now) {
- return 0, errors.Join(fmt.Errorf("sponsor_accounts_before %s is after the console's start (%s): set it to when plans go on, not later",
+ return 0, 0, errors.Join(fmt.Errorf("sponsor_accounts_before %s is after the console's start (%s): set it to when plans go on, not later",
cutoff.UTC().Format(time.RFC3339), now.UTC().Format(time.RFC3339)), clearLaunchRule(st))
}
- n, err := st.StartLaunchSponsorship(cat, cutoff, sponsorUnlimited(), planSponsorReason, planDefaultActor, now)
+ n, carried, err := st.StartLaunchSponsorship(cat, cutoff, launch, planSponsorReason, planDefaultActor, now)
if err != nil {
- return 0, errors.Join(fmt.Errorf("writing the sponsored plans: %w", err), clearLaunchRule(st))
+ return 0, 0, errors.Join(fmt.Errorf("writing the sponsored plans: %w", err), clearLaunchRule(st))
}
- return n, nil
+ return n, carried, nil
+}
+
+// clearLaunchRuleCarrying removes the recorded rule (plans on without a
+// cutoff) and carries the launch rows that still sponsor their accounts,
+// in one transaction (the carry invariant, SettleLaunchSponsorship).
+func (s *Store) clearLaunchRuleCarrying(launch plans.Limits, reason, by string, now time.Time) (int, error) {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return 0, err
+ }
+ defer tx.Rollback()
+ if _, err := tx.Exec(`DELETE FROM plan_launch_sponsorship`); err != nil {
+ return 0, err
+ }
+ n, err := carryLaunchFiguresTx(tx, launch, reason, by, now)
+ if err != nil {
+ return 0, err
+ }
+ return n, tx.Commit()
}
// launchCarried are the launch figures added after launch sponsorships
@@ -153,13 +202,15 @@ func SettleLaunchSponsorship(st *Store, cat *plans.Catalog, now time.Time) (int,
// while every other figure is unlimited.
var launchCarried = []string{"pdf_renders_month", "media_minutes_month"}
-// carryLaunchFigures gives every launch sponsorship that lacks one of
-// launchCarried the figure launch now carries (Task 6 fix rounds 1 and 2).
-// One transaction; idempotent, so every start runs it.
+// carryLaunchFiguresTx gives every launch sponsorship that lacks one of
+// launchCarried the figure launch now carries (Task 6 fix rounds 1 and 2),
+// inside tx, which also writes the rule (the carry invariant,
+// SettleLaunchSponsorship). Idempotent, so every start runs it.
//
// A launch row is what launchRule.apply writes and nothing else does:
-// source sponsored, reason planSponsorReason and writer planDefaultActor
-// (the plan door records the operator's address, billing its own source).
+// source sponsored, the rule's reason and writer (planSponsorReason,
+// planDefaultActor; the plan door records the operator's address, billing
+// its own source).
// It is carried only when its sponsored limits lack a launchCarried field
// and every field they do have holds launch's value: a row written by an
// earlier launch figure set may lack later fields, but a field that
@@ -167,7 +218,7 @@ var launchCarried = []string{"pdf_renders_month", "media_minutes_month"}
// missing launchCarried fields are added; a carried row's revision is
// bumped so the publish pass sends its limits record again; nothing else
// in it changes.
-func (s *Store) carryLaunchFigures(launch plans.Limits, now time.Time) (int, error) {
+func carryLaunchFiguresTx(tx *sql.Tx, launch plans.Limits, reason, by string, now time.Time) (int, error) {
lj, err := json.Marshal(launch)
if err != nil {
return 0, err
@@ -181,13 +232,8 @@ func (s *Store) carryLaunchFigures(launch plans.Limits, now time.Time) (int, err
return 0, fmt.Errorf("console: the launch figures have no %s to carry", k)
}
}
- tx, err := s.db.Begin()
- if err != nil {
- return 0, err
- }
- defer tx.Rollback()
rows, err := tx.Query(`SELECT account_id, sponsored FROM account_plans
- WHERE source = ? AND reason = ? AND updated_by = ? ORDER BY account_id`, PlanSourceSponsored, planSponsorReason, planDefaultActor)
+ WHERE source = ? AND reason = ? AND updated_by = ? ORDER BY account_id`, PlanSourceSponsored, reason, by)
if err != nil {
return 0, err
}
@@ -262,7 +308,7 @@ func (s *Store) carryLaunchFigures(launch plans.Limits, now time.Time) (int, err
n++
}
}
- return n, tx.Commit()
+ return n, nil
}
// jsonFields is a JSON object's fields, numbers kept exact (json.Number),