console: hourly plan grace pass with owner warnings (plans 4a)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+400
−0
cmd/console/main.go+1 −0internal/console/claim_invariant_fixtures_test.go+1 −0internal/console/claim_invariant_probes_worker_test.go+14 −0internal/console/claim_workers.go+1 −0internal/console/plancaps_copy.go+19 −0internal/console/plangracepass.go+217 −0internal/console/plangracepass_test.go+146 −0internal/console/testdata/claim-routes.txt+1 −0
diff --git a/cmd/console/main.go b/cmd/console/main.go| index d78578a29..773114ee3 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -603,6 +603,7 @@ func serve() { |
| // The plan limits pass (internal/console/planlimits.go): publishes each |
| // account's limits record. A no-op with CARLOS_PLAN_CATALOG unset. |
| go srv.RunClaimWorker(context.Background(), "StartPlanLimitsPass") |
| + go srv.RunClaimWorker(context.Background(), "StartPlanGracePass") |
| // The plans deployment marker (internal/console/plansmarker.go): once per |
| // start. Writes nothing on a deployment that never set a catalog. |
| go srv.RunClaimWorker(context.Background(), "PublishPlansMarker") |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 92749cd45..3f4234af7 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -1947,6 +1947,7 @@ var claimFixtures = map[string]claimFixture{ |
| "worker StartGeoipJobs": claimNonApp("GeoIP orphan sweep, D1 expiry and feed status under control/geoip/: the platform database, no app"), |
| "worker StartHostReports": claimNonApp("this console's census report (status/consoles) and roster activation release"), |
| "worker StartInfraPass": claimNonApp("the deployment's infrastructure inventory snapshot"), |
| + "worker StartPlanGracePass": claimNonApp("an account's plan cap warnings and grace clocks in plan_cap_state, keyed by account; names no app"), |
| "worker StartPlanLimitsPass": claimNonApp("account plan rows and their limits records under accounts/<sqid>/limits.json; names no app"), |
| "worker PublishPlansMarker": claimNonApp("the plans deployment marker (control/plans.json): whether boxes read limits; names no app"), |
| "worker StartClaimRecoveryPass": {door: &claimDoor{ |
diff --git a/internal/console/claim_invariant_probes_worker_test.go b/internal/console/claim_invariant_probes_worker_test.go| index a79737061..65f1ef5d9 100644 |
| --- a/internal/console/claim_invariant_probes_worker_test.go |
| +++ b/internal/console/claim_invariant_probes_worker_test.go |
| @@ -205,6 +205,20 @@ var claimWorkerProbes = map[string]claimProbe{ |
| return "" |
| }, |
| }, |
| + "worker StartPlanGracePass": { |
| + setup: func(t *testing.T, cx *claimCase) { cx.srv.cfg.PlanCatalog = examplePlanCatalog(t) }, |
| + do: claimWorkerReply("StartPlanGracePass"), |
| + effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| + acct, err := cx.srv.store.AccountBySqid("bab") |
| + if err != nil || acct == nil { |
| + return "no bab account" |
| + } |
| + if states, err := cx.srv.store.CapStates(acct.ID); err != nil || len(states) == 0 { |
| + return "no plan cap state was written for bab" |
| + } |
| + return "" |
| + }, |
| + }, |
| "worker StartPlanLimitsPass": { |
| setup: func(t *testing.T, cx *claimCase) { cx.srv.cfg.PlanCatalog = examplePlanCatalog(t) }, |
| do: claimWorkerReply("StartPlanLimitsPass"), |
diff --git a/internal/console/claim_workers.go b/internal/console/claim_workers.go| index ed947d88c..1f4c6d7d6 100644 |
| --- a/internal/console/claim_workers.go |
| +++ b/internal/console/claim_workers.go |
| @@ -15,6 +15,7 @@ func (s *Server) registerClaimWorkers() { |
| "StartScanDrain": s.StartScanDrain, |
| "StartExpiryPass": s.StartExpiryPass, |
| "StartPlanLimitsPass": s.StartPlanLimitsPass, |
| + "StartPlanGracePass": s.StartPlanGracePass, |
| "PublishPlansMarker": s.PublishPlansMarker, |
| "StartRunSweep": s.StartRunSweep, |
| "StartSeedsPass": s.StartSeedsPass, |
diff --git a/internal/console/plancaps_copy.go b/internal/console/plancaps_copy.go| index 81475dd29..4a7e94e42 100644 |
| --- a/internal/console/plancaps_copy.go |
| +++ b/internal/console/plancaps_copy.go |
| @@ -24,3 +24,22 @@ var capCopy = map[string]string{ |
| // planCheckFailedCopy is the approved answer when an account's plan could |
| // not be read (copy review 2026-10-22, cli.err.plan_check_failed). |
| const planCheckFailedCopy = "could not check this account's plan. Try again" |
| + |
| +// planNoticeCopy holds the plan warning and grace notices (plans 4a). Copy |
| +// review is a Luna pass on the house rules (Paul, 2026-10-25). |
| +var planNoticeCopy = map[string]string{ |
| + "usage.running_things": "%d of %d apps and instances", |
| + "usage.storage": "%s of %s object storage", |
| + "usage.email": "%d of %d emails today", |
| + "usage.bandwidth": "%s of %s bandwidth this month", |
| + "usage.awake_hours": "%d of %d awake hours this month", |
| + "banner.warn": "This account has used %s. If it goes over, nothing changes for a grace period.", |
| + "banner.over": "This account is over its plan: %s. Nothing changes until %s. To stay within it, buy a pack, move to a bigger plan, or clean up.", |
| + "cli.warn": "this account has used %s", |
| + "cli.over": "this account is over its plan: %s. nothing changes until %s. buy a pack, move to a bigger plan, or clean up", |
| + "email.subject": "[carlos] Account %s: plan usage", |
| + "email.intro": "Account %s is near or over what its plan includes:", |
| + "email.warn": "- %s.", |
| + "email.over": "- %s, over the limit. Nothing changes until %s.", |
| + "email.ways_out": "To stay within the plan, buy a pack, move to a bigger plan, or clean up.\n\nAccount settings:\n%s", |
| +} |
diff --git a/internal/console/plangracepass.go b/internal/console/plangracepass.go| new file mode 100644 |
| index 000000000..ff61f6115 |
| --- /dev/null |
| +++ b/internal/console/plangracepass.go |
| @@ -0,0 +1,217 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "log" |
| + "net/url" |
| + "strconv" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// planGracePassInterval is how often the grace pass measures. The figures |
| +// it reads move hourly (the economics pass) or daily (the storage sweep). |
| +const planGracePassInterval = time.Hour |
| + |
| +// planNoticeDeliveryTimeout bounds one owner email. |
| +const planNoticeDeliveryTimeout = 15 * time.Second |
| + |
| +// StartPlanGracePass measures every plan-governed account against its |
| +// effective limits, keeps each cap's grace clock and warns owners (plans |
| +// 4a, spec §6): now, then hourly. With no catalog it does nothing at all. |
| +func (s *Server) StartPlanGracePass(ctx context.Context) { |
| + if s.cfg.Releases == nil || s.cfg.PlanCatalog == nil { |
| + return |
| + } |
| + t := time.NewTicker(planGracePassInterval) |
| + defer t.Stop() |
| + for { |
| + s.planGracePass(ctx, time.Now()) |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-t.C: |
| + } |
| + } |
| +} |
| + |
| +// planGracePass is one pass at the given clock. One account's failure |
| +// never stops the others; a cap that cannot be measured keeps its row. |
| +func (s *Server) planGracePass(ctx context.Context, now time.Time) { |
| + if s.cfg.Releases == nil || s.cfg.PlanCatalog == nil { |
| + return |
| + } |
| + accts, err := s.store.Accounts() |
| + if err != nil { |
| + log.Printf("console: plan grace: accounts: %v", err) |
| + return |
| + } |
| + for i := range accts { |
| + if ctx.Err() != nil { |
| + return |
| + } |
| + if err := s.planGraceAccount(ctx, &accts[i], now); err != nil { |
| + log.Printf("console: plan grace %s: %v", accts[i].Sqid, err) |
| + } |
| + } |
| +} |
| + |
| +func (s *Server) planGraceAccount(ctx context.Context, acct *Account, now time.Time) error { |
| + l, err := s.EffectiveLimits(acct) |
| + if err != nil || l == nil { |
| + return err |
| + } |
| + prev, err := s.store.CapStates(acct.ID) |
| + if err != nil { |
| + return err |
| + } |
| + byCap := map[capID]*capState{} |
| + for i := range prev { |
| + byCap[prev[i].Cap] = &prev[i] |
| + } |
| + measures, errs := s.measureCaps(ctx, acct, l, now) |
| + var states []capState |
| + for _, c := range capOrder { |
| + m, measured := measures[c] |
| + switch { |
| + case measured: |
| + st := evaluateCap(byCap[c], c, m.Used, m.Limit, now) |
| + st.AccountID = acct.ID |
| + if err := s.store.PutCapState(st); err != nil { |
| + return err |
| + } |
| + states = append(states, st) |
| + case errs[c] != nil: |
| + log.Printf("console: plan grace %s: %s: %v (row kept)", acct.Sqid, c, errs[c]) |
| + if p := byCap[c]; p != nil { |
| + states = append(states, *p) |
| + } |
| + case byCap[c] != nil: |
| + if err := s.store.DeleteCapState(acct.ID, c); err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + return s.notifyPlanOwners(ctx, acct, states, now) |
| +} |
| + |
| +// noticeDue is whether st should go out in this pass's email: the first |
| +// 80% warning of the period, the first over, then a reminder a day. |
| +func noticeDue(st capState, now time.Time) bool { |
| + switch { |
| + case st.Level == levelWarn: |
| + return st.WarnedAt.IsZero() |
| + case st.Level.over(): |
| + return st.RemindedAt.IsZero() || st.RemindedAt.Before(st.FirstOver) || !now.Before(st.RemindedAt.Add(24*time.Hour)) |
| + } |
| + return false |
| +} |
| + |
| +// notifyPlanOwners sends one email per owner listing every cap that is |
| +// due. Marks are set, and notice recorded, only when at least one owner's |
| +// delivery was accepted; otherwise the next pass tries again. |
| +func (s *Server) notifyPlanOwners(ctx context.Context, acct *Account, states []capState, now time.Time) error { |
| + var due []capState |
| + for _, st := range states { |
| + if noticeDue(st, now) { |
| + due = append(due, st) |
| + } |
| + } |
| + if len(due) == 0 || (s.consoleMail == nil && s.sendFederated == nil) { |
| + return nil |
| + } |
| + members, err := s.store.Members(acct.ID) |
| + if err != nil { |
| + return err |
| + } |
| + subject, body := s.planNoticeEmail(acct, due) |
| + delivered := false |
| + for _, m := range members { |
| + if m.Role != RoleOwner { |
| + continue |
| + } |
| + dctx, cancel := context.WithTimeout(ctx, planNoticeDeliveryTimeout) |
| + _, err := s.deliver(dctx, m.Name, subject, body, planNoticeDeliveryTimeout*4/5) |
| + cancel() |
| + if err != nil { |
| + log.Printf("console: plan grace %s: notice to %s: %v", acct.Sqid, m.Name, err) |
| + continue |
| + } |
| + delivered = true |
| + } |
| + if !delivered { |
| + return nil |
| + } |
| + var noticed []capID |
| + for _, st := range due { |
| + if st.WarnedAt.IsZero() { |
| + st.WarnedAt = now |
| + } |
| + if st.Level.over() { |
| + st.RemindedAt = now |
| + noticed = append(noticed, st.Cap) |
| + } |
| + if err := s.store.PutCapState(st); err != nil { |
| + return err |
| + } |
| + } |
| + return s.store.RecordCapNotice(acct.ID, noticed, now) |
| +} |
| + |
| +func (s *Server) planNoticeEmail(acct *Account, due []capState) (string, string) { |
| + lines := []string{fmt.Sprintf(planNoticeCopy["email.intro"], acct.Sqid), ""} |
| + for _, n := range planNoticesOf(due) { |
| + lines = append(lines, planNoticeText(n, "email")) |
| + } |
| + settings := s.cfg.Origin + "/a/" + url.PathEscape(acct.Sqid) + "/settings" |
| + lines = append(lines, "", fmt.Sprintf(planNoticeCopy["email.ways_out"], settings)) |
| + return fmt.Sprintf(planNoticeCopy["email.subject"], acct.Sqid), strings.Join(lines, "\n") + "\n" |
| +} |
| + |
| +// planNotice is one cap worth telling someone about. |
| +type planNotice struct { |
| + Cap capID |
| + Level capLevel |
| + Used, Limit int64 |
| + GraceEnds time.Time |
| +} |
| + |
| +// planNoticesOf is the caps at warn or over, in capOrder. |
| +func planNoticesOf(states []capState) []planNotice { |
| + var out []planNotice |
| + for _, c := range capOrder { |
| + for _, st := range states { |
| + if st.Cap == c && (st.Level == levelWarn || st.Level.over()) { |
| + out = append(out, planNotice{Cap: st.Cap, Level: st.Level, Used: st.Used, Limit: st.Limit, GraceEnds: st.GraceEnds}) |
| + } |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// planNoticeText renders one notice for a surface: "banner", "cli" or |
| +// "email". |
| +func planNoticeText(n planNotice, surface string) string { |
| + use := usagePhrase(n) |
| + if n.Level.over() { |
| + return fmt.Sprintf(planNoticeCopy[surface+".over"], use, n.GraceEnds.UTC().Format("2 January 2006")) |
| + } |
| + return fmt.Sprintf(planNoticeCopy[surface+".warn"], use) |
| +} |
| + |
| +func usagePhrase(n planNotice) string { |
| + f := planNoticeCopy["usage."+string(n.Cap)] |
| + switch n.Cap { |
| + case capStorage, capBandwidth: |
| + return fmt.Sprintf(f, humanGB(n.Used), humanGB(n.Limit)) |
| + } |
| + return fmt.Sprintf(f, n.Used, n.Limit) |
| +} |
| + |
| +// humanGB is bytes as gigabytes (1e9) to one decimal place, without a |
| +// trailing ".0". |
| +func humanGB(b int64) string { |
| + s := strconv.FormatFloat(float64(b)/1e9, 'f', 1, 64) |
| + return strings.TrimSuffix(s, ".0") + " GB" |
| +} |
diff --git a/internal/console/plangracepass_test.go b/internal/console/plangracepass_test.go| new file mode 100644 |
| index 000000000..39c0f06d3 |
| --- /dev/null |
| +++ b/internal/console/plangracepass_test.go |
| @@ -0,0 +1,146 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// graceFixture turns plans on with the ops account at its running-things |
| +// cap (warn), owners reachable by a fake console mailer. |
| +func graceFixture(t *testing.T) (*consoleFixture, *Account, *fakeConsoleMail) { |
| + t.Helper() |
| + fx := newConsoleFixture(t) |
| + acct := atRunningCap(t, fx, 5) |
| + mailer := &fakeConsoleMail{ready: true} |
| + fx.srv.consoleMail = mailer |
| + fx.srv.sendFederated = nil |
| + return fx, acct, mailer |
| +} |
| + |
| +func capRow(t *testing.T, fx *consoleFixture, acct *Account, c capID) (capState, bool) { |
| + t.Helper() |
| + states, err := fx.st.CapStates(acct.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, s := range states { |
| + if s.Cap == c { |
| + return s, true |
| + } |
| + } |
| + return capState{}, false |
| +} |
| + |
| +func goOver(t *testing.T, fx *consoleFixture, acct *Account) { |
| + t.Helper() |
| + capsApp(t, fx, acct, "overflow") |
| +} |
| + |
| +func TestGracePassOffWithoutACatalog(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + mailer := &fakeConsoleMail{ready: true} |
| + fx.srv.consoleMail = mailer |
| + fx.srv.planGracePass(context.Background(), planNow) |
| + acct, _ := fx.st.AccountBySqid(fx.sqid) |
| + if states, _ := fx.st.CapStates(acct.ID); len(states) != 0 { |
| + t.Fatalf("rows with plans off: %v", states) |
| + } |
| + if len(mailer.sentCopy()) != 0 { |
| + t.Fatal("mail with plans off") |
| + } |
| +} |
| + |
| +func TestGracePassWarnsOnceAt80Percent(t *testing.T) { |
| + fx, acct, mailer := graceFixture(t) |
| + fx.srv.planGracePass(context.Background(), planNow) |
| + st, ok := capRow(t, fx, acct, capRunningThings) |
| + if !ok || st.Level != levelWarn || !st.WarnedAt.Equal(planNow.UTC().Truncate(time.Second)) { |
| + t.Fatalf("row = %+v, %v, want warn with WarnedAt", st, ok) |
| + } |
| + sent := mailer.sentCopy() |
| + if len(sent) != 1 || !strings.HasPrefix(sent[0], "paul@keymail.dev|") { |
| + t.Fatalf("sent = %v, want one email to the owner", sent) |
| + } |
| + fx.srv.planGracePass(context.Background(), planNow.Add(time.Hour)) |
| + if n := len(mailer.sentCopy()); n != 1 { |
| + t.Fatalf("second pass sent %d emails in all, want still 1", n) |
| + } |
| +} |
| + |
| +func TestGracePassOverStartsGraceAndRecordsNotice(t *testing.T) { |
| + fx, acct, mailer := graceFixture(t) |
| + goOver(t, fx, acct) |
| + fx.srv.planGracePass(context.Background(), planNow) |
| + st, _ := capRow(t, fx, acct, capRunningThings) |
| + if st.Level != levelOver || !st.GraceEnds.Equal(planNow.Add(7*24*time.Hour).UTC().Truncate(time.Second)) { |
| + t.Fatalf("row = %+v, want over with 7 days of grace", st) |
| + } |
| + if !st.NoticeAt.Equal(planNow.UTC().Truncate(time.Second)) { |
| + t.Fatalf("NoticeAt = %v, want the delivered email's time", st.NoticeAt) |
| + } |
| + if len(mailer.sentCopy()) != 1 { |
| + t.Fatalf("sent = %v", mailer.sentCopy()) |
| + } |
| +} |
| + |
| +func TestGracePassRemindsOncePerDay(t *testing.T) { |
| + fx, acct, mailer := graceFixture(t) |
| + goOver(t, fx, acct) |
| + ctx := context.Background() |
| + fx.srv.planGracePass(ctx, planNow) |
| + fx.srv.planGracePass(ctx, planNow.Add(time.Hour)) |
| + if n := len(mailer.sentCopy()); n != 1 { |
| + t.Fatalf("after an hour: %d emails, want 1", n) |
| + } |
| + fx.srv.planGracePass(ctx, planNow.Add(24*time.Hour)) |
| + if n := len(mailer.sentCopy()); n != 2 { |
| + t.Fatalf("after a day: %d emails, want 2", n) |
| + } |
| +} |
| + |
| +func TestGracePassWithoutMailRecordsNoNotice(t *testing.T) { |
| + fx, acct, mailer := graceFixture(t) |
| + mailer.err = errors.New("ses down") |
| + goOver(t, fx, acct) |
| + fx.srv.planGracePass(context.Background(), planNow) |
| + st, _ := capRow(t, fx, acct, capRunningThings) |
| + if !st.NoticeAt.IsZero() || !st.RemindedAt.IsZero() || !st.WarnedAt.IsZero() { |
| + t.Fatalf("row after failed delivery = %+v, want no notice and nothing marked sent", st) |
| + } |
| + if st.Level != levelOver || st.GraceEnds.IsZero() { |
| + t.Fatalf("grace clock did not start: %+v", st) |
| + } |
| +} |
| + |
| +func TestGracePassSkipsUnreadableMeasurements(t *testing.T) { |
| + fx, acct, _ := graceFixture(t) |
| + over := evaluateCap(nil, capStorage, 2<<30, 1<<30, planNow.Add(-48*time.Hour)) |
| + over.AccountID, over.NoticeAt = acct.ID, planNow.Add(-24*time.Hour) |
| + if err := fx.st.PutCapState(over); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.st.SetAccountPlan(acct.ID, "personal", nil, "operator", nil, "test", "ops@example.com", planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.srv.planGracePass(context.Background(), planNow) // no storage sweep exists: storage is unknown |
| + st, ok := capRow(t, fx, acct, capStorage) |
| + if !ok || st.Level != levelOver || !st.FirstOver.Equal(over.FirstOver.Truncate(time.Second)) || st.NoticeAt.IsZero() { |
| + t.Fatalf("storage row after an unreadable sweep = %+v, %v, want it unchanged", st, ok) |
| + } |
| +} |
| + |
| +func TestGracePassMembersGetNoEmail(t *testing.T) { |
| + fx, acct, mailer := graceFixture(t) |
| + if err := fx.st.AddMember(acct.ID, "kim@keymail.dev", RoleMember, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.srv.planGracePass(context.Background(), planNow) |
| + for _, s := range mailer.sentCopy() { |
| + if strings.HasPrefix(s, "kim@keymail.dev|") { |
| + t.Fatalf("a member was emailed: %v", s) |
| + } |
| + } |
| +} |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 8e4029792..f0a1b102e 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -300,6 +300,7 @@ worker StartGeoipJobs |
| worker StartHostReports |
| worker StartInfraPass |
| worker StartMailEventPush |
| +worker StartPlanGracePass |
| worker StartPlanLimitsPass |
| worker StartRelay |
| worker StartRunSweep |