carlos / platform Public

console: plan cap state and grace rules (plans 4a)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 82a5b0f78f4e96c9407301cc1440317e87bce75c parent 113a2c4
5 files changed, +404 −1
  • internal/console/plangrace.go +125 −0
  • internal/console/plangrace_store.go +111 −0
  • internal/console/plangrace_test.go +162 −0
  • internal/console/store.go +5 −1
  • internal/console/store_gate.go +1 −0
diff --git a/internal/console/plangrace.go b/internal/console/plangrace.go
new file mode 100644
index 000000000..9be794f19
--- /dev/null
+++ b/internal/console/plangrace.go
@@ -0,0 +1,125 @@
+package console
+
+import "time"
+
+// Plans 4a (spec §6): one engine for warnings, grace and notice. A row per
+// account per cap says where the account stands; evaluateCap moves it on
+// from a fresh measurement, and afterGraceDue is the one question Plan 4b's
+// after-grace stages ask of it. Nothing here refuses or slows anything.
+
+// capID names a measured cap. The strings are stored and sent; keep them.
+type capID string
+
+const (
+ capRunningThings capID = "running_things" // count
+ capStorage capID = "storage" // bytes, per account
+ capEmail capID = "email" // sends, per UTC day
+ capBandwidth capID = "bandwidth" // bytes, per UTC month
+ capAwakeHours capID = "awake_hours" // hours, per UTC month
+)
+
+// capOrder is the order caps are listed in, everywhere.
+var capOrder = []capID{capRunningThings, capStorage, capEmail, capBandwidth, capAwakeHours}
+
+// capLevel is how close to its limit an account is on one cap.
+type capLevel string
+
+const (
+ levelOK capLevel = "ok" // under 80%
+ levelWarn capLevel = "warn" // 80% up to the limit
+ levelOver capLevel = "over" // past the limit: in grace
+ levelCeiling capLevel = "ceiling" // 2x the limit, for caps whose grace is "up to 2x"
+)
+
+func (l capLevel) over() bool { return l == levelOver || l == levelCeiling }
+
+// capState is one plan_cap_state row. A zero time is unset.
+type capState struct {
+ AccountID int64
+ Cap capID
+ Period string // "" counts and sizes, "2006-01-02" email, "2006-01" monthly
+ Level capLevel
+ Used, Limit int64
+ FirstOver time.Time // when this period's over began
+ GraceEnds time.Time
+ WarnedAt time.Time // the 80% warning went out this period
+ RemindedAt time.Time // the last over notice or reminder went out
+ NoticeAt time.Time // an owner received notice after the cap went over
+ UpdatedAt time.Time
+}
+
+// capPeriod is the window a cap's usage counts over: a daily cap rolls at
+// UTC midnight, a monthly one at the UTC month, counts and sizes never.
+func capPeriod(c capID, now time.Time) string {
+ switch c {
+ case capEmail:
+ return now.UTC().Format("2006-01-02")
+ case capBandwidth, capAwakeHours:
+ return now.UTC().Format("2006-01")
+ }
+ return ""
+}
+
+// hasCeiling: email, bandwidth and awake hours give grace "up to 2x"
+// (spec §6), so 2x is a level of its own. Counts and sizes do not.
+func hasCeiling(c capID) bool {
+ return c == capEmail || c == capBandwidth || c == capAwakeHours
+}
+
+// graceEnd is when grace started at first runs out (spec §6): 7 days for
+// counts and sizes, the rest of the UTC day for email, the rest of the
+// UTC month for bandwidth and awake hours.
+func graceEnd(c capID, first time.Time) time.Time {
+ u := first.UTC()
+ switch c {
+ case capEmail:
+ return time.Date(u.Year(), u.Month(), u.Day()+1, 0, 0, 0, 0, time.UTC)
+ case capBandwidth, capAwakeHours:
+ return time.Date(u.Year(), u.Month()+1, 1, 0, 0, 0, 0, time.UTC)
+ }
+ return u.Add(7 * 24 * time.Hour)
+}
+
+func levelOf(c capID, used, limit int64) capLevel {
+ switch {
+ case hasCeiling(c) && used >= 2*limit:
+ return levelCeiling
+ case used > limit:
+ return levelOver
+ case used*5 >= limit*4:
+ return levelWarn
+ }
+ return levelOK
+}
+
+// evaluateCap is the next row for cap c given a fresh measurement. A row
+// from an earlier period is not carried; within one, the over clock runs
+// from the first over and stops only when usage falls back under the
+// limit. WarnedAt and RemindedAt are the grace pass's to set.
+func evaluateCap(prev *capState, c capID, used, limit int64, now time.Time) capState {
+ next := capState{Cap: c, Period: capPeriod(c, now), Used: used, Limit: limit, UpdatedAt: now}
+ if prev != nil {
+ next.AccountID = prev.AccountID
+ if prev.Period == next.Period {
+ next.FirstOver, next.GraceEnds, next.NoticeAt = prev.FirstOver, prev.GraceEnds, prev.NoticeAt
+ next.WarnedAt, next.RemindedAt = prev.WarnedAt, prev.RemindedAt
+ }
+ }
+ next.Level = levelOf(c, used, limit)
+ if !next.Level.over() {
+ next.FirstOver, next.GraceEnds, next.NoticeAt = time.Time{}, time.Time{}, time.Time{}
+ return next
+ }
+ if next.FirstOver.IsZero() {
+ next.FirstOver = now
+ next.GraceEnds = graceEnd(c, now)
+ }
+ return next
+}
+
+// afterGraceDue is whether an after-grace stage may start (spec §6): over,
+// grace run out, and an owner received notice at least 3 days before now.
+func afterGraceDue(st capState, now time.Time) bool {
+ return st.Level.over() && !st.GraceEnds.IsZero() && !now.Before(st.GraceEnds) &&
+ !st.NoticeAt.IsZero() && !st.NoticeAt.After(now.Add(-72*time.Hour))
+}
diff --git a/internal/console/plangrace_store.go b/internal/console/plangrace_store.go
new file mode 100644
index 000000000..46f4329aa
--- /dev/null
+++ b/internal/console/plangrace_store.go
@@ -0,0 +1,111 @@
+package console
+
+import (
+ "strings"
+ "time"
+)
+
+// Plans 4a's own table, kept here so the feature is one file to read.
+func (s *Store) migratePlanGrace() error {
+ _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS plan_cap_state (
+ account_id INTEGER NOT NULL,
+ cap TEXT NOT NULL,
+ period TEXT NOT NULL DEFAULT '',
+ level TEXT NOT NULL,
+ used INTEGER NOT NULL,
+ cap_limit INTEGER NOT NULL,
+ first_over INTEGER NOT NULL DEFAULT 0,
+ grace_ends INTEGER NOT NULL DEFAULT 0,
+ warned_at INTEGER NOT NULL DEFAULT 0,
+ reminded_at INTEGER NOT NULL DEFAULT 0,
+ notice_at INTEGER NOT NULL DEFAULT 0,
+ updated_at INTEGER NOT NULL,
+ PRIMARY KEY (account_id, cap)
+);`)
+ return err
+}
+
+func unixOrZero(t time.Time) int64 {
+ if t.IsZero() {
+ return 0
+ }
+ return t.Unix()
+}
+
+func timeOrZero(sec int64) time.Time {
+ if sec == 0 {
+ return time.Time{}
+ }
+ return time.Unix(sec, 0).UTC()
+}
+
+// CapStates is every cap row for the account, in capOrder.
+func (s *Store) CapStates(accountID int64) ([]capState, error) {
+ rows, err := s.db.Query(`SELECT cap, period, level, used, cap_limit, first_over, grace_ends,
+ warned_at, reminded_at, notice_at, updated_at FROM plan_cap_state WHERE account_id = ?`, accountID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ byCap := map[capID]capState{}
+ for rows.Next() {
+ st := capState{AccountID: accountID}
+ var first, grace, warned, reminded, notice, updated int64
+ if err := rows.Scan(&st.Cap, &st.Period, &st.Level, &st.Used, &st.Limit, &first, &grace,
+ &warned, &reminded, &notice, &updated); err != nil {
+ return nil, err
+ }
+ st.FirstOver, st.GraceEnds, st.WarnedAt = timeOrZero(first), timeOrZero(grace), timeOrZero(warned)
+ st.RemindedAt, st.NoticeAt, st.UpdatedAt = timeOrZero(reminded), timeOrZero(notice), timeOrZero(updated)
+ byCap[st.Cap] = st
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ var out []capState
+ for _, c := range capOrder {
+ if st, ok := byCap[c]; ok {
+ out = append(out, st)
+ }
+ }
+ return out, nil
+}
+
+// PutCapState writes the row for (s.AccountID, s.Cap), replacing any.
+func (s *Store) PutCapState(st capState) error {
+ _, err := s.db.Exec(`INSERT INTO plan_cap_state (account_id, cap, period, level, used, cap_limit,
+ first_over, grace_ends, warned_at, reminded_at, notice_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(account_id, cap) DO UPDATE SET period = excluded.period, level = excluded.level,
+ used = excluded.used, cap_limit = excluded.cap_limit, first_over = excluded.first_over,
+ grace_ends = excluded.grace_ends, warned_at = excluded.warned_at, reminded_at = excluded.reminded_at,
+ notice_at = excluded.notice_at, updated_at = excluded.updated_at`,
+ st.AccountID, string(st.Cap), st.Period, string(st.Level), st.Used, st.Limit,
+ unixOrZero(st.FirstOver), unixOrZero(st.GraceEnds), unixOrZero(st.WarnedAt),
+ unixOrZero(st.RemindedAt), unixOrZero(st.NoticeAt), unixOrZero(st.UpdatedAt))
+ return err
+}
+
+// DeleteCapState drops the account's row for a cap it no longer has.
+func (s *Store) DeleteCapState(accountID int64, c capID) error {
+ _, err := s.db.Exec(`DELETE FROM plan_cap_state WHERE account_id = ? AND cap = ?`, accountID, string(c))
+ return err
+}
+
+// RecordCapNotice records that an owner received notice of caps at `at`.
+// Only notice after a cap went over counts (spec §6), and the first such
+// notice is the one kept.
+func (s *Store) RecordCapNotice(accountID int64, caps []capID, at time.Time) error {
+ if len(caps) == 0 {
+ return nil
+ }
+ args := []any{at.Unix(), accountID}
+ marks := make([]string, len(caps))
+ for i, c := range caps {
+ marks[i] = "?"
+ args = append(args, string(c))
+ }
+ _, err := s.db.Exec(`UPDATE plan_cap_state SET notice_at = ? WHERE account_id = ?
+ AND cap IN (`+strings.Join(marks, ",")+`) AND level IN ('over', 'ceiling') AND notice_at = 0`, args...)
+ return err
+}
diff --git a/internal/console/plangrace_test.go b/internal/console/plangrace_test.go
new file mode 100644
index 000000000..af4f36074
--- /dev/null
+++ b/internal/console/plangrace_test.go
@@ -0,0 +1,162 @@
+package console
+
+import (
+ "testing"
+ "time"
+)
+
+func TestCapLevels(t *testing.T) {
+ for _, c := range []struct {
+ cap capID
+ used int64
+ want capLevel
+ }{
+ {capRunningThings, 79, levelOK}, {capRunningThings, 80, levelWarn}, {capRunningThings, 100, levelWarn},
+ {capRunningThings, 101, levelOver}, {capEmail, 200, levelCeiling}, {capStorage, 200, levelOver},
+ {capBandwidth, 250, levelCeiling}, {capAwakeHours, 199, levelOver},
+ } {
+ if got := evaluateCap(nil, c.cap, c.used, 100, planNow).Level; got != c.want {
+ t.Errorf("%s used %d of 100 = %s, want %s", c.cap, c.used, got, c.want)
+ }
+ }
+}
+
+func TestEvaluateCapGraceEnds(t *testing.T) {
+ now := planNow.UTC()
+ day := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, time.UTC)
+ month := time.Date(now.Year(), now.Month()+1, 1, 0, 0, 0, 0, time.UTC)
+ for _, c := range []struct {
+ cap capID
+ want time.Time
+ }{
+ {capRunningThings, now.Add(7 * 24 * time.Hour)}, {capStorage, now.Add(7 * 24 * time.Hour)},
+ {capEmail, day}, {capBandwidth, month}, {capAwakeHours, month},
+ } {
+ st := evaluateCap(nil, c.cap, 150, 100, now)
+ if !st.GraceEnds.Equal(c.want) || !st.FirstOver.Equal(now) {
+ t.Errorf("%s: FirstOver %v GraceEnds %v, want %v and %v", c.cap, st.FirstOver, st.GraceEnds, now, c.want)
+ }
+ }
+}
+
+func TestEvaluateCapKeepsFirstOverWhileOver(t *testing.T) {
+ first := evaluateCap(nil, capRunningThings, 4, 3, planNow)
+ later := evaluateCap(&first, capRunningThings, 5, 3, planNow.Add(3*24*time.Hour))
+ if !later.FirstOver.Equal(first.FirstOver) || !later.GraceEnds.Equal(first.GraceEnds) {
+ t.Fatalf("still over: FirstOver %v GraceEnds %v, want %v %v", later.FirstOver, later.GraceEnds, first.FirstOver, first.GraceEnds)
+ }
+}
+
+func TestEvaluateCapUnderClearsClocks(t *testing.T) {
+ over := evaluateCap(nil, capStorage, 150, 100, planNow)
+ over.NoticeAt = planNow
+ under := evaluateCap(&over, capStorage, 90, 100, planNow.Add(time.Hour))
+ if under.Level != levelWarn || !under.FirstOver.IsZero() || !under.GraceEnds.IsZero() || !under.NoticeAt.IsZero() {
+ t.Fatalf("back under: %+v, want warn with clocks cleared", under)
+ }
+}
+
+func TestEvaluateCapNewPeriodClears(t *testing.T) {
+ now := planNow.UTC()
+ email := evaluateCap(nil, capEmail, 150, 100, now.Add(-24*time.Hour))
+ email.WarnedAt, email.NoticeAt = now.Add(-24*time.Hour), now.Add(-24*time.Hour)
+ if got := evaluateCap(&email, capEmail, 10, 100, now); got.Level != levelOK || !got.WarnedAt.IsZero() || !got.NoticeAt.IsZero() {
+ t.Errorf("email on a new day = %+v, want a fresh row", got)
+ }
+ bw := evaluateCap(nil, capBandwidth, 150, 100, now.AddDate(0, -1, 0))
+ bw.NoticeAt = bw.FirstOver
+ if got := evaluateCap(&bw, capBandwidth, 150, 100, now); !got.NoticeAt.IsZero() || !got.FirstOver.Equal(now) {
+ t.Errorf("bandwidth in a new month = %+v, want clocks from now", got)
+ }
+ rt := evaluateCap(nil, capRunningThings, 4, 3, now.AddDate(0, -1, 0))
+ if got := evaluateCap(&rt, capRunningThings, 4, 3, now); !got.FirstOver.Equal(rt.FirstOver) {
+ t.Errorf("running things a month on: FirstOver %v, want %v (counts never roll)", got.FirstOver, rt.FirstOver)
+ }
+}
+
+func TestEvaluateCapIsStable(t *testing.T) {
+ first := evaluateCap(nil, capEmail, 150, 100, planNow)
+ first.NoticeAt, first.WarnedAt, first.RemindedAt = planNow, planNow, planNow
+ again := evaluateCap(&first, capEmail, 150, 100, planNow.Add(time.Minute))
+ if !again.FirstOver.Equal(first.FirstOver) || !again.GraceEnds.Equal(first.GraceEnds) || !again.NoticeAt.Equal(first.NoticeAt) ||
+ !again.WarnedAt.Equal(first.WarnedAt) || !again.RemindedAt.Equal(first.RemindedAt) {
+ t.Fatalf("re-evaluated = %+v, want the clocks of %+v", again, first)
+ }
+}
+
+func TestAfterGraceDue(t *testing.T) {
+ st := evaluateCap(nil, capStorage, 150, 100, planNow)
+ ended := st.GraceEnds
+ if afterGraceDue(st, ended.Add(-time.Second)) {
+ t.Error("due before grace ended")
+ }
+ if afterGraceDue(st, ended) {
+ t.Error("due with no notice")
+ }
+ st.NoticeAt = ended.Add(-71 * time.Hour)
+ if afterGraceDue(st, ended) {
+ t.Error("due with notice 71h old")
+ }
+ st.NoticeAt = ended.Add(-72 * time.Hour)
+ if !afterGraceDue(st, ended) {
+ t.Error("not due with grace ended and notice 72h old")
+ }
+}
+
+func TestCapStateRoundTrip(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct, _ := fx.st.AccountBySqid(fx.sqid)
+ st := evaluateCap(nil, capBandwidth, 150, 100, planNow)
+ st.AccountID, st.WarnedAt = acct.ID, planNow
+ if err := fx.st.PutCapState(st); err != nil {
+ t.Fatal(err)
+ }
+ got, err := fx.st.CapStates(acct.ID)
+ if err != nil || len(got) != 1 {
+ t.Fatalf("CapStates = %v, %v", got, err)
+ }
+ g := got[0]
+ if g.Cap != capBandwidth || g.Level != levelOver || g.Used != 150 || g.Limit != 100 || g.Period != st.Period ||
+ !g.FirstOver.Equal(st.FirstOver.Truncate(time.Second)) || !g.GraceEnds.Equal(st.GraceEnds) ||
+ !g.WarnedAt.Equal(planNow) || !g.NoticeAt.IsZero() {
+ t.Fatalf("round trip = %+v, want %+v", g, st)
+ }
+ if err := fx.st.DeleteCapState(acct.ID, capBandwidth); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := fx.st.CapStates(acct.ID); len(got) != 0 {
+ t.Fatalf("after delete = %v", got)
+ }
+}
+
+func TestRecordCapNoticeOnlyWhenOver(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct, _ := fx.st.AccountBySqid(fx.sqid)
+ warn := evaluateCap(nil, capEmail, 85, 100, planNow)
+ over := evaluateCap(nil, capStorage, 150, 100, planNow)
+ warn.AccountID, over.AccountID = acct.ID, acct.ID
+ for _, s := range []capState{warn, over} {
+ if err := fx.st.PutCapState(s); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := fx.st.RecordCapNotice(acct.ID, []capID{capEmail, capStorage}, planNow); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.RecordCapNotice(acct.ID, []capID{capStorage}, planNow.Add(time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ got, _ := fx.st.CapStates(acct.ID)
+ for _, g := range got {
+ switch g.Cap {
+ case capEmail:
+ if !g.NoticeAt.IsZero() {
+ t.Errorf("warn row got notice %v", g.NoticeAt)
+ }
+ case capStorage:
+ if !g.NoticeAt.Equal(planNow) {
+ t.Errorf("over row notice = %v, want the first, %v", g.NoticeAt, planNow)
+ }
+ }
+ }
+}
diff --git a/internal/console/store.go b/internal/console/store.go
index 2f83cc562..17a8619b5 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -545,7 +545,11 @@ func (s *Store) migrate() error {
return err
}
// Door keys' own tables (doorkeys_store.go), for the same reason.
- return s.migrateDoorKeys()
+ if err := s.migrateDoorKeys(); err != nil {
+ return err
+ }
+ // Plans 4a's cap state (plangrace_store.go), for the same reason.
+ return s.migratePlanGrace()
}
// mailCountsBackfillVersion is the user_version this migration stamps. The
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go
index 679c3a742..5e1311baa 100644
--- a/internal/console/store_gate.go
+++ b/internal/console/store_gate.go
@@ -209,6 +209,7 @@ var claimSQLTables = map[string]claimSQLTable{
"memberships": {NonApp: "account membership, keyed by account and address; names no app"},
"invites": {NonApp: "account invites, keyed by account and address; names no app"},
"account_plans": {NonApp: "an account's plan and packs, keyed by account; names no app"},
+ "plan_cap_state": {NonApp: "an account's plan cap warnings and grace clocks, keyed by account; names no app"},
"alert_seen": {NonApp: "operator alert memory, keyed by box, rule and address"},
"claim_loss_pages": {NonApp: "claim recovery page attempts per loss record and condition, and scan progress; no app state or lifecycle authority"},
"move_pages": {NonApp: "the move pass's last page attempt per finding (rule names the host and the move); no app column"},