plans 4c: box-side throttle plan
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+249
−0
docs/superpowers/plans/2026-10-25-plans-4c-box-throttle.md+249 −0
CI passed — run details
diff --git a/docs/superpowers/plans/2026-10-25-plans-4c-box-throttle.md b/docs/superpowers/plans/2026-10-25-plans-4c-box-throttle.md| new file mode 100644 |
| index 000000000..0fe840058 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-25-plans-4c-box-throttle.md |
| @@ -0,0 +1,249 @@ |
| +# Plans 4c: Box-Side Throttle for Bandwidth and Awake Hours Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** An account that runs through its monthly bandwidth or awake hours is slowed down for the rest of the month, not cut off. |
| +- Its instances are served at a reduced per-account request rate. |
| +- When the cause is awake hours, its open WebSockets are closed, new upgrades are refused, and each instance is put to sleep after 15 minutes awake. It wakes on its next request. |
| +- Everything lifts when the month rolls or the plan grows. |
| + |
| +**Architecture:** |
| +- **Console:** the grace pass decides a per-account throttle and stores it on `account_plans` (`throttle`, bumping `revision`). The existing publish pass carries it to the box in the limits record as `plans.Record.Throttle`. |
| +- **Box:** `plansPass` keeps it in the snapshot and feeds three new hooks, each beside its existing sibling: |
| + - `edge.SetPlanThrottleFor`: a per-account token bucket, plus closing and refusing upgrades; |
| + - `activator.SetMaxRunFor`: the continuous-awake ceiling for instances; |
| + - `edge.CloseAccountUpgrades`: called when an account becomes awake-throttled. |
| +- A throttle carries `Until`, the first instant of the next UTC month. A box drops it after that even if the console has stopped. |
| + |
| +**Tech Stack:** Go; `internal/console`, `internal/plans`, `internal/host`, `internal/edge`, `internal/activator`. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-10-20-plans-caps-packs-design.md`: |
| +- §5.2 "Awake hours": throttle, close WebSockets and refuse new upgrades, and the 15-minute continuous-awake ceiling, using `MaxRunSeconds` applied to instances; |
| +- §5.7 "Bandwidth": "throttle, do not refuse", "the rest of the month, up to 2x the cap", per-account throttle state in the limits record; |
| +- §6 (the notice rule); |
| +- table 4.2 (bandwidth hard ceiling "2x cap, then throttled"; awake hours have none). |
| + |
| +The plan builds on Plans 4a and 4b, merged, and on the edge rate limiter (#358), merged as c3a34e3. |
| + |
| +## Calls for Paul |
| + |
| +1. **When the throttle starts.** A monthly cap's grace is "the rest of the month, up to 2x". Its grace end is the month boundary, which is also when the cap resets, so the only point where a stage can act is 2x within the month (the same shape as email in Plan 4b). Proposed: |
| + - bandwidth throttles at 2x without waiting for notice, because table 4.2 makes 2x its hard ceiling, "then throttled"; |
| + - awake hours throttle at 2x only once an owner has had notice for 72 hours, because awake hours have no hard ceiling. |
| +2. **How slow.** A throttled account gets one shared bucket across all its instances. Proposed: **5 requests a second, burst 30**. That's enough to read a page and show a notice, too little to run a service. The values are catalog-free constants (`plans.ThrottleRule`), so a later plan can make them per-plan. |
| +3. **Independent of `CARLOS_RATE_LIMIT`.** The throttle is a plan stage, not abuse protection. It enforces even while the box's rate limiter is in `observe`. `CARLOS_PLAN_LIMITS=off` on a box turns it off, along with every other plan limit. |
| + |
| +## Global Constraints |
| + |
| +- **No catalog, no change:** |
| + - no `throttle` written, no `Record.Throttle`, no hook returns throttled; |
| + - the edge rate limiter, the activator and WebSockets behave exactly as today. |
| + |
| + A box with `CARLOS_PLAN_LIMITS=off`, or that has never read the record, applies no throttle (fail open, spec §7). |
| +- **Throttle triggers** (Call 1): |
| + - `bandwidthThrottleDue(st, now) = st.Period == capPeriod(capBandwidth, now) && st.Level == levelCeiling`; |
| + - `awakeThrottleDue(st, now) = st.Period == capPeriod(capAwakeHours, now) && st.Level == levelCeiling && !st.NoticeAt.IsZero() && !st.NoticeAt.After(now.Add(-72*time.Hour))`. |
| + |
| + An unmeasured cap keeps the current throttle. A plan with no limit for the cap clears it. |
| +- **Throttle rule:** `plans.ThrottleRule = ratelimit.Rule{Rate: 5, Burst: 30}` per account (Call 2). A throttled request gets the rate limiter's own 429 shape: `Retry-After`, `no-store`, the same body. It is counted through `noteRateLimited` with a distinct reason, `plan-throttle`. |
| +- **The awake ceiling:** 15 minutes, applied only to `instance` routes of awake-throttled accounts. It never touches sidecar workers' own `MaxRunSeconds`, and never an always-on route. |
| +- **`Until`:** the first instant of the next UTC month. The box ignores an expired throttle. |
| +- **New bucket fields** are `omitempty`, so an older box reads a newer record and ignores them. |
| +- **Copy:** the banner and CLI stage strings join `planNoticeCopy`, and Luna reviews them. |
| +- **Census:** |
| + - re-pin through `make census-card` and `make census-propose`; |
| + - write hand decision rows if new units appear; |
| + - Astra approves the card, and decisions go to Paul. |
| +- **New tests:** `internal/host` and `internal/activator` tests call `t.Parallel()` unless they touch package vars, env or the umask. `planLimits` is a package var, so host tests that set it stay serial. |
| +- **Tests:** touched packages only, with `-run`; CI runs the full suite. |
| + |
| +## Review Focus |
| + |
| +1. **The month roll lifts everything,** even with the console down: the box drops a throttle past `Until`. Pinned in Task 3 (`TestExpiredThrottleIsIgnored`). |
| +2. **Only the throttled account is slowed.** Another account's instances on the same box keep their own limits. Pinned in Task 4 (`TestThrottleIsPerAccount`). |
| +3. **A closed WebSocket is closed for good.** After an account becomes awake-throttled its open upgrades end and new ones are refused, while ordinary requests still pass at the throttled rate. Pinned in Task 4 (`TestAwakeThrottleClosesAndRefusesUpgrades`). |
| +4. **The awake ceiling puts an always-busy instance to sleep** even with requests in flight (`inflight > 0`), and the next request wakes it. Pinned in Task 5 (`TestMaxRunForStopsABusyInstance`). |
| +5. **Unknown is not over:** a pass that can't measure bandwidth leaves the throttle as it was. Pinned in Task 2 (`TestThrottleUnchangedWhenUnmeasured`). |
| + |
| +--- |
| + |
| +### Task 1: Throttle on the plan row and in the limits record |
| + |
| +**Files:** |
| +- Modify: `internal/plans/record.go:23` (`Record` gains `Throttle *Throttle`). |
| +- Create: `internal/plans/throttle.go` (`Throttle`, `ThrottleRule`). |
| +- Modify: `internal/console/store.go` (additive ALTER `account_plans ADD COLUMN throttle TEXT NOT NULL DEFAULT ''`). |
| +- Modify: `internal/console/accountplans.go`: `AccountPlanRow.Throttle`, `scanAccountPlan`, and a new `SetAccountThrottle`. |
| +- Modify: `internal/console/planlimits.go:78` (`publishAccountLimits` fills `rec.Throttle`). |
| +- Test: `internal/plans/record_test.go`, `internal/console/accountplans_test.go`, `internal/console/planlimits_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: |
| + ```go |
| + // plans |
| + type Throttle struct { |
| + Bandwidth bool `json:"bandwidth,omitempty"` |
| + Awake bool `json:"awake,omitempty"` |
| + Until time.Time `json:"until"` |
| + } |
| + func (t *Throttle) Active(now time.Time) bool // non-nil, (Bandwidth || Awake), now before Until |
| + var ThrottleRule = ratelimit.Rule{Rate: 5, Burst: 30} |
| + // Record gains: Throttle *Throttle `json:"throttle,omitempty"` |
| + // console |
| + func (s *Store) SetAccountThrottle(accountID int64, t *plans.Throttle, now time.Time) (changed bool, err error) // writes and bumps revision only when the stored JSON differs; nil clears; no row: (false, nil) |
| + ``` |
| +- [ ] **Step 1: Write the failing tests** |
| + ```go |
| + func TestThrottleActive(t *testing.T) // nil false; Bandwidth before Until true; at Until false; neither flag false |
| + func TestRecordRoundTripsThrottle(t *testing.T) // PutLimits/GetLimits keep Throttle; a record without it parses with nil |
| + func TestSetAccountThrottleBumpsRevisionOnChange(t *testing.T) // set: changed, revision+1; same again: unchanged, same revision; nil: changed |
| + func TestPublishCarriesThrottle(t *testing.T) // after SetAccountThrottle, planLimitsPass writes a record whose Throttle matches |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/plans/ ./internal/console/ -run 'ThrottleActive|RoundTripsThrottle|SetAccountThrottle|PublishCarriesThrottle'`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** |
| +- [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'PlanLimits|AccountPlan'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** `plans, console: per-account throttle on the plan row and the limits record (plans 4c)`. |
| + |
| +### Task 2: The grace pass decides the throttle |
| + |
| +**Files:** |
| +- Create: `internal/console/planthrottle.go`. |
| +- Modify: `internal/console/plangracepass.go`: |
| + - `planGraceAccount` calls `s.convergeThrottle`; |
| + - `planStage` names `bandwidth_throttled` and `awake_throttled`. |
| +- Modify: `internal/console/plancaps_copy.go` (keys `banner.bandwidth_throttled`, `cli.bandwidth_throttled`, `banner.awake_throttled`, `cli.awake_throttled`). |
| +- Test: `internal/console/planthrottle_test.go`, `plangrace_view_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: |
| + ```go |
| + func bandwidthThrottleDue(st capState, now time.Time) bool |
| + func awakeThrottleDue(st capState, now time.Time) bool |
| + func (s *Server) convergeThrottle(ctx context.Context, acct *Account, states map[capID]capState, measured map[capID]bool, offered map[capID]bool, now time.Time) error |
| + ``` |
| + `convergeThrottle` handles each of the two caps the same way: |
| + - **measured:** due or not, from the predicate; |
| + - **not offered:** false; |
| + - **unmeasured:** the stored value is kept. |
| + |
| + It builds `Throttle{Bandwidth, Awake, Until: graceEnd(capBandwidth, now)}`, or nil when neither flag is set, and calls `SetAccountThrottle`. On a change it audits `plan.throttled` or `plan.unthrottled` with the figures. |
| + |
| + Draft copy: |
| + - bandwidth: "This account is slowed down until the month ends: it has used %s." / cli: "this account is slowed down until the month ends: it has used %s". |
| + - awake: "This account's apps are slowed down and put to sleep after 15 minutes awake until the month ends: %s." / cli: lower-case form. |
| + |
| +- [ ] **Step 1: Write the failing tests** |
| + ```go |
| + func TestBandwidthThrottleDue(t *testing.T) // over: false; ceiling: true without notice; last month's ceiling row: false |
| + func TestAwakeThrottleDue(t *testing.T) // ceiling, no notice: false; notice 71h: false; 72h: true |
| + func TestThrottleSetAndCleared(t *testing.T) // bandwidth ceiling: row throttle Bandwidth, revision bumped, audit plan.throttled; back under: cleared, plan.unthrottled |
| + func TestThrottleUnchangedWhenUnmeasured(t *testing.T) |
| + func TestThrottleWithoutACatalogUnchanged(t *testing.T) |
| + func TestBannerSaysBandwidthThrottled(t *testing.T) |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'ThrottleDue|ThrottleSet|ThrottleUnchanged|ThrottleWithout|BannerSaysBandwidth'`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** |
| +- [ ] **Step 4: Run** again, plus `go test ./internal/console/ -run 'GracePass|Banner|CLIWarning'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** `console: throttle an account past its monthly bandwidth or awake hours (plans 4c)`. |
| + |
| +### Task 3: The box keeps the throttle |
| + |
| +**Files:** |
| +- Modify: `internal/host/plans_pass.go`: |
| + - the snapshot gains `throttle map[string]plans.Throttle`, filled from `rec.Throttle` and kept with the last good copy; |
| + - `planThrottleFor` and `planMaxRunFor` sit beside `planIdleFor`. |
| +- Test: `internal/host/plans_throttle_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: |
| + ```go |
| + func planThrottleFor(rt registry.Route) (plans.Throttle, bool) // the route's account throttle when Active(now); false when none, expired, plans off, or not an instance route |
| + func planMaxRunFor(rt registry.Route) time.Duration // 15m when the account's throttle has Awake and is active and rt.Kind == "instance"; else 0 |
| + ``` |
| +- [ ] **Step 1: Write the failing tests** (`plansWorld` and `putAccountLimits`, extended to write a throttle) |
| + ```go |
| + func TestPlansPassKeepsThrottle(t *testing.T) // record with Throttle{Bandwidth}: planThrottleFor(route of that account) true; other account false |
| + func TestExpiredThrottleIsIgnored(t *testing.T) // Until in the past: false |
| + func TestPlanMaxRunFor(t *testing.T) // awake-throttled instance route: 15m; bandwidth-only: 0; worker route: 0 |
| + func TestThrottleOffWithPlanLimitsOff(t *testing.T) // CARLOS_PLAN_LIMITS=off: false |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/host/ -run 'PlansPassKeepsThrottle|ExpiredThrottle|PlanMaxRunFor|ThrottleOffWith'`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** |
| +- [ ] **Step 4: Run** again, plus `go test ./internal/host/ -run 'PlansPass|PlanIdle|PlanRate'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** `host: keep each account's plan throttle from its limits record (plans 4c)`. |
| + |
| +### Task 4: Edge throttle and upgrades |
| + |
| +**Files:** |
| +- Modify: `internal/edge/ratelimit.go`: |
| + - add `SetPlanThrottleFor`; |
| + - add a per-account bucket checked in `rateAdmit`, before the mode switch. |
| +- Modify: `internal/edge/edge.go`: |
| + - the upgrade branch (~:1774) refuses a new upgrade for an awake-throttled account; |
| + - it registers each open upgrade's cancel under the route's account; |
| + - add `CloseAccountUpgrades`. |
| +- Modify: `internal/host/agent.go:946` (arm `e.SetPlanThrottleFor(planThrottleFor)` beside `SetRateCeilingFor`). After each `plansPass` that turns an account awake-throttled, call `e.CloseAccountUpgrades(sqid)`. |
| +- Test: `internal/edge/planthrottle_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: |
| + ```go |
| + func (e *Edge) SetPlanThrottleFor(f func(registry.Route) (plans.Throttle, bool)) |
| + func (e *Edge) CloseAccountUpgrades(account string) int // cancels every open upgraded connection of the account's routes; returns how many |
| + ``` |
| + The throttle bucket uses `e.rateLimiter.Admit` with: |
| + - `host = "plan:" + account`; |
| + - `eff = ratelimit.Effective{Rule: plans.ThrottleRule}`; |
| + - `client` = the zero prefix (one bucket per account); |
| + - `observe = false`. |
| + |
| + A refusal goes through `writeRateLimited`, and `noteRateLimited` records the reason `plan-throttle`. |
| + |
| +- [ ] **Step 1: Write the failing tests** (`newRateScene`, `rlRoute`, `countingUpstream`, and the raw 101 server from `TestRateWebSocketUpgradeReleasesOnceUpgraded`) |
| + ```go |
| + func TestThrottleRefusesPastTheRule(t *testing.T) // throttled account: 30 burst pass, the next is 429 with Retry-After, in observe mode too |
| + func TestThrottleIsPerAccount(t *testing.T) // a second account's route on the same edge is unaffected |
| + func TestAwakeThrottleClosesAndRefusesUpgrades(t *testing.T) // an open upgrade: CloseAccountUpgrades returns 1 and the client sees EOF; a new upgrade: 429; a plain GET: passes |
| + func TestNoThrottleHookUnchanged(t *testing.T) // hook unset: identical behaviour to before |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/edge/ -run 'Throttle|AwakeThrottle'`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** |
| +- [ ] **Step 4: Run** again, plus `go test ./internal/edge/ -run 'Rate|Upgrade|Gate'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** `edge: slow a plan-throttled account and close its upgrades (plans 4c)`. |
| + |
| +### Task 5: The continuous-awake ceiling for instances |
| + |
| +**Files:** |
| +- Modify: `internal/activator/activator.go`: |
| + - add field `maxRunFor` beside `idleFor` (~:1145), and `SetMaxRunFor` beside `SetIdleFor` (~:5485); |
| + - in `sweepOnce`, after the worker max-run branch (~:4726), stop a non-worker entry with `StopIdle` once `now.Sub(e.spawnedAt) >= maxRunFor(route)`, whatever `inflight` is. |
| +- Modify: `internal/host/agent.go:502` (`svc.SetMaxRunFor(planMaxRunFor)`). |
| +- Test: `internal/activator/activator_maxrunfor_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: `func (s *Service) SetMaxRunFor(f func(registry.Route) time.Duration)`. A return of 0 means no ceiling. |
| + |
| +- [ ] **Step 1: Write the failing tests** (`testActivator`, `wakeInstance`, `fakeClock`, as in `activator_idlefor_test.go`) |
| + ```go |
| + func TestMaxRunForStopsABusyInstance(t *testing.T) // 15m ceiling, a request held in flight: at 15m the instance stops (StopIdle); the next request wakes it |
| + func TestMaxRunForZeroUnchanged(t *testing.T) // hook returns 0: no stop past 15m while busy |
| + func TestMaxRunForLeavesWorkersAlone(t *testing.T) // a worker route keeps its own MaxRunSeconds rule |
| + ``` |
| +- [ ] **Step 2: Run** `go test ./internal/activator/ -run 'MaxRunFor'`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** |
| +- [ ] **Step 4: Run** again, plus `go test ./internal/activator/ -run 'IdleFor|MaxRun|Sweep'`. Expected: PASS. |
| +- [ ] **Step 5: Commit** `activator: a per-route continuous-awake ceiling for instances (plans 4c)`. |
| + |
| +### Task 6: Docs, Luna, census and gates |
| + |
| +- [ ] Run a Luna copy pass on the four stage strings. Apply its changes and show Paul only what it flags. |
| +- [ ] Extend `docs/site/plans.md` with what happens after bandwidth and awake hours reach twice their limit, and how it lifts. Mention that the throttle ignores `CARLOS_RATE_LIMIT`, and that `CARLOS_PLAN_LIMITS=off` turns it off on a box. |
| +- [ ] Census: |
| + - run `make census-card`, add hand decision rows if new units appear, then `make census-propose NAME=plans-4c-box-throttle CLAIMS=<file>`; |
| + - add record-write census entries if named; |
| + - Astra approves the card, and decisions go to Paul. |
| +- [ ] Merge main, push, wait for green CI, then Astra's whole-branch review. |
| + |
| +## Done when |
| + |
| +Every task's tests pass and Review Focus 1–5 are pinned. The census card is approved. CI is green after merging current main, and Astra's whole-branch review has no open Critical or Important finding. |