Plans 4c: box-side throttle. Past twice the month's bandwidth (no notice wait) or awake hours (72 h notice), an account's instances share one 5 req/s bucket until the month ends; awake-throttled accounts also have open WebSockets closed, new upgrades refused and a 15-minute continuous-awake ceiling; carried in the limits record with an Until; dormant without CARLOS_PLAN_CATALOG
Squashed from plans-4c-box-throttle into main.
34 files changed,
+1,694
−9
docs/site/plans.md+7 −2docs/superpowers/notes/census-proposal-plans-4c-box-throttle.md+51 −0docs/superpowers/notes/plans-4c-ledger.md+20 −0docs/superpowers/plans/2026-10-25-plans-4c-box-throttle.md+261 −0docs/superpowers/specs/CODEX-FINDINGS-PLANS-4C-CODE.md+55 −0docs/superpowers/specs/CODEX-REVIEW-BRIEF-PLANS-4C-CODE.md+44 −0docs/superpowers/specs/LUNA-COPY-BRIEF-PLANS-4C.md+32 −0docs/superpowers/specs/LUNA-COPY-RESULT-PLANS-4C.md+10 −0internal/activator/activator.go+27 −0internal/activator/activator_maxrunfor_test.go+72 −0internal/console/accountplans.go+41 −4internal/console/plancaps_copy.go+6 −0internal/console/plangrace_view_test.go+15 −0internal/console/plangracepass.go+16 −0internal/console/planlimits.go+1 −0internal/console/planlimits_test.go+65 −0internal/console/planthrottle.go+68 −0internal/console/planthrottle_test.go+118 −0internal/console/store.go+2 −0internal/edge/edge.go+24 −1internal/edge/planthrottle.go+138 −0internal/edge/planthrottle_test.go+251 −0internal/edge/usagemeter.go+11 −0internal/host/agent.go+12 −0internal/host/plans_pass.go+76 −1internal/host/plans_throttle_test.go+131 −0internal/plans/record.go+3 −0internal/plans/throttle.go+28 −0internal/plans/throttle_test.go+46 −0internal/provision/testdata/plan14-root-reads-chain.tsv+2 −0internal/provision/testdata/plan14-root-reads-plans-4c-box-throttle.tsv+20 −0internal/provision/testdata/plan14-root-reads-plans-4c-units.tsv+21 −0internal/usage/edge.go+6 −1internal/usage/edge_test.go+14 −0
CI passed — run details
diff --git a/docs/site/plans.md b/docs/site/plans.md| index b52239fa3..1f2e53de2 100644 |
| --- a/docs/site/plans.md |
| +++ b/docs/site/plans.md |
| @@ -84,6 +84,11 @@ After grace, only the capped action is refused, and each refusal lifts by itself |
| - **Email.** When an account has sent twice its daily limit, every sender of every app is paused until midnight UTC. This does not wait for notice, because sending reputation is shared by every tenant. The catalog's email ceiling caps it. |
| - **Storage.** New uploads to the account's stores are refused once grace has ended and an owner has had notice for 3 days, or straight away at twice the limit. Downloads, listing and deletes keep working, so the account can clean up. Uploads come back once usage is under the limit or the limit is raised. |
| -The account banner and the CLI warning line say which stage is in force. Bandwidth and awake hours only warn for now. |
| +- **Bandwidth.** At twice the month's limit, the account's apps are served more slowly until the month ends or the plan grows: one shared allowance of 5 requests a second, with bursts up to 30, across all its instances. This does not wait for notice, because twice the limit is bandwidth's hard ceiling. |
| +- **Awake hours.** At twice the month's limit, once an owner has had notice for 3 days, the apps are slowed the same way. Open live connections (WebSockets) are closed, new ones are refused, and each instance is put to sleep after 15 minutes awake. It wakes on its next request. |
| -The console also records when an owner actually received notice: an email that was accepted for delivery, an owner viewing an account page with the banner, or an owner's CLI printing the warning. Apart from the two ceilings above (email at twice its limit, storage at twice its limit), whatever acts after grace starts only once grace has ended and an owner received notice at least 3 days earlier. So an account nobody has heard from is never cut off for anything short of a ceiling. |
| +The slowdown is a plan stage, not abuse protection, so it applies whatever `CARLOS_RATE_LIMIT` says. `CARLOS_PLAN_LIMITS=off` on a box turns it off with every other plan limit. Each box drops a throttle at the start of the next month even if it can't reach the console. |
| + |
| +The account banner and the CLI warning line say which stage is in force. |
| + |
| +The console also records when an owner actually received notice: an email that was accepted for delivery, an owner viewing an account page with the banner, or an owner's CLI printing the warning. Apart from the ceilings above (email, storage and bandwidth at twice their limits), whatever acts after grace starts only once grace has ended and an owner received notice at least 3 days earlier. So an account nobody has heard from is never cut off for anything short of a ceiling. |
diff --git a/docs/superpowers/notes/census-proposal-plans-4c-box-throttle.md b/docs/superpowers/notes/census-proposal-plans-4c-box-throttle.md| new file mode 100644 |
| index 000000000..6c06a0b9b |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-plans-4c-box-throttle.md |
| @@ -0,0 +1,51 @@ |
| +# Census approval: plans-4c-box-throttle |
| + |
| +Ruling `census-ruling-plans-4c-box-throttle`. Every change below keeps the disposition it already has, so it needs an approval, not a decision. |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/activator/activator.go` `type Service` | body | unchanged (0) | gains the maxRunFor hook field beside idleFor (plans 4c). No read added. | |
| +| `internal/console/accountplans.go` `Store.SetAccountPlan` | body | unchanged (1) | the upsert also clears the account's throttle (plans 4c, Astra finding 3), so a plan change publishes without it. The same statement on the same table; no read added. | |
| +| `internal/console/store.go` `Store.migrate` | body | unchanged (2) | adds the additive account_plans.throttle column (plans 4c). No read added. | |
| +| `internal/edge/edge.go` `Edge.ServeHTTP` | body | unchanged (22) | calls planThrottleAdmit before the response cache, and on an upgrade trackUpgrade then planUpgradeAdmit (plans 4c, Astra findings 1 and 2); the new reads live in those units (plans-4c-units decision). The same read sites here. | |
| +| `internal/host/agent.go` `runAgent` | body | unchanged (5) | arms svc.SetMaxRunFor(planMaxRunFor) beside SetIdleFor, and e.SetPlanThrottleFor(planThrottleFor), e.SetPlanGovernedFor(planGoverned) and the planAwakeThrottled close hook beside SetRateCeilingFor (plans 4c). No read added. | |
| +| `internal/host/plans_pass.go` `plansPass` | body | unchanged (3) | keeps each account's published throttle from its limits record in the cache beside its limits, and tells planAwakeThrottled when an account first becomes awake-throttled (plans 4c). The same bucket objects; no read added. | |
| +| `internal/activator/activator.go` `Service.sweepOnce` | sites | +whole:Route | after the worker max_run branch, stops a non-worker entry past the plans continuous-awake ceiling (maxRunFor, passed the row), busy or not, never mid-command (plans 4c). One more whole-row read: the row handed to the hook, as idleFor already is. This bypasses the inflight and held-for-tick protections the idle stop keeps, on purpose: escalated by Astra and ACCEPTED by Paul (census owner), 2026-10-25. | |
| + |
| +Envelopes re-pinned: `internal/activator`, `internal/console`, `internal/edge`, `internal/host`, `internal/plans`, `internal/usage`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Escalate if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. An escalation goes to the census owner as a decision. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/activator/activator.go` `type Service`: authority, task B,C,D,F,J4. Basis: rev3=PROPOSED-seed; existing activator lifecycle and due-wake state plus owned seed exclusion and incarnation-keyed diagnostics; normal refusal and preparation ordering remain authoritative; PROPOSED-plans-2-box-limits adds the idleFor hook field, which only narrows idle windows |
| +- `internal/console/accountplans.go` `Store.SetAccountPlan`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=PROPOSED-design-plans-and-caps;basis=root-input; console SQL on its own account_plans table, as its store siblings (J4). |
| +- `internal/console/store.go` `Store.migrate`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-email-signin;identity=the console (cmd/console serve under console.service, user carlos-console);basis=adds the sessions.method column (default keymail, the backfill) and calls migrateEmailSignin; SQLite DDL on CONSOLE_DB; the existing site moves;rev3=census-ruling-plans-4-notices-grace;basis=calls migratePlanGrace last, which creates the console's own plan_cap_state table (plans 4a). No read added here; the new store units are the plans-4a-store decision. |
| +- `internal/edge/edge.go` `Edge.ServeHTTP`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-seeded-instances;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body with the import gate checked after the door's scope and a gated row left out of the response cache; serving only;rev3=census-ruling-edge-request-records;basis=one more call in the observer defer, observeRecords(up.route, ...), passing on the route the defer already holds; no new kind of read;rev3=census-ruling-design-edge-rate-limit-358;basis=calls rateAdmit twice, and an admitted request holds a slot on both paths: on the upgrade path before the activator or proxy (the handshake holds its slot through slotWriter, given back at the first final answer or at the reverse proxy's hijack on a 101, so an open WebSocket is not counted; released by a defer), and on the ordinary path after the response-cache check and before the activator and proxy (an admitted request holds a slot through slotWriter, released by a defer); a refusal is a 429 written there and returns; the upgrade path's comment now names slotWriter as its one wrapper; one comment on the door mark reworded; read sites unchanged (22: main's 21 plus edge-request-records' observeRecords pass of the route), offsets moved; no read added |
| +- `internal/host/agent.go` `runAgent`: authority, task B,C,D,F. Basis: rev3=census-ruling-seeded-instances;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body with wireSeedPlacement called in the activator start's Configure step, before armMovesPass, and the startup sweep's result stored for the import rollback in Recover; read sites unchanged, offsets moved; main's B,C,D,F authority retained PROPOSED E46: captured claim selection and root journal mutation; root RPC outside service host exclusion; SQL/route data never grants root authority. Executing identity: service controller; root for inventory/retirement callbacks.;rev3=PROPOSED-325;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=passes the agent's log sink to armRunsPass; reads unchanged;rev3=census-ruling-db-region-forward-1;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=arms the db-reads loop (armDBReads) beside armRunsPass in the activator start's Configure step; reads unchanged, offsets moved; main's authority retained;rev3=PROPOSED-s3-change-index;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=arms the change index (armChangeIndex) and starts the record view's backstop loop before the loops that read through it, and hands the edge the watch loader (edge.WithChangeWatch); read sites unchanged at the same offsets;rev3=census-ruling-edge-request-records;basis=builds the edge request recorder against the existing log sink and data dir (newRequestRecorder, passed os.Getenv and time.Now) and starts reqrecLoop on a minute ticker; no read added;rev3=census-ruling-design-edge-rate-limit-358;basis=arms the edge's plan rate-ceiling hook, e.SetRateCeilingFor(planRateCeilingFor), right after EnableUsage; read sites unchanged (5), offsets moved; no read added;rev3=census-ruling-edge-asset-cache-1;basis=starts edgesFileLoop with the activator's serving build (servingBuildOf(svc): ServingGen's build on a box with generations, nothing otherwise); read sites unchanged (5), none added |
| +- `internal/host/plans_pass.go` `plansPass`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=PROPOSED-plans-2-box-limits;basis=root-route; the agent's plans pass, serialised by its own mutex, reads its own routes' accounts and two bucket objects (the plans marker, each account's limits record) into a cache; planIdleFor only narrows the activator's idle window. No root decision. |
| +- `internal/activator/activator.go` `Service.sweepOnce`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=PROPOSED-seed;basis=census-ruling-FS-R6; registry remains legacy; PROPOSED-plans-2-box-limits: the sweep also narrows an entry's idle window to its account's plan idle through the SetIdleFor hook (never lengthens it; always-on workers and held probe entries are untouched; the hibernate, inflight and held-for-tick guards are unchanged). |
| + |
| +Seal: `f6c05461d95d00fb468c5f580487de16370049b91963539546026cadadaa1c9d` → `c71b2974cd929122afc730f22cb53c63f3fdefdb4b26f7ca60db76fface906de`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-plans-4c-box-throttle.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
| +## Decision (hand-written, census-ruling-plans-4c-units) |
| + |
| +The plan throttle adds ten new units. Each is a new unit, so each is a decision. They have their own overlay, `internal/provision/testdata/plan14-root-reads-plans-4c-units.tsv`, chained just before this one (seal → `f6c05461…`). Each is classed `legacy`/`accepted-legacy`, the same way as its sibling: |
| + |
| +| unit | sibling | what it does | |
| +|---|---|---| |
| +| `internal/console/accountplans.go` `Store.SetAccountThrottle` | `Store.SetAccountPlan` (J4) | stores the account's throttle on its own `account_plans` row and bumps the revision | |
| +| `internal/edge/planthrottle.go` `Edge.planThrottleOf` | `Edge.rateAdmit` | asks the throttle hook about an instance row; door, hop and tunnel callers are exempt | |
| +| `Edge.planThrottleAdmit` | `Edge.rateAdmit` | spends a token of the account's in-memory bucket; returns the rate limit's 429 | |
| +| `Edge.planUpgradeAdmit` | `Edge.rateAdmit` | refuses a new upgrade for an awake-throttled account | |
| +| `Edge.trackUpgrade` | `Edge.rateAdmit` | registers an upgrade under its account so it can be closed | |
| +| `internal/host/plans_pass.go` `planThrottleFor` | `planRateCeilingFor` | returns the account's published throttle while it is in force | |
| +| `planMaxRunFor` | `planIdleFor` | 15 minutes for an awake-throttled instance, else 0 | |
| +| `Edge.notePlanThrottled` | `Edge.noteRateLimited` | counts and logs a plan-throttle refusal (Astra finding 5) | |
| +| `internal/edge/usagemeter.go` `UsageMeter.RecordPlanThrottled` | `UsageMeter.RecordRateLimited` | adds to the row's in-memory PlanThrottled counter | |
| +| `planGoverned` | `planIdleFor` | whether the account has a limits record, so its upgrades are tracked only then (Astra finding 4) | |
| + |
| +Astra also escalated `Service.sweepOnce`'s changed basis to the census owner. The continuous-awake ceiling stops an instance even with requests in flight or a tick due, which is the behaviour the spec asks for. |
| + |
| +Every one of them only slows, shortens or closes what the account itself runs. None reads a path or value a tenant can name, and none grants anything. |
diff --git a/docs/superpowers/notes/plans-4c-ledger.md b/docs/superpowers/notes/plans-4c-ledger.md| new file mode 100644 |
| index 000000000..bba87d1b6 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/plans-4c-ledger.md |
| @@ -0,0 +1,20 @@ |
| +# SDD ledger — plan: docs/superpowers/plans/2026-10-25-plans-4c-box-throttle.md |
| +Pre-flight: T1 produces plans.Throttle/ThrottleRule/SetAccountThrottle, T2-T4 consume (match); T3 produces planThrottleFor/planMaxRunFor, T4/T5 consume (match); T5 produces SetMaxRunFor, wired in agent.go by T5. No conflicts. |
| +Task 1: complete (commits a523cb6..67a3a8e, tests: sh -c 'go test ./internal/plans/ -run 'ThrottleActive|RoundTripsThrottle' && go test ./internal/console/ -run 'SetAccountThrottle|PublishCarriesThrottle|PlanLimits|AccountPlan'' → ok github.com/carlosframework/platform/internal/console 6.900s) |
| +Task 2: Ruling: convergeThrottle treats an expired stored throttle (past Until) as off before applying 'unmeasured keeps the stored value' — a stale last-month throttle never carries into a new month — cost if wrong: none. |
| +Task 2: complete (commits 67a3a8e..d65f4f6, tests: go test ./internal/console/ -run 'ThrottleDue|ThrottleSet|ThrottleUnchanged|ThrottleWithout|BannerSays|GracePass' → ok github.com/carlosframework/platform/internal/console 3.377s) |
| +Task 3: Ruling: planThrottleFor answers only for instance routes (sidecar workers and others are never plan-throttled at the edge) — the spec's throttle targets the account's apps; workers have their own run ceiling — cost if wrong: a worker route escapes the slowdown. |
| +Task 3: complete (commits d65f4f6..6215723, tests: go test ./internal/host/ -run 'PlansPassKeepsThrottle|ExpiredThrottle|PlanMaxRunFor|ThrottleOffWith|PlansPass|PlanIdle|PlanRate' → ok github.com/carlosframework/platform/internal/host 1.334s) |
| +Task 4: Ruling: the plan throttle has its own limiter (Edge.planLimiter), separate from the #358 limiter, keyed 'plan:<account>' with one fixed client prefix — independent of CARLOS_RATE_LIMIT and of #358's buckets and eviction — cost if wrong: one more limiter's memory. |
| +Task 4: Ruling: an awake-throttled account's new upgrade gets the 429 with Retry-After 60s; upgrades are tracked (cancellable context) only while a throttle hook is armed, so a box without plans keeps its request untouched. |
| +Task 4: Ruling: the host closes upgrades on the pass that first sees an awake throttle (planAwakeThrottled, armed in agent.go beside SetPlanThrottleFor) — transitions only; later upgrades are refused at the edge. |
| +Task 4: complete (commits 6215723..ed72cb3, tests: sh -c 'go test ./internal/edge/ -run 'Throttle' && go test ./internal/host/ -run 'Throttle|PlansPass'' → ok github.com/carlosframework/platform/internal/host 1.670s) |
| +Task 5: Ruling: the ceiling skips an entry with a command in progress (e.cmd != nil), as the idle predicate does — a run is not cut mid-command — cost if wrong: a long command can hold an awake-throttled instance awake past 15 minutes. |
| +Task 5: complete (commits ed72cb3..00541bd, tests: go test ./internal/activator/ -run 'MaxRunFor|IdleFor|MaxRun|Sweep' → ok github.com/carlosframework/platform/internal/activator (cached)) |
| +Task 6: complete (commits 00541bd..64bbf1e, tests: sh -c 'GOFLAGS=-buildvcs=false go test ./internal/provision/ -run 'Plan14RootReadCensus$|Plan9B8RecordWriteCensus$'' → ok github.com/carlosframework/platform/internal/provision 7.706s) |
| +Final: fixed (1) cache hits bypassed the throttle — TestThrottleAppliesToCacheHits RED→GREEN (plan check moved before the response cache; #358 still after it) |
| +Final: fixed (2) an upgrade could escape the close — TestUpgradeRegisteredBeforeTheThrottleCheck RED→GREEN, mutation-checked (register before asking the throttle) |
| +Final: fixed (3) a plan change republished the old throttle — TestPlanChangeClearsTheThrottle RED→GREEN (SetAccountPlan clears it; the pass re-sets within the hour) |
| +Final: fixed (4, re-graded Important: a plan requirement) plans-off upgrades were tracked — TestUpgradesUntrackedWhenNotGoverned, TestPlanGoverned RED→GREEN (SetPlanGovernedFor + host planGoverned) |
| +Final: fixed (5, re-graded Important: a plan requirement) refusals not counted — TestPlanThrottleRefusalCounted, TestPlanThrottledSumsAndResetsWithOwner RED→GREEN (EdgeRow.PlanThrottled) |
| +Final: census — Astra approved the existing units and envelopes except sweepOnce's changed basis and the ten new units, which go to Paul. |
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..7c8587cd8 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-25-plans-4c-box-throttle.md |
| @@ -0,0 +1,261 @@ |
| +# 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 and 2 CONFIRMED by Paul, 2026-10-25; 3 taken as stated) |
| + |
| +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. |
| + |
| +## Astra review (2026-10-25) |
| + |
| +Findings in `docs/superpowers/specs/CODEX-FINDINGS-PLANS-4C-CODE.md`: three Important and two Minor. The two Minors were re-graded Important, because each breaks a requirement this plan states. All five are fixed, each test-first: |
| + |
| +1. **Cache hits skipped the throttle.** The plan check now runs before the response cache. The #358 limit still runs after it. |
| +2. **An upgrade could escape the close.** It is now registered before the throttle check (mutation-checked). |
| +3. **A plan change republished the old throttle.** `SetAccountPlan` now clears it, and the grace pass sets it again within the hour if the new plan is still exceeded. |
| +4. **Upgrades were tracked with plans off.** Tracking now happens only for an account plans govern (`SetPlanGovernedFor`, `planGoverned`). |
| +5. **Plan refusals weren't counted.** They are now counted in `EdgeRow.PlanThrottled`, apart from #358's counters. |
| + |
| +Census: Astra escalated `sweepOnce`'s changed basis and the ten new units to the census owner. |
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-PLANS-4C-CODE.md b/docs/superpowers/specs/CODEX-FINDINGS-PLANS-4C-CODE.md| new file mode 100644 |
| index 000000000..7f3219cad |
| --- /dev/null |
| +++ b/docs/superpowers/specs/CODEX-FINDINGS-PLANS-4C-CODE.md |
| @@ -0,0 +1,55 @@ |
| +Reviewed `13af0b2c459467404e79418be167c59661ca2649` against `7f8767715280765a9b47bd715a96203d3d36fda4`, which also matches local `origin/main`. No Critical findings. |
| + |
| +1. **Important — Cached responses bypass the account throttle.** |
| + [internal/edge/edge.go:1880](/home/paulca/.cache/tmp/claude-1001/plans-4c-box-throttle/internal/edge/edge.go:1880): cache hits return at lines 1866–1868 before `planThrottleAdmit`. An account past twice its bandwidth allowance can keep serving a cached response at unrestricted request rates, continuing to incur metered egress. Move the plan admission check before cache replay while preserving #358’s existing cache exemption. |
| + |
| +2. **Important — An upgrade can escape the throttle transition’s close operation.** |
| + [internal/edge/edge.go:1796](/home/paulca/.cache/tmp/claude-1001/plans-4c-box-throttle/internal/edge/edge.go:1796): admission and registration are separate. A request can pass `planUpgradeAdmit`, then the host publishes an awake throttle and calls `CloseAccountUpgrades`, then the request registers through `trackUpgrade` and completes its handshake. Registration never rechecks the throttle. Subsequent passes suppress the close callback because the account was already throttled. Make registration and the throttle recheck coordinate with closing, and add a deterministic test of this interleaving. |
| + |
| +3. **Important — A plan upgrade republishes the old throttle.** |
| + [internal/console/planlimits.go:95](/home/paulca/.cache/tmp/claude-1001/plans-4c-box-throttle/internal/console/planlimits.go:95): publication copies `row.Throttle` unchanged. `SetAccountPlan` preserves that column, and the plan-change handler immediately publishes without recalculating it. For example, upgrading a bandwidth-throttled Free account to Personal publishes the larger allowance while retaining the 5 req/s throttle. Relief waits for the hourly grace pass despite the new limits already reaching boxes. Reconcile the throttle against the changed allowance before publishing the plan change. |
| + |
| +4. **Minor — Plans-off boxes still track upgrades.** |
| + [internal/edge/planthrottle.go:76](/home/paulca/.cache/tmp/claude-1001/plans-4c-box-throttle/internal/edge/planthrottle.go:76): tracking checks whether the hook exists, but `runAgent` installs it unconditionally at line 951. With no catalog, no limits record, or `CARLOS_PLAN_LIMITS=off`, every instance upgrade still allocates a cancellable context and retains an account-map entry until completion. This violates the explicit requirement for no upgrade-tracking side effects when plans are off. Gate tracking on actual plan enablement, including the production wiring in its test. |
| + |
| +5. **Minor — Plan refusals omit the required rate-limit accounting.** |
| + [internal/edge/planthrottle.go:55](/home/paulca/.cache/tmp/claude-1001/plans-4c-box-throttle/internal/edge/planthrottle.go:55): both refusal paths log directly and write a 429; neither calls `noteRateLimited` or records an equivalent distinct counter. An account receiving plan-throttle 429s therefore contributes no corresponding rate-limit refusal counts. Add the specified `plan-throttle` accounting without misclassifying it as #358 backstop or fair-share shedding. |
| + |
| +The five Review Focus checks were examined individually: expiry is enforced at lookup without another pass; buckets are account-scoped; upgrade closure fails the race described above; busy instances reach the ceiling and use the existing serialized stop/wake lifecycle; unmeasured caps preserve an active throttle. The command exemption matches the executor’s ruling. Worker ceilings, held probes and in-progress seeds retain their guards. Publication revisions, missing-plan-row deferral, last-good snapshots, 429 formatting, limiter slot release and reuse of existing polling paths have no additional findings from source inspection. |
| + |
| +**Census verdicts** |
| + |
| +These verdicts concern the recorded authority basis; they do not waive the functional findings above. |
| + |
| +| Existing unit | Verdict and evidence | |
| +|---|---| |
| +| `activator.Service` | **Approve.** [activator.go:1146](/home/paulca/.cache/tmp/claude-1001/plans-4c-box-throttle/internal/activator/activator.go:1146) adds only the atomic hook field. | |
| +| `console.Store.migrate` | **Approve.** [store.go:426](/home/paulca/.cache/tmp/claude-1001/plans-4c-box-throttle/internal/console/store.go:426) adds a column to the existing console database; no new database or path selection. | |
| +| `edge.Edge.ServeHTTP` | **Approve.** [edge.go:1796](/home/paulca/.cache/tmp/claude-1001/plans-4c-box-throttle/internal/edge/edge.go:1796) and line 1880 add serving restrictions after existing scope and import gates; no root authority is granted. | |
| +| `host.runAgent` | **Approve.** [agent.go:503](/home/paulca/.cache/tmp/claude-1001/plans-4c-box-throttle/internal/host/agent.go:503) and lines 951–957 wire in-memory callbacks; existing root callbacks and input boundaries remain intact. | |
| +| `host.plansPass` | **Approve.** [plans_pass.go:105](/home/paulca/.cache/tmp/claude-1001/plans-4c-box-throttle/internal/host/plans_pass.go:105) reads the same account limits objects; lines 114–129 retain throttle values and notify the edge. No additional root input is followed. | |
| +| `activator.Service.sweepOnce` | **Escalate.** [activator.go:4734](/home/paulca/.cache/tmp/claude-1001/plans-4c-box-throttle/internal/activator/activator.go:4734) introduces a `StopIdle` path that bypasses `inflight == 0` and `heldForTick`, protections expressly named in the recorded basis. This is intentional ceiling behavior, but the owner must approve the changed basis rather than treating it as an unchanged-disposition approval. | |
| + |
| +All seven hand-written `plans-4c-units` entries are **new-unit decisions requiring the census owner**, as the card itself records: |
| + |
| +| New unit | Verdict and source assessment | |
| +|---|---| |
| +| `Store.SetAccountThrottle` | **Escalate — new disposition.** [accountplans.go:199](/home/paulca/.cache/tmp/claude-1001/plans-4c-box-throttle/internal/console/accountplans.go:199): parameterized update of the existing console table; no new root target. | |
| +| `Edge.planThrottleOf` | **Escalate — new disposition.** [planthrottle.go:32](/home/paulca/.cache/tmp/claude-1001/plans-4c-box-throttle/internal/edge/planthrottle.go:32): route classification and an in-memory hook; existing caller exemptions retained. | |
| +| `Edge.planThrottleAdmit` | **Escalate — new disposition.** [planthrottle.go:46](/home/paulca/.cache/tmp/claude-1001/plans-4c-box-throttle/internal/edge/planthrottle.go:46): in-memory bucket and HTTP refusal; no root operation. | |
| +| `Edge.planUpgradeAdmit` | **Escalate — new disposition.** [planthrottle.go:62](/home/paulca/.cache/tmp/claude-1001/plans-4c-box-throttle/internal/edge/planthrottle.go:62): restricts upgrade admission; no root operation. | |
| +| `Edge.trackUpgrade` | **Escalate — new disposition.** [planthrottle.go:75](/home/paulca/.cache/tmp/claude-1001/plans-4c-box-throttle/internal/edge/planthrottle.go:75): tracks cancellation by account; no tenant-named path is opened or executed. | |
| +| `planThrottleFor` | **Escalate — new disposition.** [plans_pass.go:194](/home/paulca/.cache/tmp/claude-1001/plans-4c-box-throttle/internal/host/plans_pass.go:194): reads the existing snapshot and checks expiry. | |
| +| `planMaxRunFor` | **Escalate — new disposition.** [plans_pass.go:211](/home/paulca/.cache/tmp/claude-1001/plans-4c-box-throttle/internal/host/plans_pass.go:211): returns a fixed duration from that snapshot; introduces no additional input source. | |
| + |
| +| Re-pinned envelope | Verdict | |
| +|---|---| |
| +| `internal/activator` | **Escalate**, for the `sweepOnce` basis change above. The field and setter add no separate authority concern. | |
| +| `internal/console` | **Approve** existing authority boundaries; new-unit disposition remains owner-gated. Changed functions use existing SQL, measurement, audit and limits-publication paths. | |
| +| `internal/edge` | **Approve** existing authority boundaries; four new-unit dispositions remain owner-gated. Changes reach in-memory limiting, cancellation and response writing. | |
| +| `internal/host` | **Approve** existing authority boundaries; two new-unit dispositions remain owner-gated. No new polling, bucket keys or root targets. | |
| +| `internal/plans` | **Approve.** Additive wire field, expiry predicate and fixed rate rule; no new I/O. | |
| + |
| +Independent read-only checks verified both overlay seals (`35f31d04…` and `eb7ea215…`), legacy fingerprints, all 13 unit source digests and all five envelope hashes. The Go tests—including the typed census checks—could not start because creating Go’s build directory failed with `read-only file system`. Nothing was modified or posted to #280. |
| + |
| +**Verdict: changes required.** |
| \ No newline at end of file |
diff --git a/docs/superpowers/specs/CODEX-REVIEW-BRIEF-PLANS-4C-CODE.md b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-PLANS-4C-CODE.md| new file mode 100644 |
| index 000000000..c45089b04 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-PLANS-4C-CODE.md |
| @@ -0,0 +1,44 @@ |
| +# Whole-branch code review brief: Plans 4c (box-side throttle) |
| + |
| +You are a senior Go reviewer on the carlos platform, and the census's |
| +cross-model reviewer for this branch. Review branch `plans-4c-box-throttle` |
| +(`git diff 7f8767715280765a9b47bd715a96203d3d36fda4..HEAD` is the branch's own change). Read-only: do not |
| +modify the working tree, index, HEAD or branches. You may run `go test` |
| +with GOFLAGS=-buildvcs=false, targeted with -run. |
| + |
| +Requirements: the spec docs/superpowers/specs/2026-10-20-plans-caps-packs-design.md |
| +§5.2 ("Awake hours"), §5.7, §6, §7 and table 4.2; the plan |
| +docs/superpowers/plans/2026-10-25-plans-4c-box-throttle.md, including its |
| +Global Constraints, Review Focus and Paul's CONFIRMED calls (bandwidth |
| +throttles at 2x without notice; awake hours at 2x with 72 h notice; |
| +5 req/s burst 30 per account; independent of CARLOS_RATE_LIMIT); the |
| +executor's `Ruling:` lines in docs/superpowers/notes/plans-4c-ledger.md. |
| +Plans 4a and 4b (merged) and the edge rate limiter #358 (merged) are the |
| +base. |
| + |
| +Grade by effect. Check each Review Focus line deliberately, and also: |
| +- plans off and boxes with CARLOS_PLAN_LIMITS=off change nothing: no |
| + throttle, no upgrade tracking side effects, rate limiter unchanged; |
| +- the console: revision bumps only on change; the publish pass and |
| + existing plan rows; a throttle row for an account with no plan row; |
| +- the edge: the throttle check's placement relative to the response cache, |
| + doors, hop-door and tunnel callers, the activator wake path, and the |
| + #358 limiter (no double counting, no slot leaks); upgrade tracking and |
| + context cancellation (leaks, races between CloseAccountUpgrades and a |
| + new upgrade); 429 shape; |
| +- the activator ceiling: hibernation semantics, probes, seeds, commands, |
| + workers, always-on routes, races with a wake; |
| +- the host: snapshot last-good copy, Until expiry, notification once per |
| + transition, CARLOS_PLAN_LIMITS=off; |
| +- cost: no new per-box polling (the throttle rides the existing limits |
| + record and the existing plans pass). |
| + |
| +Census: answer the card's review question for every unit and re-pinned |
| +envelope in docs/superpowers/notes/census-proposal-plans-4c-box-throttle.md, |
| +including the hand-written decision overlay plans-4c-units (approve or |
| +escalate per unit; check its seal and fingerprints). |
| + |
| +Answer: findings graded Critical / Important / Minor, each with file:line |
| +and a concrete failure scenario; then the census verdicts; then a verdict: |
| +accept, accept with fixes, or changes required. Do not review the wording |
| +(Luna-approved copy in plancaps_copy.go). |
diff --git a/docs/superpowers/specs/LUNA-COPY-BRIEF-PLANS-4C.md b/docs/superpowers/specs/LUNA-COPY-BRIEF-PLANS-4C.md| new file mode 100644 |
| index 000000000..2bd6d5695 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/LUNA-COPY-BRIEF-PLANS-4C.md |
| @@ -0,0 +1,32 @@ |
| +# Copy pass brief: plan throttle notices (plans 4c) |
| + |
| +You are reviewing user-facing strings for a hosting console (the carlos platform). Paul, the owner, delegated this review to you. Apply his house rules and return improved strings. |
| + |
| +## House rules |
| + |
| +- No em dashes or en dashes used as dashes. Where you would use one, end the sentence with a full stop and start a new one. |
| +- Plain words, short sentences, no jargon, no marketing tone, no exclamation marks. |
| +- CLI strings (keys starting `cli.`) are entirely lower case, with no full stop at the very end. Banner strings use normal sentence case. |
| +- Keep the one `%s` placeholder in each string. |
| +- Do not name the product. |
| +- Facts that must stay true: the account has used twice its monthly bandwidth or awake hours; its apps are served more slowly (a reduced request rate) until the month ends, not cut off; for awake hours, apps are also put to sleep after 15 minutes awake and wake on their next request, and open live connections (WebSockets) are closed; it all lifts when the month ends or the plan grows. |
| + |
| +## How the strings combine |
| + |
| +`%s` is a usage phrase. Examples: `25 GB of 10.7 GB bandwidth this month`, `210 of 100 awake hours this month`. |
| + |
| +- banner, bandwidth: This account is slowed down until the month ends: it has used 25 GB of 10.7 GB bandwidth this month. |
| +- banner, awake: This account's apps are slowed down and put to sleep after 15 minutes awake until the month ends: 210 of 100 awake hours this month. |
| + |
| +## Strings |
| + |
| +| key | current | |
| +|---|---| |
| +| `banner.bandwidth_throttled` | This account is slowed down until the month ends: it has used %s. | |
| +| `cli.bandwidth_throttled` | this account is slowed down until the month ends: it has used %s | |
| +| `banner.awake_throttled` | This account's apps are slowed down and put to sleep after 15 minutes awake until the month ends: %s. | |
| +| `cli.awake_throttled` | this account's apps are slowed down and put to sleep after 15 minutes awake until the month ends: %s | |
| + |
| +## Answer |
| + |
| +Return a Markdown table with columns `key`, `new`, `why` for every key, `new` equal to `current` where no change is needed. Then a section `Flags` for anything Paul must decide. Do not edit any files. |
diff --git a/docs/superpowers/specs/LUNA-COPY-RESULT-PLANS-4C.md b/docs/superpowers/specs/LUNA-COPY-RESULT-PLANS-4C.md| new file mode 100644 |
| index 000000000..468cb68bf |
| --- /dev/null |
| +++ b/docs/superpowers/specs/LUNA-COPY-RESULT-PLANS-4C.md |
| @@ -0,0 +1,10 @@ |
| +| key | new | why | |
| +|---|---|---| |
| +| `banner.bandwidth_throttled` | This account's apps are served more slowly until the month ends or the plan grows: it has used %s. | Names the affected apps, explains the reduced rate, and includes both recovery conditions. | |
| +| `cli.bandwidth_throttled` | this account's apps are served more slowly until the month ends or the plan grows: it has used %s | Same facts in lower case with no final full stop. | |
| +| `banner.awake_throttled` | This account's apps are served more slowly and put to sleep after 15 minutes awake until the month ends or the plan grows: %s. Open live connections (WebSockets) are closed. | Keeps the sleep rule, reduced rate, recovery conditions, and connection behavior. | |
| +| `cli.awake_throttled` | this account's apps are served more slowly and put to sleep after 15 minutes awake until the month ends or the plan grows: %s. open live connections are closed | Same facts in lower case with no final full stop. | |
| + |
| +## Flags |
| + |
| +None. |
| \ No newline at end of file |
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index 3c6870a57..97d513ce9 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -1143,6 +1143,10 @@ type Service struct { |
| // entry's route it names the plan's idle window, or 0 for no opinion. It |
| // can only shorten a window. nil means today's behaviour. |
| idleFor atomic.Pointer[func(registry.Route) time.Duration] |
| + // maxRunFor is the plans continuous-awake hook (plans 4c): a ceiling on |
| + // how long an instance stays awake, busy or not; 0 is none. Workers |
| + // keep their own MaxRunSeconds and are never asked. |
| + maxRunFor atomic.Pointer[func(registry.Route) time.Duration] |
| cfg Config |
| backend Backend |
| @@ -4722,6 +4726,18 @@ func (a *Service) sweepOnce() { |
| a.beginStopLocked(e, StopIdle) |
| continue |
| } |
| + // The plans continuous-awake ceiling (plans 4c, spec §5.2): an |
| + // awake-throttled account's instance that is never idle (a steady |
| + // pinger, a long stream) still sleeps after the ceiling, whatever is |
| + // in flight, and wakes on its next request. Never a worker, and |
| + // never mid-command. |
| + if f := a.maxRunFor.Load(); f != nil && !e.worker && hibernates && e.cmd == nil { |
| + if d := (*f)(e.route); d > 0 && now.Sub(e.spawnedAt) >= d { |
| + log.Printf("activator: %s awake %s, past its plan's ceiling of %s — stopping", e.host, now.Sub(e.spawnedAt).Truncate(time.Second), d) |
| + a.beginStopLocked(e, StopIdle) |
| + continue |
| + } |
| + } |
| // Converge onto a shipped build. A running child never re-reads |
| // live/<host>, so once a ship repoints the symlink this awake child is |
| // serving a stale binary. Idle hosts converge for free on their next |
| @@ -5489,3 +5505,14 @@ func (a *Service) SetIdleFor(f func(registry.Route) time.Duration) { |
| } |
| a.idleFor.Store(&f) |
| } |
| + |
| +// SetMaxRunFor installs the plans continuous-awake hook (plans 4c): an |
| +// instance awake for that long is put to sleep even while busy, and wakes |
| +// on its next request. nil, and a return of 0, mean no ceiling. |
| +func (a *Service) SetMaxRunFor(f func(registry.Route) time.Duration) { |
| + if f == nil { |
| + a.maxRunFor.Store(nil) |
| + return |
| + } |
| + a.maxRunFor.Store(&f) |
| +} |
diff --git a/internal/activator/activator_maxrunfor_test.go b/internal/activator/activator_maxrunfor_test.go| new file mode 100644 |
| index 000000000..fe4469083 |
| --- /dev/null |
| +++ b/internal/activator/activator_maxrunfor_test.go |
| @@ -0,0 +1,72 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// The plans continuous-awake hook (plans 4c): an awake-throttled account's |
| +// instance sleeps after 15 minutes awake even while busy, and wakes on its |
| +// next request. |
| + |
| +func maxRunFor(d time.Duration) func(registry.Route) time.Duration { |
| + return func(registry.Route) time.Duration { return d } |
| +} |
| + |
| +func TestMaxRunForStopsABusyInstance(t *testing.T) { |
| + t.Parallel() |
| + a, _, clk, _ := testActivator(t, 15*time.Minute) |
| + a.SetMaxRunFor(maxRunFor(15 * time.Minute)) |
| + release, err := a.beginRequest(context.Background(), testRoute("one.example.com")) |
| + if err != nil { |
| + t.Fatalf("beginRequest: %v", err) |
| + } |
| + defer release() // held in flight throughout |
| + clk.advance(14 * time.Minute) |
| + a.sweepOnce() |
| + if a.entryCount() != 1 { |
| + t.Fatal("stopped before the 15-minute ceiling") |
| + } |
| + clk.advance(time.Minute + time.Second) |
| + a.sweepOnce() |
| + waitFor(t, "ceiling stop of a busy instance", func() bool { return a.entryCount() == 0 }) |
| + wakeInstance(t, a, "one.example.com") |
| + if a.entryCount() != 1 { |
| + t.Fatal("the next request did not wake it") |
| + } |
| +} |
| + |
| +func TestMaxRunForZeroUnchanged(t *testing.T) { |
| + t.Parallel() |
| + a, _, clk, _ := testActivator(t, 15*time.Minute) |
| + a.SetMaxRunFor(maxRunFor(0)) |
| + release, err := a.beginRequest(context.Background(), testRoute("one.example.com")) |
| + if err != nil { |
| + t.Fatalf("beginRequest: %v", err) |
| + } |
| + defer release() |
| + clk.advance(2 * time.Hour) |
| + a.sweepOnce() |
| + if a.entryCount() != 1 { |
| + t.Fatal("a zero ceiling stopped a busy instance") |
| + } |
| +} |
| + |
| +func TestMaxRunForLeavesWorkersAlone(t *testing.T) { |
| + t.Parallel() |
| + a, _, clk, _ := testActivator(t, 15*time.Minute) |
| + a.SetMaxRunFor(maxRunFor(time.Minute)) |
| + rt := testWorkerRoute("bot.x.internal") |
| + rt.Hibernate = false // always on: no idle clock, so only a ceiling could stop it |
| + if err := a.WakeWorker(rt); err != nil { |
| + t.Fatalf("WakeWorker: %v", err) |
| + } |
| + clk.advance(5 * time.Minute) |
| + a.sweepOnce() |
| + if !a.entryAwake("bot.x.internal") { |
| + t.Fatal("the instance ceiling stopped a worker") |
| + } |
| +} |
diff --git a/internal/console/accountplans.go b/internal/console/accountplans.go| index 4917eb1b7..5a3980c24 100644 |
| --- a/internal/console/accountplans.go |
| +++ b/internal/console/accountplans.go |
| @@ -39,19 +39,27 @@ type AccountPlanRow struct { |
| PublishedCatalog string |
| UpdatedBy string |
| UpdatedAt time.Time |
| + // Throttle is the account's plan throttle (plans 4c); nil for none. |
| + Throttle *plans.Throttle |
| } |
| const accountPlanColumns = `p.account_id, a.sqid, p.plan, p.packs, p.source, p.sponsored, p.reason, |
| - p.revision, p.published_revision, p.published_catalog, p.updated_by, p.updated_at` |
| + p.revision, p.published_revision, p.published_catalog, p.updated_by, p.updated_at, p.throttle` |
| func scanAccountPlan(sc interface{ Scan(...any) error }) (*AccountPlanRow, error) { |
| var r AccountPlanRow |
| - var packs, sponsored string |
| + var packs, sponsored, throttle string |
| var updated int64 |
| if err := sc.Scan(&r.AccountID, &r.Sqid, &r.Plan, &packs, &r.Source, &sponsored, &r.Reason, |
| - &r.Revision, &r.PublishedRevision, &r.PublishedCatalog, &r.UpdatedBy, &updated); err != nil { |
| + &r.Revision, &r.PublishedRevision, &r.PublishedCatalog, &r.UpdatedBy, &updated, &throttle); err != nil { |
| return nil, err |
| } |
| + if throttle != "" { |
| + r.Throttle = &plans.Throttle{} |
| + if err := json.Unmarshal([]byte(throttle), r.Throttle); err != nil { |
| + return nil, err |
| + } |
| + } |
| if err := json.Unmarshal([]byte(packs), &r.Packs); err != nil { |
| return nil, err |
| } |
| @@ -76,6 +84,10 @@ func (s *Store) AccountPlan(accountID int64) (*AccountPlanRow, error) { |
| } |
| // SetAccountPlan writes the account's plan and returns its new revision. |
| +// It drops the account's throttle (plans 4c, Astra finding 3): a bigger |
| +// plan's relief must reach the boxes with its limits, and the grace pass |
| +// sets the throttle again within the hour if the new plan is still |
| +// exceeded. |
| // It validates nothing: callers check the plan against the catalog first. |
| func (s *Store) SetAccountPlan(accountID int64, plan string, packs map[string]int, source string, |
| sponsored *plans.Limits, reason, by string, now time.Time) (int64, error) { |
| @@ -100,7 +112,8 @@ func (s *Store) SetAccountPlan(accountID int64, plan string, packs map[string]in |
| SELECT ?, ?, ?, ?, ?, ?, 1, ?, ? WHERE EXISTS (SELECT 1 FROM accounts WHERE id = ? AND deleted_at = 0) |
| ON CONFLICT(account_id) DO UPDATE SET plan = excluded.plan, packs = excluded.packs, |
| source = excluded.source, sponsored = excluded.sponsored, reason = excluded.reason, |
| - updated_by = excluded.updated_by, updated_at = excluded.updated_at, revision = revision + 1 |
| + updated_by = excluded.updated_by, updated_at = excluded.updated_at, revision = revision + 1, |
| + throttle = '' |
| RETURNING revision`, |
| accountID, plan, string(pj), source, sj, reason, by, now.Unix(), accountID).Scan(&rev) |
| if errors.Is(err, sql.ErrNoRows) { |
| @@ -182,3 +195,27 @@ func (s *Store) RestoringAppsIn(accountID int64) ([]string, error) { |
| } |
| return out, rows.Err() |
| } |
| + |
| +// SetAccountThrottle stores the account's throttle (nil clears it) and |
| +// bumps its revision so the publish pass carries it to the boxes. An |
| +// unchanged throttle writes nothing. An account with no plan row yet is |
| +// (false, nil): the default-plan pass gives it one, and the next grace |
| +// pass sets the throttle then. |
| +func (s *Store) SetAccountThrottle(accountID int64, t *plans.Throttle, now time.Time) (bool, error) { |
| + val := "" |
| + if t != nil { |
| + t.Until = t.Until.UTC() |
| + b, err := json.Marshal(t) |
| + if err != nil { |
| + return false, err |
| + } |
| + val = string(b) |
| + } |
| + res, err := s.db.Exec(`UPDATE account_plans SET throttle = ?, revision = revision + 1, updated_at = ? |
| + WHERE account_id = ? AND throttle <> ?`, val, now.Unix(), accountID, val) |
| + if err != nil { |
| + return false, err |
| + } |
| + n, err := res.RowsAffected() |
| + return n > 0, err |
| +} |
diff --git a/internal/console/plancaps_copy.go b/internal/console/plancaps_copy.go| index 0552ab413..745e220e6 100644 |
| --- a/internal/console/plancaps_copy.go |
| +++ b/internal/console/plancaps_copy.go |
| @@ -49,4 +49,10 @@ var planNoticeCopy = map[string]string{ |
| "cli.email_paused": "email is paused until midnight utc: this account sent %s", |
| "banner.storage_denied": "New uploads to this account's storage are refused: %s. Downloads and deletes still work.", |
| "cli.storage_denied": "new uploads to this account's storage are refused: %s. downloads and deletes still work", |
| + // Plans 4c: the monthly throttle. Approved by delegation (Luna, |
| + // docs/superpowers/specs/LUNA-COPY-RESULT-PLANS-4C.md). |
| + "banner.bandwidth_throttled": "This account's apps are served more slowly until the month ends or the plan grows: it has used %s.", |
| + "cli.bandwidth_throttled": "this account's apps are served more slowly until the month ends or the plan grows: it has used %s", |
| + "banner.awake_throttled": "This account's apps are served more slowly and put to sleep after 15 minutes awake until the month ends or the plan grows: %s. Open live connections (WebSockets) are closed.", |
| + "cli.awake_throttled": "this account's apps are served more slowly and put to sleep after 15 minutes awake until the month ends or the plan grows: %s. open live connections are closed", |
| } |
diff --git a/internal/console/plangrace_view_test.go b/internal/console/plangrace_view_test.go| index be2fbb535..9f8f77cc8 100644 |
| --- a/internal/console/plangrace_view_test.go |
| +++ b/internal/console/plangrace_view_test.go |
| @@ -119,3 +119,18 @@ func TestBannerSaysStorageWritesDenied(t *testing.T) { |
| t.Fatalf("no storage-denied banner:\n%s", body) |
| } |
| } |
| + |
| +func TestBannerSaysBandwidthThrottled(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + acct, _ := fx.st.AccountBySqid(fx.sqid) |
| + st := evaluateCap(nil, capBandwidth, 25_000_000_000, 10_737_418_240, time.Now()) // free: 10 GiB a month, 2x and over |
| + st.AccountID = acct.ID |
| + if err := fx.st.PutCapState(st); err != nil { |
| + t.Fatal(err) |
| + } |
| + c := signInPaul(t, fx) |
| + if _, _, body := get(t, c, fx.u("/")); !strings.Contains(body, "This account's apps are served more slowly until the month ends") { |
| + t.Fatalf("no bandwidth-throttled banner:\n%s", body) |
| + } |
| +} |
diff --git a/internal/console/plangracepass.go b/internal/console/plangracepass.go| index 3fc5ebd19..feb8d32e6 100644 |
| --- a/internal/console/plangracepass.go |
| +++ b/internal/console/plangracepass.go |
| @@ -99,6 +99,18 @@ func (s *Server) planGraceAccount(ctx context.Context, acct *Account, now time.T |
| } |
| } |
| } |
| + byState := map[capID]capState{} |
| + measuredCaps, offeredCaps := map[capID]bool{}, map[capID]bool{} |
| + for _, st := range states { |
| + byState[st.Cap] = st |
| + } |
| + for _, c := range capOrder { |
| + _, m := measures[c] |
| + measuredCaps[c], offeredCaps[c] = m, m || errs[c] != nil |
| + } |
| + if err := s.convergeThrottle(ctx, acct, byState, measuredCaps, offeredCaps, now); err != nil { |
| + log.Printf("console: plan grace %s: throttle: %v", acct.Sqid, err) |
| + } |
| if _, measured := measures[capStorage]; !measured && errs[capStorage] == nil { |
| // The plan sets no storage limit: nothing can be over it. |
| if err := s.clearStorageDeny(ctx, acct, now); err != nil { |
| @@ -352,6 +364,10 @@ func (s *Server) planStage(acct *Account, now time.Time) func(capState) string { |
| return "email_paused" |
| case st.Cap == capStorage && storageDenyDue(st, now): |
| return "storage_denied" |
| + case st.Cap == capBandwidth && bandwidthThrottleDue(st, now): |
| + return "bandwidth_throttled" |
| + case st.Cap == capAwakeHours && awakeThrottleDue(st, now): |
| + return "awake_throttled" |
| } |
| return "" |
| } |
diff --git a/internal/console/planlimits.go b/internal/console/planlimits.go| index 813f0020c..dd9456831 100644 |
| --- a/internal/console/planlimits.go |
| +++ b/internal/console/planlimits.go |
| @@ -92,6 +92,7 @@ func (s *Server) publishAccountLimits(ctx context.Context, row AccountPlanRow, n |
| Revision: row.Revision, |
| Limits: limits, |
| IssuedAt: now.UTC().Truncate(time.Second), |
| + Throttle: row.Throttle, |
| } |
| for attempt := 0; attempt < 2; attempt++ { |
| cur, etag, err := plans.GetLimits(ctx, s.cfg.Releases, row.Sqid) |
diff --git a/internal/console/planlimits_test.go b/internal/console/planlimits_test.go| index fb81019c2..9b00f0f63 100644 |
| --- a/internal/console/planlimits_test.go |
| +++ b/internal/console/planlimits_test.go |
| @@ -238,3 +238,68 @@ func TestPlanLimitsPassOrphansDoNotStarveLaterAccounts(t *testing.T) { |
| t.Fatal("orphaned accounts starved a later valid account") |
| } |
| } |
| + |
| +func TestSetAccountThrottleBumpsRevisionOnChange(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + acct := planAccount(t, fx, 501) |
| + if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + before, _ := fx.st.AccountPlan(acct.ID) |
| + th := &plans.Throttle{Bandwidth: true, Until: time.Date(2027, 2, 1, 0, 0, 0, 0, time.UTC)} |
| + if changed, err := fx.st.SetAccountThrottle(acct.ID, th, planNow); err != nil || !changed { |
| + t.Fatalf("set = %v, %v", changed, err) |
| + } |
| + row, _ := fx.st.AccountPlan(acct.ID) |
| + if row.Revision != before.Revision+1 || row.Throttle == nil || !row.Throttle.Bandwidth { |
| + t.Fatalf("row after set = %+v", row) |
| + } |
| + if changed, err := fx.st.SetAccountThrottle(acct.ID, th, planNow); err != nil || changed { |
| + t.Fatalf("same throttle again = %v, %v, want unchanged", changed, err) |
| + } |
| + if again, _ := fx.st.AccountPlan(acct.ID); again.Revision != row.Revision { |
| + t.Fatalf("revision moved on an unchanged throttle: %d -> %d", row.Revision, again.Revision) |
| + } |
| + if changed, err := fx.st.SetAccountThrottle(acct.ID, nil, planNow); err != nil || !changed { |
| + t.Fatalf("clear = %v, %v", changed, err) |
| + } |
| + if cleared, _ := fx.st.AccountPlan(acct.ID); cleared.Throttle != nil { |
| + t.Fatalf("cleared row still throttled: %+v", cleared.Throttle) |
| + } |
| +} |
| + |
| +func TestPublishCarriesThrottle(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + acct := planAccount(t, fx, 501) |
| + fx.srv.planLimitsPass(context.Background(), planNow) |
| + th := &plans.Throttle{Awake: true, Until: time.Date(2027, 2, 1, 0, 0, 0, 0, time.UTC)} |
| + if _, err := fx.st.SetAccountThrottle(acct.ID, th, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.srv.planLimitsPass(context.Background(), planNow.Add(time.Minute)) |
| + r, _ := readLimits(t, fx, acct.Sqid) |
| + if r == nil || r.Throttle == nil || !r.Throttle.Awake || !r.Throttle.Until.Equal(th.Until) { |
| + t.Fatalf("published record = %+v", r) |
| + } |
| +} |
| + |
| +// Astra plans-4c finding 3: a plan change drops the throttle, so a bigger |
| +// plan's relief reaches the boxes with its limits; the grace pass sets it |
| +// again within the hour if the new plan is still exceeded. |
| +func TestPlanChangeClearsTheThrottle(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + acct := planAccount(t, fx, 501) |
| + if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.st.SetAccountThrottle(acct.ID, &plans.Throttle{Bandwidth: true, Until: planNow.Add(time.Hour)}, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.st.SetAccountPlan(acct.ID, "personal", nil, PlanSourceOperator, nil, "upgrade", "ops@example.com", planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if row, _ := fx.st.AccountPlan(acct.ID); row.Throttle != nil { |
| + t.Fatalf("throttle survived a plan change: %+v", row.Throttle) |
| + } |
| +} |
diff --git a/internal/console/planthrottle.go b/internal/console/planthrottle.go| new file mode 100644 |
| index 000000000..284cf3f1a |
| --- /dev/null |
| +++ b/internal/console/planthrottle.go |
| @@ -0,0 +1,68 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/plans" |
| +) |
| + |
| +// bandwidthThrottleDue: the month's bandwidth has reached twice the limit, |
| +// table 4.2's hard ceiling, "then throttled", which does not wait for |
| +// notice (Paul, 2026-10-25). |
| +func bandwidthThrottleDue(st capState, now time.Time) bool { |
| + return st.Period == capPeriod(capBandwidth, now) && st.Level == levelCeiling |
| +} |
| + |
| +// awakeThrottleDue: the month's awake hours have reached twice the limit |
| +// and an owner has had notice for 72 hours. Awake hours have no hard |
| +// ceiling, so the notice rule holds (Paul, 2026-10-25). |
| +func awakeThrottleDue(st capState, now time.Time) bool { |
| + return st.Period == capPeriod(capAwakeHours, now) && st.Level == levelCeiling && |
| + !st.NoticeAt.IsZero() && !st.NoticeAt.After(now.Add(-72*time.Hour)) |
| +} |
| + |
| +// convergeThrottle sets the account's throttle from this pass's rows |
| +// (plans 4c). Per cap: measured decides from the predicate; not offered by |
| +// the plan means no throttle; offered but unmeasured keeps what is stored |
| +// (unknown is not over), unless the stored throttle has already expired. |
| +func (s *Server) convergeThrottle(ctx context.Context, acct *Account, states map[capID]capState, measured, offered map[capID]bool, now time.Time) error { |
| + if s.cfg.PlanCatalog == nil { |
| + return nil |
| + } |
| + row, err := s.store.AccountPlan(acct.ID) |
| + if err != nil || row == nil { |
| + return err |
| + } |
| + var bw, aw bool |
| + if row.Throttle.Active(now) { |
| + bw, aw = row.Throttle.Bandwidth, row.Throttle.Awake |
| + } |
| + decide := func(c capID, cur bool, due func(capState, time.Time) bool) bool { |
| + switch { |
| + case measured[c]: |
| + return due(states[c], now) |
| + case !offered[c]: |
| + return false |
| + } |
| + return cur |
| + } |
| + bw = decide(capBandwidth, bw, bandwidthThrottleDue) |
| + aw = decide(capAwakeHours, aw, awakeThrottleDue) |
| + var next *plans.Throttle |
| + if bw || aw { |
| + next = &plans.Throttle{Bandwidth: bw, Awake: aw, Until: graceEnd(capBandwidth, now)} |
| + } |
| + changed, err := s.store.SetAccountThrottle(acct.ID, next, now) |
| + if err != nil || !changed { |
| + return err |
| + } |
| + if next == nil { |
| + s.audit(acct, "", "plan", "plan.unthrottled", "plan: the account is no longer slowed down") |
| + return nil |
| + } |
| + s.audit(acct, "", "plan", "plan.throttled", fmt.Sprintf("plan: slowed down until %s (bandwidth %v, awake hours %v)", |
| + next.Until.Format("2 January 2006"), bw, aw)) |
| + return nil |
| +} |
diff --git a/internal/console/planthrottle_test.go b/internal/console/planthrottle_test.go| new file mode 100644 |
| index 000000000..bac62f425 |
| --- /dev/null |
| +++ b/internal/console/planthrottle_test.go |
| @@ -0,0 +1,118 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func monthRow(c capID, used, limit int64, at time.Time) capState { |
| + return evaluateCap(nil, c, used, limit, at) |
| +} |
| + |
| +func TestBandwidthThrottleDue(t *testing.T) { |
| + now := planNow |
| + if bandwidthThrottleDue(monthRow(capBandwidth, 150, 100, now), now) { |
| + t.Error("due when over but under 2x") |
| + } |
| + if !bandwidthThrottleDue(monthRow(capBandwidth, 200, 100, now), now) { |
| + t.Error("not due at 2x without notice") |
| + } |
| + last := monthRow(capBandwidth, 300, 100, now.AddDate(0, -1, 0)) |
| + if bandwidthThrottleDue(last, now) { |
| + t.Error("last month's ceiling row due this month") |
| + } |
| +} |
| + |
| +func TestAwakeThrottleDue(t *testing.T) { |
| + now := planNow |
| + st := monthRow(capAwakeHours, 200, 100, now.Add(-100*time.Hour)) |
| + if awakeThrottleDue(st, now) { |
| + t.Error("due at 2x without notice") |
| + } |
| + st.NoticeAt = now.Add(-71 * time.Hour) |
| + if awakeThrottleDue(st, now) { |
| + t.Error("due with notice 71h old") |
| + } |
| + st.NoticeAt = now.Add(-72 * time.Hour) |
| + if !awakeThrottleDue(st, now) { |
| + t.Error("not due at 2x with notice 72h old") |
| + } |
| +} |
| + |
| +func throttleFixture(t *testing.T) (*consoleFixture, *Account) { |
| + t.Helper() |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + acct, _ := fx.st.AccountBySqid(fx.sqid) |
| + if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + return fx, acct |
| +} |
| + |
| +func both(v bool) map[capID]bool { return map[capID]bool{capBandwidth: v, capAwakeHours: v} } |
| + |
| +func TestThrottleSetAndCleared(t *testing.T) { |
| + fx, acct := throttleFixture(t) |
| + ctx := context.Background() |
| + states := map[capID]capState{capBandwidth: monthRow(capBandwidth, 200, 100, planNow)} |
| + if err := fx.srv.convergeThrottle(ctx, acct, states, map[capID]bool{capBandwidth: true}, both(true), planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + row, _ := fx.st.AccountPlan(acct.ID) |
| + if row.Throttle == nil || !row.Throttle.Bandwidth || row.Throttle.Awake || !row.Throttle.Until.Equal(graceEnd(capBandwidth, planNow)) { |
| + t.Fatalf("throttle = %+v", row.Throttle) |
| + } |
| + under := map[capID]capState{capBandwidth: monthRow(capBandwidth, 50, 100, planNow)} |
| + if err := fx.srv.convergeThrottle(ctx, acct, under, map[capID]bool{capBandwidth: true}, both(true), planNow.Add(time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if row, _ := fx.st.AccountPlan(acct.ID); row.Throttle != nil { |
| + t.Fatalf("throttle after falling under = %+v", row.Throttle) |
| + } |
| + events, _ := fx.st.Events(acct.ID, "", 20) |
| + var actions []string |
| + for _, e := range events { |
| + actions = append(actions, e.Action) |
| + } |
| + joined := strings.Join(actions, ",") |
| + if !strings.Contains(joined, "plan.throttled") || !strings.Contains(joined, "plan.unthrottled") { |
| + t.Errorf("audit = %v, want plan.throttled and plan.unthrottled", actions) |
| + } |
| +} |
| + |
| +func TestThrottleUnchangedWhenUnmeasured(t *testing.T) { |
| + fx, acct := throttleFixture(t) |
| + ctx := context.Background() |
| + states := map[capID]capState{capBandwidth: monthRow(capBandwidth, 200, 100, planNow)} |
| + if err := fx.srv.convergeThrottle(ctx, acct, states, map[capID]bool{capBandwidth: true}, both(true), planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.srv.convergeThrottle(ctx, acct, map[capID]capState{}, both(false), both(true), planNow.Add(time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if row, _ := fx.st.AccountPlan(acct.ID); row.Throttle == nil || !row.Throttle.Bandwidth { |
| + t.Fatalf("an unmeasured pass changed the throttle: %+v", row.Throttle) |
| + } |
| + // A plan without the cap clears it. |
| + if err := fx.srv.convergeThrottle(ctx, acct, map[capID]capState{}, both(false), both(false), planNow.Add(2*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if row, _ := fx.st.AccountPlan(acct.ID); row.Throttle != nil { |
| + t.Fatalf("a plan without the caps kept the throttle: %+v", row.Throttle) |
| + } |
| +} |
| + |
| +func TestThrottleWithoutACatalogUnchanged(t *testing.T) { |
| + fx, acct := throttleFixture(t) |
| + fx.srv.cfg.PlanCatalog = nil |
| + states := map[capID]capState{capBandwidth: monthRow(capBandwidth, 200, 100, planNow)} |
| + if err := fx.srv.convergeThrottle(context.Background(), acct, states, map[capID]bool{capBandwidth: true}, both(true), planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if row, _ := fx.st.AccountPlan(acct.ID); row.Throttle != nil { |
| + t.Fatal("throttled with plans off") |
| + } |
| +} |
diff --git a/internal/console/store.go b/internal/console/store.go| index 17a8619b5..5049a2b4f 100644 |
| --- a/internal/console/store.go |
| +++ b/internal/console/store.go |
| @@ -422,6 +422,8 @@ func (s *Store) migrate() error { |
| // re-running is always safe. |
| for _, stmt := range []string{ |
| `ALTER TABLE users ADD COLUMN operator INTEGER NOT NULL DEFAULT 0;`, |
| + // Plans 4c: the account's throttle, JSON, "" for none. |
| + `ALTER TABLE account_plans ADD COLUMN throttle TEXT NOT NULL DEFAULT '';`, |
| // deliveries (tenant-email, ruling 2a): SES already publishes |
| // Delivery to the event destination and the ingest already |
| // verifies and parses it — this stops throwing the answer away. |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 9978d0e3c..d138d7e2a 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -57,6 +57,7 @@ import ( |
| "github.com/carlosframework/platform/internal/geo" |
| "github.com/carlosframework/platform/internal/geoip" |
| "github.com/carlosframework/platform/internal/lbhealth" |
| + "github.com/carlosframework/platform/internal/plans" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/ratelimit" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -323,6 +324,14 @@ type Edge struct { |
| rateMode RateMode |
| rateLimiter *ratelimit.Limiter |
| rateCeiling atomic.Pointer[func(registry.Route) ratelimit.Ceiling] |
| + // planThrottle, planLimiter and upgrades are the plan throttle (plans |
| + // 4c, planthrottle.go): the hook, the per-account buckets, and each |
| + // account's open upgraded connections, closable when it is throttled. |
| + planThrottle atomic.Pointer[func(registry.Route) (plans.Throttle, bool)] |
| + planGoverned atomic.Pointer[func(registry.Route) bool] |
| + planLimiter *ratelimit.Limiter |
| + upgradesMu sync.Mutex |
| + upgrades map[string]map[*int]context.CancelFunc |
| } |
| // RunOption configures the Edge that Run/RunWithActivator* builds, before it |
| @@ -423,7 +432,8 @@ type upstream struct { |
| // (no hibernation). |
| func New(reg *registry.Registry, act Activator) (*Edge, error) { |
| e := &Edge{reg: reg, act: act, gate: gate.New(), probers: newProberSet(), gzipOn: gzipEnabled(), steeringHost: steeringProbeHostFromEnv(), appsDomain: appsDomainFromEnv(), |
| - lbHealth: lbHealthFromEnv(os.Getenv, act), rateMode: rateModeFromEnv(), rateLimiter: ratelimit.NewLimiter(time.Now, 100_000)} |
| + lbHealth: lbHealthFromEnv(os.Getenv, act), rateMode: rateModeFromEnv(), rateLimiter: ratelimit.NewLimiter(time.Now, 100_000), |
| + planLimiter: ratelimit.NewLimiter(time.Now, 100_000)} |
| e.geo = geo.NewSwappable() |
| e.geoLookup = e.geo.Lookup |
| // Generations (zero-downtime spec §7.2), before the startup Reload so |
| @@ -1784,6 +1794,12 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // proxy's hijack on a 101, so an open WebSocket is not counted, and |
| // it is itself an http.Hijacker (with Unwrap) for the proxy. A |
| // refusal is written to the raw writer. |
| + var untrack func() |
| + r, untrack = e.trackUpgrade(r, up) |
| + defer untrack() |
| + if !e.planUpgradeAdmit(w, r, up) { |
| + return |
| + } |
| release, ok := e.rateAdmit(w, r, up) |
| if !ok { |
| return |
| @@ -1838,6 +1854,13 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // A gated row's verify request is exempt in both directions too: it must |
| // reach the import rather than a response cached for the legacy route, |
| // and the import's answer must not outlive a rollback. |
| + // The plan throttle (planthrottle.go) comes BEFORE the cache: a slowed |
| + // account is slowed whoever answers, and a cache hit still spends |
| + // bandwidth (Astra plans-4c finding 1). The per-instance rate limit |
| + // below stays after it, so it still never limits a hit. |
| + if !e.planThrottleAdmit(w, r, up) { |
| + return |
| + } |
| cacheable := e.cache != nil && (r.Method == http.MethodGet || r.Method == http.MethodHead) && |
| up.route.Kind != "status" && up.route.ImportGate == "" |
| var key CacheKey |
diff --git a/internal/edge/planthrottle.go b/internal/edge/planthrottle.go| new file mode 100644 |
| index 000000000..65358f5f3 |
| --- /dev/null |
| +++ b/internal/edge/planthrottle.go |
| @@ -0,0 +1,138 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "net/netip" |
| + |
| + "github.com/carlosframework/platform/internal/plans" |
| + "github.com/carlosframework/platform/internal/ratelimit" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// planThrottleBucket is the one client key of an account's throttle bucket: |
| +// the bucket is the account's, whoever is asking. |
| +var planThrottleBucket = netip.MustParsePrefix("0.0.0.0/0") |
| + |
| +// SetPlanThrottleFor installs the plan throttle hook (plans 4c): whether a |
| +// route's account is slowed down for the rest of the month, and why |
| +// (internal/host's planThrottleFor). nil, the default and every box without |
| +// a plan catalog, throttles nothing. Safe to call while serving. |
| +func (e *Edge) SetPlanThrottleFor(f func(registry.Route) (plans.Throttle, bool)) { |
| + if f == nil { |
| + e.planThrottle.Store(nil) |
| + return |
| + } |
| + e.planThrottle.Store(&f) |
| +} |
| + |
| +// SetPlanGovernedFor installs the hook that says whether a route's account |
| +// is governed by plans on this box at all (internal/host's planGoverned): |
| +// only then are its upgrades tracked for closing (Astra plans-4c finding |
| +// 4). nil tracks nothing. |
| +func (e *Edge) SetPlanGovernedFor(f func(registry.Route) bool) { |
| + if f == nil { |
| + e.planGoverned.Store(nil) |
| + return |
| + } |
| + e.planGoverned.Store(&f) |
| +} |
| + |
| +// notePlanThrottled counts and logs one plan-throttle refusal, apart from |
| +// the per-instance rate limit's reasons (Astra plans-4c finding 5). |
| +func (e *Edge) notePlanThrottled(rt registry.Route, what string) { |
| + if m := e.usageMeter.Load(); m != nil { |
| + m.RecordPlanThrottled(rt) |
| + } |
| + e.logThrottled("plan-throttle "+rt.Host, "plan throttle: refused "+what+" for "+rt.Host+" (the account is slowed down until the month ends)") |
| +} |
| + |
| +// planThrottleOf is the route's throttle when one applies to this request. |
| +// Door, hop-door and tunnel callers are exempt, as from the rate limit. |
| +func (e *Edge) planThrottleOf(r *http.Request, up upstream) (plans.Throttle, bool) { |
| + f := e.planThrottle.Load() |
| + if f == nil || up.route.Kind != "instance" { |
| + return plans.Throttle{}, false |
| + } |
| + if _, door := doorCallerFrom(r.Context()); door || hopDoorFrom(r.Context()) || fromTunnel(r.Context()) { |
| + return plans.Throttle{}, false |
| + } |
| + return (*f)(up.route) |
| +} |
| + |
| +// planThrottleAdmit spends one token of a throttled account's shared |
| +// bucket. It is a plan stage, not abuse protection, so it refuses whatever |
| +// CARLOS_RATE_LIMIT says. When ok is false the 429 is written. |
| +func (e *Edge) planThrottleAdmit(w http.ResponseWriter, r *http.Request, up upstream) bool { |
| + if _, on := e.planThrottleOf(r, up); !on { |
| + return true |
| + } |
| + eff := ratelimit.Effective{Base: plans.ThrottleRule} |
| + _, d, retryAfter := e.planLimiter.Admit("plan:"+release.RouteAccount(up.route), eff, planThrottleBucket, "", false, false) |
| + if d == ratelimit.Allow { |
| + return true |
| + } |
| + e.notePlanThrottled(up.route, "a request") |
| + writeRateLimited(w, retryAfter) |
| + return false |
| +} |
| + |
| +// planUpgradeAdmit is planThrottleAdmit for an upgrade: an awake-throttled |
| +// account opens no new connection that would hold its apps awake. |
| +func (e *Edge) planUpgradeAdmit(w http.ResponseWriter, r *http.Request, up upstream) bool { |
| + if th, on := e.planThrottleOf(r, up); on && th.Awake { |
| + e.notePlanThrottled(up.route, "an upgrade") |
| + writeRateLimited(w, 60e9) |
| + return false |
| + } |
| + return e.planThrottleAdmit(w, r, up) |
| +} |
| + |
| +// trackUpgrade makes an upgrade's connection closable by its account |
| +// (CloseAccountUpgrades): the proxy ends an upgraded connection when its |
| +// request context is done. Only for an account plans govern, so a box or |
| +// account without plans keeps its request exactly as it was. The caller |
| +// registers BEFORE asking the throttle (Astra plans-4c finding 2): the host |
| +// publishes a throttle and then closes, so either this request sees the |
| +// throttle, or it is registered when the close comes. |
| +func (e *Edge) trackUpgrade(r *http.Request, up upstream) (*http.Request, func()) { |
| + g := e.planGoverned.Load() |
| + if g == nil || up.route.Kind != "instance" || !(*g)(up.route) { |
| + return r, func() {} |
| + } |
| + acct := release.RouteAccount(up.route) |
| + ctx, cancel := context.WithCancel(r.Context()) |
| + h := new(int) |
| + e.upgradesMu.Lock() |
| + if e.upgrades == nil { |
| + e.upgrades = map[string]map[*int]context.CancelFunc{} |
| + } |
| + if e.upgrades[acct] == nil { |
| + e.upgrades[acct] = map[*int]context.CancelFunc{} |
| + } |
| + e.upgrades[acct][h] = cancel |
| + e.upgradesMu.Unlock() |
| + return r.WithContext(ctx), func() { |
| + e.upgradesMu.Lock() |
| + delete(e.upgrades[acct], h) |
| + if len(e.upgrades[acct]) == 0 { |
| + delete(e.upgrades, acct) |
| + } |
| + e.upgradesMu.Unlock() |
| + cancel() |
| + } |
| +} |
| + |
| +// CloseAccountUpgrades ends every open upgraded connection of the account's |
| +// routes, and says how many (plans 4c: an account becomes awake-throttled). |
| +func (e *Edge) CloseAccountUpgrades(account string) int { |
| + e.upgradesMu.Lock() |
| + cancels := e.upgrades[account] |
| + delete(e.upgrades, account) |
| + e.upgradesMu.Unlock() |
| + for _, cancel := range cancels { |
| + cancel() |
| + } |
| + return len(cancels) |
| +} |
diff --git a/internal/edge/planthrottle_test.go b/internal/edge/planthrottle_test.go| new file mode 100644 |
| index 000000000..1a7b7b457 |
| --- /dev/null |
| +++ b/internal/edge/planthrottle_test.go |
| @@ -0,0 +1,251 @@ |
| +package edge |
| + |
| +import ( |
| + "bufio" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/plans" |
| + "github.com/carlosframework/platform/internal/ratelimit" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +const ( |
| + ptHost = "throttled.example" |
| + ptOtherHost = "other.example" |
| +) |
| + |
| +// throttleScene: two instances of two accounts behind one edge, the plan |
| +// throttle hook answering from on/awake for bdk, and a frozen clock for |
| +// the throttle's bucket so the rule is exact. |
| +func throttleScene(t *testing.T, on, awake *atomic.Bool, backend string) *rateScene { |
| + t.Helper() |
| + s := newRateScene(t, "", nil, |
| + registry.Route{Host: ptHost, Kind: "instance", Addr: backend, Status: "ready", App: "web", Account: "bdk"}, |
| + registry.Route{Host: ptOtherHost, Kind: "instance", Addr: backend, Status: "ready", App: "shop", Account: "bdm"}, |
| + ) |
| + frozen := time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC) |
| + s.e.planLimiter = ratelimit.NewLimiter(func() time.Time { return frozen }, 1000) |
| + s.e.SetPlanGovernedFor(func(rt registry.Route) bool { return rt.Account == "bdk" }) |
| + s.e.SetPlanThrottleFor(func(rt registry.Route) (plans.Throttle, bool) { |
| + if rt.Account != "bdk" || !on.Load() { |
| + return plans.Throttle{}, false |
| + } |
| + return plans.Throttle{Bandwidth: true, Awake: awake.Load(), Until: frozen.Add(time.Hour)}, true |
| + }) |
| + return s |
| +} |
| + |
| +func okBackend(t *testing.T) string { |
| + t.Helper() |
| + b := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "ok") })) |
| + t.Cleanup(b.Close) |
| + return b.Listener.Addr().String() |
| +} |
| + |
| +func TestThrottleRefusesPastTheRule(t *testing.T) { |
| + var on, awake atomic.Bool |
| + on.Store(true) |
| + s := throttleScene(t, &on, &awake, okBackend(t)) |
| + for i := 0; i < plans.ThrottleRule.Burst; i++ { |
| + wantOK(t, s.get(t, "203.0.113.1", ptHost, "/"), fmt.Sprintf("request %d within the burst", i)) |
| + } |
| + res := s.get(t, "203.0.113.9", ptHost, "/") // another client: the bucket is the account's |
| + if res.status != http.StatusTooManyRequests || res.header.Get("Retry-After") == "" || res.header.Get("Cache-Control") != "no-store" { |
| + t.Fatalf("past the throttle: %d %v, want a 429 with Retry-After and no-store (even in observe mode)", res.status, res.header) |
| + } |
| +} |
| + |
| +func TestThrottleIsPerAccount(t *testing.T) { |
| + var on, awake atomic.Bool |
| + on.Store(true) |
| + s := throttleScene(t, &on, &awake, okBackend(t)) |
| + for i := 0; i <= plans.ThrottleRule.Burst; i++ { |
| + s.get(t, "203.0.113.1", ptHost, "/") |
| + } |
| + for i := 0; i < 40; i++ { |
| + wantOK(t, s.get(t, "203.0.113.1", ptOtherHost, "/"), "another account's instance") |
| + } |
| +} |
| + |
| +func TestNoThrottleHookUnchanged(t *testing.T) { |
| + s := newRateScene(t, "", nil, registry.Route{Host: ptHost, Kind: "instance", Addr: okBackend(t), Status: "ready", App: "web", Account: "bdk"}) |
| + for i := 0; i < 60; i++ { |
| + wantOK(t, s.get(t, "203.0.113.1", ptHost, "/"), "no hook") |
| + } |
| +} |
| + |
| +// openSocket upgrades a raw connection to host and returns its reader. |
| +func openSocket(t *testing.T, s *rateScene, host string) (net.Conn, *bufio.Reader, int) { |
| + t.Helper() |
| + c, err := net.Dial("tcp", s.front.Listener.Addr().String()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { c.Close() }) |
| + c.SetDeadline(time.Now().Add(10 * time.Second)) |
| + fmt.Fprintf(c, "GET /socket HTTP/1.1\r\nHost: %s\r\n%s: 203.0.113.1\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n", host, rlPeerHeader) |
| + br := bufio.NewReader(c) |
| + resp, err := http.ReadResponse(br, nil) |
| + if err != nil { |
| + t.Fatalf("handshake: %v", err) |
| + } |
| + return c, br, resp.StatusCode |
| +} |
| + |
| +func TestAwakeThrottleClosesAndRefusesUpgrades(t *testing.T) { |
| + ws := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path != "/socket" { |
| + io.WriteString(w, "ok") |
| + return |
| + } |
| + conn, buf, err := w.(http.Hijacker).Hijack() |
| + if err != nil { |
| + return |
| + } |
| + defer conn.Close() |
| + buf.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n") |
| + buf.Flush() |
| + for { |
| + line, err := buf.ReadString('\n') |
| + if err != nil { |
| + return |
| + } |
| + buf.WriteString("echo:" + line) |
| + buf.Flush() |
| + } |
| + })) |
| + t.Cleanup(ws.Close) |
| + var on, awake atomic.Bool |
| + s := throttleScene(t, &on, &awake, ws.Listener.Addr().String()) |
| + |
| + c, br, status := openSocket(t, s, ptHost) |
| + if status != http.StatusSwitchingProtocols { |
| + t.Fatalf("handshake before the throttle = %d", status) |
| + } |
| + fmt.Fprint(c, "one\n") |
| + if line, err := br.ReadString('\n'); err != nil || line != "echo:one\n" { |
| + t.Fatalf("echo = %q, %v", line, err) |
| + } |
| + |
| + on.Store(true) |
| + awake.Store(true) |
| + if n := s.e.CloseAccountUpgrades("bdk"); n != 1 { |
| + t.Fatalf("CloseAccountUpgrades = %d, want 1", n) |
| + } |
| + fmt.Fprint(c, "two\n") |
| + if _, err := br.ReadString('\n'); err == nil { |
| + t.Fatal("the socket stayed open after the account was awake-throttled") |
| + } |
| + if _, _, status := openSocket(t, s, ptHost); status != http.StatusTooManyRequests { |
| + t.Fatalf("new upgrade while awake-throttled = %d, want 429", status) |
| + } |
| + wantOK(t, s.get(t, "203.0.113.1", ptHost, "/plain"), "a plain request while awake-throttled") |
| +} |
| + |
| +// Astra plans-4c finding 1: a cache hit spends the throttled account's |
| +// bucket too; the #358 limit still never limits a hit. |
| +func TestThrottleAppliesToCacheHits(t *testing.T) { |
| + ts, _ := countingUpstream(t, "cached page", map[string]string{"Cache-Control": "public, max-age=60"}) |
| + var on, awake atomic.Bool |
| + on.Store(true) |
| + s := throttleScene(t, &on, &awake, ts.Listener.Addr().String()) |
| + s.e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes)) |
| + for i := 0; i < plans.ThrottleRule.Burst; i++ { |
| + wantOK(t, s.get(t, "203.0.113.1", ptHost, "/page"), fmt.Sprintf("request %d within the burst", i)) |
| + } |
| + if res := s.get(t, "203.0.113.1", ptHost, "/page"); res.status != http.StatusTooManyRequests { |
| + t.Fatalf("a cache hit past the throttle: %d, want 429", res.status) |
| + } |
| +} |
| + |
| +// Finding 2: an upgrade is registered before the throttle is asked, so a |
| +// close that lands between the two still reaches it. |
| +func TestUpgradeRegisteredBeforeTheThrottleCheck(t *testing.T) { |
| + ws := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + conn, buf, err := w.(http.Hijacker).Hijack() |
| + if err != nil { |
| + return |
| + } |
| + defer conn.Close() |
| + buf.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n") |
| + buf.Flush() |
| + for { |
| + line, err := buf.ReadString('\n') |
| + if err != nil { |
| + return |
| + } |
| + buf.WriteString("echo:" + line) |
| + buf.Flush() |
| + } |
| + })) |
| + t.Cleanup(ws.Close) |
| + s := newRateScene(t, "", nil, registry.Route{Host: ptHost, Kind: "instance", Addr: ws.Listener.Addr().String(), Status: "ready", App: "web", Account: "bdk"}) |
| + s.e.SetPlanGovernedFor(func(registry.Route) bool { return true }) |
| + var once atomic.Bool |
| + s.e.SetPlanThrottleFor(func(rt registry.Route) (plans.Throttle, bool) { |
| + if once.CompareAndSwap(false, true) { |
| + // The host publishes an awake throttle and closes the account's |
| + // upgrades while this request is between registration and the |
| + // throttle check; this check still saw the old snapshot. |
| + s.e.CloseAccountUpgrades("bdk") |
| + } |
| + return plans.Throttle{}, false |
| + }) |
| + c, br, status := openSocket(t, s, ptHost) |
| + if status == http.StatusSwitchingProtocols { |
| + fmt.Fprint(c, "one\n") |
| + if line, err := br.ReadString('\n'); err == nil { |
| + t.Fatalf("the upgrade escaped the close: echoed %q", line) |
| + } |
| + } |
| +} |
| + |
| +// Finding 4: with plans off for the account nothing is tracked. |
| +func TestUpgradesUntrackedWhenNotGoverned(t *testing.T) { |
| + ws := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + conn, buf, err := w.(http.Hijacker).Hijack() |
| + if err != nil { |
| + return |
| + } |
| + defer conn.Close() |
| + buf.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n") |
| + buf.Flush() |
| + io.Copy(io.Discard, buf) |
| + })) |
| + t.Cleanup(ws.Close) |
| + s := newRateScene(t, "", nil, registry.Route{Host: ptHost, Kind: "instance", Addr: ws.Listener.Addr().String(), Status: "ready", App: "web", Account: "bdk"}) |
| + s.e.SetPlanThrottleFor(func(registry.Route) (plans.Throttle, bool) { return plans.Throttle{}, false }) |
| + s.e.SetPlanGovernedFor(func(registry.Route) bool { return false }) |
| + if _, _, status := openSocket(t, s, ptHost); status != http.StatusSwitchingProtocols { |
| + t.Fatalf("handshake = %d", status) |
| + } |
| + s.e.upgradesMu.Lock() |
| + n := len(s.e.upgrades) |
| + s.e.upgradesMu.Unlock() |
| + if n != 0 { |
| + t.Fatalf("%d account(s) tracked with plans off", n) |
| + } |
| +} |
| + |
| +// Finding 5: a plan-throttle refusal is counted as its own reason. |
| +func TestPlanThrottleRefusalCounted(t *testing.T) { |
| + var on, awake atomic.Bool |
| + on.Store(true) |
| + s := throttleScene(t, &on, &awake, okBackend(t)) |
| + m := NewUsageMeter() |
| + s.e.EnableUsage(m) |
| + for i := 0; i <= plans.ThrottleRule.Burst; i++ { |
| + s.get(t, "203.0.113.1", ptHost, "/") |
| + } |
| + row := m.Drain()[ptHost] |
| + if row.PlanThrottled != 1 || row.RateShed != 0 || row.RateCeiling != 0 { |
| + t.Fatalf("row = %+v, want one plan-throttle refusal and no #358 counts", row) |
| + } |
| +} |
diff --git a/internal/edge/usagemeter.go b/internal/edge/usagemeter.go| index 41cf2b038..869fa25e7 100644 |
| --- a/internal/edge/usagemeter.go |
| +++ b/internal/edge/usagemeter.go |
| @@ -68,6 +68,17 @@ func (u *UsageMeter) RecordRateLimited(rt registry.Route, d ratelimit.Decision) |
| u.mu.Unlock() |
| } |
| +// RecordPlanThrottled counts one request refused because rt's account is |
| +// slowed down by its plan (plans 4c). |
| +func (u *UsageMeter) RecordPlanThrottled(rt registry.Route) { |
| + u.mu.Lock() |
| + row := u.m[rt.Host] |
| + row.SetOwner(release.RouteAccount(rt), rt.App) |
| + row.PlanThrottled++ |
| + u.m[rt.Host] = row |
| + u.mu.Unlock() |
| +} |
| + |
| // Drain returns the accumulated rows and resets the meter. |
| func (u *UsageMeter) Drain() map[string]usage.EdgeRow { |
| u.mu.Lock() |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index e07a918bb..4f78e06ed 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -500,6 +500,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| // plans off (no marker, CARLOS_PLAN_LIMITS=off, or no record) the hook |
| // answers 0 and every window is the box's own. |
| svc.SetIdleFor(planIdleFor) |
| + svc.SetMaxRunFor(planMaxRunFor) // plans 4c: the continuous-awake ceiling |
| // Settings spec §4.2: before any process runs a build against an |
| // instance's database, the build state names it, under the lease. A |
| // store that failed to start refuses every spawn (never "run |
| @@ -944,6 +945,17 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| // activator's idle hook reads, so a box without a plan catalog gets |
| // the zero Ceiling and no extra reads. |
| e.SetRateCeilingFor(planRateCeilingFor) |
| + // The plan throttle (plans 4c), from the same snapshot: a slowed |
| + // account's shared bucket, and its open upgrades closed when it |
| + // becomes awake-throttled. |
| + e.SetPlanThrottleFor(planThrottleFor) |
| + e.SetPlanGovernedFor(planGoverned) |
| + closeUpgrades := func(sqid string) { |
| + if n := e.CloseAccountUpgrades(sqid); n > 0 { |
| + log.Printf("agent: plan throttle: closed %d open connection(s) of account %s", n, sqid) |
| + } |
| + } |
| + planAwakeThrottled.Store(&closeUpgrades) |
| // Same arming point as the meter: the edge observes an upstream 5xx |
| // on the serving path and files it here (spec 2026-09-07 §3.2), and |
| // errshipLoop above ships what this fills. Guarded, because a typed |
diff --git a/internal/host/plans_pass.go b/internal/host/plans_pass.go| index 4130da030..efd496870 100644 |
| --- a/internal/host/plans_pass.go |
| +++ b/internal/host/plans_pass.go |
| @@ -28,6 +28,9 @@ import ( |
| // are off on this box. |
| type planLimitsSnapshot struct { |
| byAccount map[string]plans.Limits |
| + // throttle is each account's plan throttle as published (plans 4c); |
| + // readers check Active, so an expired one slows nothing. |
| + throttle map[string]plans.Throttle |
| } |
| var planLimits atomic.Pointer[planLimitsSnapshot] |
| @@ -87,7 +90,7 @@ func plansPass(ctx context.Context, s release.Store, reg *registry.Registry, get |
| return |
| } |
| prev := planLimits.Load() |
| - next := &planLimitsSnapshot{byAccount: map[string]plans.Limits{}} |
| + next := &planLimitsSnapshot{byAccount: map[string]plans.Limits{}, throttle: map[string]plans.Throttle{}} |
| seen := map[string]bool{} |
| failed := false |
| for _, rt := range routes { |
| @@ -108,15 +111,48 @@ func plansPass(ctx context.Context, s release.Store, reg *registry.Registry, get |
| if l, ok := prev.byAccount[sqid]; ok { |
| next.byAccount[sqid] = l |
| } |
| + if th, ok := prev.throttle[sqid]; ok { |
| + next.throttle[sqid] = th |
| + } |
| } |
| case rec != nil: |
| next.byAccount[sqid] = rec.Limits |
| + if rec.Throttle != nil { |
| + next.throttle[sqid] = *rec.Throttle |
| + } |
| } |
| } |
| planLimits.Store(next) |
| if !failed { |
| planLimitsFailures.Store(0) |
| } |
| + notifyAwakeThrottled(prev, next) |
| +} |
| + |
| +// planAwakeThrottled is told each account that has just become |
| +// awake-throttled, so the edge can close its open upgrades (plans 4c). |
| +// Armed by the agent with the edge; nil does nothing. |
| +var planAwakeThrottled atomic.Pointer[func(sqid string)] |
| + |
| +// notifyAwakeThrottled calls planAwakeThrottled for each account whose |
| +// awake throttle is in force in next and was not in prev. |
| +func notifyAwakeThrottled(prev, next *planLimitsSnapshot) { |
| + f := planAwakeThrottled.Load() |
| + if f == nil || next == nil { |
| + return |
| + } |
| + now := time.Now() |
| + for sqid, th := range next.throttle { |
| + if !th.Awake || !th.Active(now) { |
| + continue |
| + } |
| + if prev != nil { |
| + if was, ok := prev.throttle[sqid]; ok && was.Awake && was.Active(now) { |
| + continue |
| + } |
| + } |
| + (*f)(sqid) |
| + } |
| } |
| // planLimitsFailed logs the first failure of a run and every tenth after it. |
| @@ -147,3 +183,42 @@ func planRateCeilingFor(rt registry.Route) ratelimit.Ceiling { |
| } |
| return l.RateCeiling() |
| } |
| + |
| +// planAwakeCeiling is the continuous-awake ceiling for an awake-throttled |
| +// account's instances (spec §5.2). |
| +const planAwakeCeiling = 15 * time.Minute |
| + |
| +// planThrottleFor is the route's account's plan throttle when one is in |
| +// force: an instance route, plans on, a record with a throttle, before its |
| +// Until. Anything else is (zero, false). |
| +func planThrottleFor(rt registry.Route) (plans.Throttle, bool) { |
| + if rt.Kind != "instance" { |
| + return plans.Throttle{}, false |
| + } |
| + snap := planLimits.Load() |
| + if snap == nil { |
| + return plans.Throttle{}, false |
| + } |
| + th, ok := snap.throttle[release.RouteAccount(rt)] |
| + if !ok || !th.Active(time.Now()) { |
| + return plans.Throttle{}, false |
| + } |
| + return th, true |
| +} |
| + |
| +// planGoverned is whether plans govern the route's account on this box: |
| +// plans on and a limits record read. The edge tracks upgrades for closing |
| +// only then (Astra plans-4c finding 4). |
| +func planGoverned(rt registry.Route) bool { |
| + _, ok := planLimitsFor(release.RouteAccount(rt)) |
| + return ok |
| +} |
| + |
| +// planMaxRunFor is the activator's continuous-awake hook: 15 minutes for an |
| +// instance of an awake-throttled account, else 0 (no ceiling). |
| +func planMaxRunFor(rt registry.Route) time.Duration { |
| + if th, ok := planThrottleFor(rt); ok && th.Awake { |
| + return planAwakeCeiling |
| + } |
| + return 0 |
| +} |
diff --git a/internal/host/plans_throttle_test.go b/internal/host/plans_throttle_test.go| new file mode 100644 |
| index 000000000..cc1cd3b07 |
| --- /dev/null |
| +++ b/internal/host/plans_throttle_test.go |
| @@ -0,0 +1,131 @@ |
| +package host |
| + |
| +// Serial: these write the package-level plans cache. |
| + |
| +import ( |
| + "context" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/plans" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// putThrottledLimits writes sqid's record with a throttle. |
| +func putThrottledLimits(t *testing.T, s *plansCountingStore, sqid string, th *plans.Throttle) { |
| + t.Helper() |
| + ctx := context.Background() |
| + _, etag, err := plans.GetLimits(ctx, s, sqid) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r := &plans.Record{Account: sqid, CatalogID: "v1@0123456789ab", Plan: "free", Revision: 1, Throttle: th} |
| + if _, err := plans.PutLimits(ctx, s, r, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +var ( |
| + throttledRoute = registry.Route{Host: "a.example", Kind: "instance", Account: "bab", App: "web"} |
| + otherRoute = registry.Route{Host: "b.example", Kind: "instance", Account: "bdk", App: "shop"} |
| +) |
| + |
| +func TestPlansPassKeepsThrottle(t *testing.T) { |
| + s, reg := plansWorld(t) |
| + putMarker(t, s, true) |
| + putThrottledLimits(t, s, "bab", &plans.Throttle{Bandwidth: true, Until: time.Now().Add(24 * time.Hour)}) |
| + putAccountLimits(t, s, "bdk", 90) |
| + plansPass(context.Background(), s, reg, plansNoEnv) |
| + if th, ok := planThrottleFor(throttledRoute); !ok || !th.Bandwidth { |
| + t.Fatalf("bab throttle = %+v, %v", th, ok) |
| + } |
| + if _, ok := planThrottleFor(otherRoute); ok { |
| + t.Fatal("an unthrottled account is throttled") |
| + } |
| +} |
| + |
| +func TestExpiredThrottleIsIgnored(t *testing.T) { |
| + s, reg := plansWorld(t) |
| + putMarker(t, s, true) |
| + putThrottledLimits(t, s, "bab", &plans.Throttle{Bandwidth: true, Awake: true, Until: time.Now().Add(-time.Minute)}) |
| + plansPass(context.Background(), s, reg, plansNoEnv) |
| + if _, ok := planThrottleFor(throttledRoute); ok { |
| + t.Fatal("a throttle past Until still applies") |
| + } |
| + if d := planMaxRunFor(throttledRoute); d != 0 { |
| + t.Fatalf("an expired awake throttle gives a ceiling of %v", d) |
| + } |
| +} |
| + |
| +func TestPlanMaxRunFor(t *testing.T) { |
| + t.Cleanup(func() { planLimits.Store(nil) }) |
| + until := time.Now().Add(time.Hour) |
| + planLimits.Store(&planLimitsSnapshot{byAccount: map[string]plans.Limits{}, throttle: map[string]plans.Throttle{ |
| + "bab": {Awake: true, Until: until}, "bdk": {Bandwidth: true, Until: until}, |
| + }}) |
| + if d := planMaxRunFor(throttledRoute); d != 15*time.Minute { |
| + t.Fatalf("awake-throttled instance: %v, want 15m", d) |
| + } |
| + if d := planMaxRunFor(otherRoute); d != 0 { |
| + t.Fatalf("bandwidth-only throttle: %v, want 0", d) |
| + } |
| + worker := throttledRoute |
| + worker.Kind = "worker" |
| + if d := planMaxRunFor(worker); d != 0 { |
| + t.Fatalf("worker route: %v, want 0", d) |
| + } |
| +} |
| + |
| +func TestThrottleOffWithPlanLimitsOff(t *testing.T) { |
| + s, reg := plansWorld(t) |
| + putMarker(t, s, true) |
| + putThrottledLimits(t, s, "bab", &plans.Throttle{Bandwidth: true, Until: time.Now().Add(time.Hour)}) |
| + plansPass(context.Background(), s, reg, func(k string) string { |
| + if k == "CARLOS_PLAN_LIMITS" { |
| + return "off" |
| + } |
| + return "" |
| + }) |
| + if _, ok := planThrottleFor(throttledRoute); ok { |
| + t.Fatal("throttled with CARLOS_PLAN_LIMITS=off") |
| + } |
| +} |
| + |
| +// An account that becomes awake-throttled has its open upgrades closed, |
| +// once, on the pass that sees it first. |
| +func TestPlansPassClosesUpgradesWhenAwakeThrottled(t *testing.T) { |
| + s, reg := plansWorld(t) |
| + var closed []string |
| + f := func(sqid string) { closed = append(closed, sqid) } |
| + planAwakeThrottled.Store(&f) |
| + t.Cleanup(func() { planAwakeThrottled.Store(nil) }) |
| + putMarker(t, s, true) |
| + putThrottledLimits(t, s, "bab", &plans.Throttle{Bandwidth: true, Until: time.Now().Add(time.Hour)}) |
| + plansPass(context.Background(), s, reg, plansNoEnv) |
| + if len(closed) != 0 { |
| + t.Fatalf("a bandwidth-only throttle closed upgrades: %v", closed) |
| + } |
| + putThrottledLimits(t, s, "bab", &plans.Throttle{Awake: true, Until: time.Now().Add(time.Hour)}) |
| + plansPass(context.Background(), s, reg, plansNoEnv) |
| + plansPass(context.Background(), s, reg, plansNoEnv) |
| + if len(closed) != 1 || closed[0] != "bab" { |
| + t.Fatalf("closed = %v, want bab once", closed) |
| + } |
| +} |
| + |
| +// Finding 4: the edge tracks upgrades only for accounts plans govern. |
| +func TestPlanGoverned(t *testing.T) { |
| + s, reg := plansWorld(t) |
| + if planGoverned(throttledRoute) { |
| + t.Fatal("governed with plans off") |
| + } |
| + putMarker(t, s, true) |
| + putAccountLimits(t, s, "bab", 90) |
| + plansPass(context.Background(), s, reg, plansNoEnv) |
| + if !planGoverned(throttledRoute) { |
| + t.Fatal("an account with a limits record is not governed") |
| + } |
| + if planGoverned(otherRoute) { |
| + t.Fatal("an account without a record is governed") |
| + } |
| +} |
diff --git a/internal/plans/record.go b/internal/plans/record.go| index fd8314757..e5077ba7e 100644 |
| --- a/internal/plans/record.go |
| +++ b/internal/plans/record.go |
| @@ -29,6 +29,9 @@ type Record struct { |
| Revision int64 `json:"revision"` |
| Limits Limits `json:"limits"` |
| IssuedAt time.Time `json:"issued_at"` |
| + // Throttle, when set, slows the account for the rest of the month |
| + // (plans 4c). |
| + Throttle *Throttle `json:"throttle,omitempty"` |
| } |
| // LimitsKey is where an account's limits record lives. |
diff --git a/internal/plans/throttle.go b/internal/plans/throttle.go| new file mode 100644 |
| index 000000000..6c4d84f4b |
| --- /dev/null |
| +++ b/internal/plans/throttle.go |
| @@ -0,0 +1,28 @@ |
| +package plans |
| + |
| +import ( |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/ratelimit" |
| +) |
| + |
| +// Throttle is an account slowed down for the rest of the month (plans 4c, |
| +// spec §5.2 and §5.7): past its monthly bandwidth (Bandwidth) or awake |
| +// hours (Awake). The console sets it; boxes read it from the limits record |
| +// and drop it after Until, the first instant of the next UTC month, even |
| +// if the console has stopped writing. |
| +type Throttle struct { |
| + Bandwidth bool `json:"bandwidth,omitempty"` |
| + Awake bool `json:"awake,omitempty"` |
| + Until time.Time `json:"until"` |
| +} |
| + |
| +// Active is whether t slows anything at now. |
| +func (t *Throttle) Active(now time.Time) bool { |
| + return t != nil && (t.Bandwidth || t.Awake) && now.Before(t.Until) |
| +} |
| + |
| +// ThrottleRule is a throttled account's one shared request bucket across |
| +// all its instances: enough to load a page and read why, too little to run |
| +// a service (Paul, 2026-10-25). |
| +var ThrottleRule = ratelimit.Rule{Rate: 5, Burst: 30} |
diff --git a/internal/plans/throttle_test.go b/internal/plans/throttle_test.go| new file mode 100644 |
| index 000000000..66b0e917f |
| --- /dev/null |
| +++ b/internal/plans/throttle_test.go |
| @@ -0,0 +1,46 @@ |
| +package plans |
| + |
| +import ( |
| + "context" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func TestThrottleActive(t *testing.T) { |
| + now := time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC) |
| + until := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) |
| + var none *Throttle |
| + if none.Active(now) { |
| + t.Error("nil throttle active") |
| + } |
| + if !(&Throttle{Bandwidth: true, Until: until}).Active(now) { |
| + t.Error("bandwidth throttle before Until not active") |
| + } |
| + if (&Throttle{Awake: true, Until: until}).Active(until) { |
| + t.Error("throttle active at Until") |
| + } |
| + if (&Throttle{Until: until}).Active(now) { |
| + t.Error("throttle with neither flag active") |
| + } |
| +} |
| + |
| +func TestRecordRoundTripsThrottle(t *testing.T) { |
| + ctx := context.Background() |
| + s := release.NewDirStore(t.TempDir()) |
| + until := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) |
| + rec := &Record{Account: "abc", CatalogID: "c", Plan: "free", Source: "default", Revision: 1, |
| + Throttle: &Throttle{Awake: true, Until: until}} |
| + if _, err := PutLimits(ctx, s, rec, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, _, err := GetLimits(ctx, s, "abc") |
| + if err != nil || got.Throttle == nil || !got.Throttle.Awake || got.Throttle.Bandwidth || !got.Throttle.Until.Equal(until) { |
| + t.Fatalf("round trip = %+v, %v", got, err) |
| + } |
| + plain, err := ParseLimits([]byte(`{"schema":1,"account":"abc","catalog_id":"c","plan":"free","source":"default","revision":1,"limits":{}}`), "abc") |
| + if err != nil || plain.Throttle != nil { |
| + t.Fatalf("record without throttle = %+v, %v", plain, err) |
| + } |
| +} |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index f35c8e021..120ad9dbc 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -30,3 +30,5 @@ plan14-root-reads-static-sweep.tsv 5f9f8435788e8bdaa965e1dc68cfccd5264b2b2121366 |
| plan14-root-reads-edge-asset-cache-1-decisions.tsv 018230518ae9b9b3e8df2f651354f3955076046c15197838ae6a8a6903ab0250 |
| plan14-root-reads-edge-asset-cache-1.tsv 1199c91ebbfb03869e89d06798176598526e818d28c3032da070b1d4a4532b84 |
| plan14-root-reads-hunt-account-root-hardening.tsv ed721c45bf1af12467439061137d8c7a0757bc5ca1c921616ff42d5a7672d743 |
| +plan14-root-reads-plans-4c-units.tsv f6c05461d95d00fb468c5f580487de16370049b91963539546026cadadaa1c9d |
| +plan14-root-reads-plans-4c-box-throttle.tsv c71b2974cd929122afc730f22cb53c63f3fdefdb4b26f7ca60db76fface906de |
diff --git a/internal/provision/testdata/plan14-root-reads-plans-4c-box-throttle.tsv b/internal/provision/testdata/plan14-root-reads-plans-4c-box-throttle.tsv| new file mode 100644 |
| index 000000000..fa1145dfb |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-plans-4c-box-throttle.tsv |
| @@ -0,0 +1,20 @@ |
| +# Census overlay plans-4c-box-throttle, written by census-propose (#369). census-ruling-plans-4c-box-throttle, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-plans-4c-box-throttle.md. |
| +# 6 body, 1 sites, 6 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@legacy 1293418f63bd169e58e39135d25e13bf6a0d565408ab296a0a7dba4d56bea545 internal/console/accountplans.go Store.SetAccountPlan legacy accepted-legacy accepted-legacy;rev3=PROPOSED-design-plans-and-caps;basis=root-input; console SQL on its own account_plans table, as its store siblings (J4).;rev3=census-ruling-plans-4c-box-throttle;basis=the upsert also clears the account's throttle (plans 4c, Astra finding 3), so a plan change publishes without it. The same statement on the same table; no read added. file:QueryRow@442 d04a8612067805ec734be89e2395bcb4c98e9f0a7467551159d193dc903dad92 |
| +@legacy 46b871d05b4fb6fb8407e654f710bfb7b8cc4eff4d2437ba590868af7153825b internal/console/store.go Store.migrate legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-email-signin;identity=the console (cmd/console serve under console.service, user carlos-console);basis=adds the sessions.method column (default keymail, the backfill) and calls migrateEmailSignin; SQLite DDL on CONSOLE_DB; the existing site moves;rev3=census-ruling-plans-4-notices-grace;basis=calls migratePlanGrace last, which creates the console's own plan_cap_state table (plans 4a). No read added here; the new store units are the plans-4a-store decision.;rev3=census-ruling-plans-4c-box-throttle;basis=adds the additive account_plans.throttle column (plans 4c). No read added. file:Exec@12017,file:Exec@18238 a976387d28e2b337252ca60039236a457fb99efedb6dda8c377ae30810618969 |
| +@legacy 861cc1bdc7d7e5e75e572075e6e3a023fdffbc6c0cdd50599c19bba252434fa7 internal/edge/edge.go Edge.ServeHTTP legacy accepted-legacy accepted-legacy;rev3=census-ruling-seeded-instances;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body with the import gate checked after the door's scope and a gated row left out of the response cache; serving only;rev3=census-ruling-edge-request-records;basis=one more call in the observer defer, observeRecords(up.route, ...), passing on the route the defer already holds; no new kind of read;rev3=census-ruling-design-edge-rate-limit-358;basis=calls rateAdmit twice, and an admitted request holds a slot on both paths: on the upgrade path before the activator or proxy (the handshake holds its slot through slotWriter, given back at the first final answer or at the reverse proxy's hijack on a 101, so an open WebSocket is not counted; released by a defer), and on the ordinary path after the response-cache check and before the activator and proxy (an admitted request holds a slot through slotWriter, released by a defer); a refusal is a 429 written there and returns; the upgrade path's comment now names slotWriter as its one wrapper; one comment on the door mark reworded; read sites unchanged (22: main's 21 plus edge-request-records' observeRecords pass of the route), offsets moved; no read added;rev3=census-ruling-plans-4c-box-throttle;basis=calls planThrottleAdmit before the response cache, and on an upgrade trackUpgrade then planUpgradeAdmit (plans 4c, Astra findings 1 and 2); the new reads live in those units (plans-4c-units decision). The same read sites here. registry:Gate@13604,registry:Gate@13664,registry:Gate@13722,registry:Host@13707,registry:ImportGate@17917,registry:Kind@11787,registry:Kind@17888,whole:Route@10017,whole:Route@11790,whole:Route@12348,whole:Route@12443,whole:Route@12519,whole:Route@12563,whole:Route@13607,whole:Route@13667,whole:Route@13710,whole:Route@13725,whole:Route@15358,whole:Route@17891,whole:Route@17920,whole:Route@19752,whole:Route@9805 cfa604eaff1bcd14b46eb47275582f439c4ef6fbf361feca47d6ab50a699de8f |
| +@legacy 1c79743a0774549ee9a2cd99a5352366846efb032c6bdd3ee78eafdaca75eb94 internal/host/plans_pass.go plansPass legacy accepted-legacy accepted-legacy;rev3=PROPOSED-plans-2-box-limits;basis=root-route; the agent's plans pass, serialised by its own mutex, reads its own routes' accounts and two bucket objects (the plans marker, each account's limits record) into a cache; planIdleFor only narrows the activator's idle window. No root decision.;rev3=census-ruling-plans-4c-box-throttle;basis=keeps each account's published throttle from its limits record in the cache beside its limits, and tells planAwakeThrottled when an account first becomes awake-throttled (plans 4c). The same bucket objects; no read added. registry:Kind@817,whole:Route@803,whole:Route@886 dddd6f55b1b502736e025bafffeffdbfabaa65b81b23e5534ff780f70490e3f6 |
| +@legacy 481134ba0206cdd67e084f0d852cba1e584aab86190ad9d5f1c5aac6410210ca internal/activator/activator.go Service.sweepOnce legacy accepted-legacy accepted-legacy;rev3=PROPOSED-seed;basis=census-ruling-FS-R6; registry remains legacy; PROPOSED-plans-2-box-limits: the sweep also narrows an entry's idle window to its account's plan idle through the SetIdleFor hook (never lengthens it; always-on workers and held probe entries are untouched; the hibernate, inflight and held-for-tick guards are unchanged).;rev3=census-ruling-plans-4c-box-throttle;basis=after the worker max_run branch, stops a non-worker entry past the plans continuous-awake ceiling (maxRunFor, passed the row), busy or not, never mid-command (plans 4c). One more whole-row read: the row handed to the hook, as idleFor already is. This bypasses the inflight and held-for-tick protections the idle stop keeps, on purpose: escalated by Astra and ACCEPTED by Paul (census owner), 2026-10-25. registry:Hibernate@12971,registry:Hibernate@22142,registry:Hibernate@5124,registry:Hibernate@6794,registry:Hibernate@9319,registry:Host@22211,registry:Host@22269,registry:Host@22641,registry:Host@22734,registry:Host@23469,registry:Host@23551,registry:Host@24616,registry:Host@24795,registry:Host@24844,registry:NextDue@23424,registry:Status@22158,whole:Route@10074,whole:Route@12973,whole:Route@14906,whole:Route@16616,whole:Route@16806,whole:Route@17099,whole:Route@17271,whole:Route@17418,whole:Route@21629,whole:Route@23138,whole:Route@23478,whole:Route@23485,whole:Route@24431,whole:Route@24828,whole:Route@5126,whole:Route@6796,whole:Route@7230,whole:Route@9321 3180204acfaf05f0798b0e22bc2eda7e64b0375a4b1c1b62a09cd5c64fa7dab8 |
| +internal/activator/activator.go type Service authority B,C,D,F,J4 rev3=PROPOSED-seed; existing activator lifecycle and due-wake state plus owned seed exclusion and incarnation-keyed diagnostics; normal refusal and preparation ordering remain authoritative; PROPOSED-plans-2-box-limits adds the idleFor hook field, which only narrows idle windows;rev3=census-ruling-plans-4c-box-throttle;basis=gains the maxRunFor hook field beside idleFor (plans 4c). No read added. 88d6649cac4f1bc814ca926fb5e50fa0e6188b5b0c0ff5d13c0322d905aaa5ae |
| +internal/console/accountplans.go Store.SetAccountPlan legacy accepted-legacy accepted-legacy;rev3=PROPOSED-design-plans-and-caps;basis=root-input; console SQL on its own account_plans table, as its store siblings (J4).;rev3=census-ruling-plans-4c-box-throttle;basis=the upsert also clears the account's throttle (plans 4c, Astra finding 3), so a plan change publishes without it. The same statement on the same table; no read added. file:QueryRow@442 d04a8612067805ec734be89e2395bcb4c98e9f0a7467551159d193dc903dad92 |
| +internal/console/store.go Store.migrate legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-email-signin;identity=the console (cmd/console serve under console.service, user carlos-console);basis=adds the sessions.method column (default keymail, the backfill) and calls migrateEmailSignin; SQLite DDL on CONSOLE_DB; the existing site moves;rev3=census-ruling-plans-4-notices-grace;basis=calls migratePlanGrace last, which creates the console's own plan_cap_state table (plans 4a). No read added here; the new store units are the plans-4a-store decision.;rev3=census-ruling-plans-4c-box-throttle;basis=adds the additive account_plans.throttle column (plans 4c). No read added. file:Exec@12017,file:Exec@18238 a976387d28e2b337252ca60039236a457fb99efedb6dda8c377ae30810618969 |
| +internal/edge/edge.go Edge.ServeHTTP legacy accepted-legacy accepted-legacy;rev3=census-ruling-seeded-instances;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body with the import gate checked after the door's scope and a gated row left out of the response cache; serving only;rev3=census-ruling-edge-request-records;basis=one more call in the observer defer, observeRecords(up.route, ...), passing on the route the defer already holds; no new kind of read;rev3=census-ruling-design-edge-rate-limit-358;basis=calls rateAdmit twice, and an admitted request holds a slot on both paths: on the upgrade path before the activator or proxy (the handshake holds its slot through slotWriter, given back at the first final answer or at the reverse proxy's hijack on a 101, so an open WebSocket is not counted; released by a defer), and on the ordinary path after the response-cache check and before the activator and proxy (an admitted request holds a slot through slotWriter, released by a defer); a refusal is a 429 written there and returns; the upgrade path's comment now names slotWriter as its one wrapper; one comment on the door mark reworded; read sites unchanged (22: main's 21 plus edge-request-records' observeRecords pass of the route), offsets moved; no read added;rev3=census-ruling-plans-4c-box-throttle;basis=calls planThrottleAdmit before the response cache, and on an upgrade trackUpgrade then planUpgradeAdmit (plans 4c, Astra findings 1 and 2); the new reads live in those units (plans-4c-units decision). The same read sites here. registry:Gate@13604,registry:Gate@13664,registry:Gate@13722,registry:Host@13707,registry:ImportGate@17917,registry:Kind@11787,registry:Kind@17888,whole:Route@10017,whole:Route@11790,whole:Route@12348,whole:Route@12443,whole:Route@12519,whole:Route@12563,whole:Route@13607,whole:Route@13667,whole:Route@13710,whole:Route@13725,whole:Route@15358,whole:Route@17891,whole:Route@17920,whole:Route@19752,whole:Route@9805 cfa604eaff1bcd14b46eb47275582f439c4ef6fbf361feca47d6ab50a699de8f |
| +internal/host/agent.go runAgent authority B,C,D,F rev3=census-ruling-seeded-instances;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body with wireSeedPlacement called in the activator start's Configure step, before armMovesPass, and the startup sweep's result stored for the import rollback in Recover; read sites unchanged, offsets moved; main's B,C,D,F authority retained PROPOSED E46: captured claim selection and root journal mutation; root RPC outside service host exclusion; SQL/route data never grants root authority. Executing identity: service controller; root for inventory/retirement callbacks.;rev3=PROPOSED-325;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=passes the agent's log sink to armRunsPass; reads unchanged;rev3=census-ruling-db-region-forward-1;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=arms the db-reads loop (armDBReads) beside armRunsPass in the activator start's Configure step; reads unchanged, offsets moved; main's authority retained;rev3=PROPOSED-s3-change-index;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=arms the change index (armChangeIndex) and starts the record view's backstop loop before the loops that read through it, and hands the edge the watch loader (edge.WithChangeWatch); read sites unchanged at the same offsets;rev3=census-ruling-edge-request-records;basis=builds the edge request recorder against the existing log sink and data dir (newRequestRecorder, passed os.Getenv and time.Now) and starts reqrecLoop on a minute ticker; no read added;rev3=census-ruling-design-edge-rate-limit-358;basis=arms the edge's plan rate-ceiling hook, e.SetRateCeilingFor(planRateCeilingFor), right after EnableUsage; read sites unchanged (5), offsets moved; no read added;rev3=census-ruling-edge-asset-cache-1;basis=starts edgesFileLoop with the activator's serving build (servingBuildOf(svc): ServingGen's build on a box with generations, nothing otherwise); read sites unchanged (5), none added;rev3=census-ruling-plans-4c-box-throttle;basis=arms svc.SetMaxRunFor(planMaxRunFor) beside SetIdleFor, and e.SetPlanThrottleFor(planThrottleFor), e.SetPlanGovernedFor(planGoverned) and the planAwakeThrottled close hook beside SetRateCeilingFor (plans 4c). No read added. file:Exec@13802,file:Open@731,registry:App@10065,whole:Route@10057,whole:Route@23594 d2f7bc2603d3d67ca7540741500ea65a2e641ed97dcc5b83372c5707219f42d9 |
| +internal/host/plans_pass.go plansPass legacy accepted-legacy accepted-legacy;rev3=PROPOSED-plans-2-box-limits;basis=root-route; the agent's plans pass, serialised by its own mutex, reads its own routes' accounts and two bucket objects (the plans marker, each account's limits record) into a cache; planIdleFor only narrows the activator's idle window. No root decision.;rev3=census-ruling-plans-4c-box-throttle;basis=keeps each account's published throttle from its limits record in the cache beside its limits, and tells planAwakeThrottled when an account first becomes awake-throttled (plans 4c). The same bucket objects; no read added. registry:Kind@817,whole:Route@803,whole:Route@886 dddd6f55b1b502736e025bafffeffdbfabaa65b81b23e5534ff780f70490e3f6 |
| +internal/activator/activator.go Service.sweepOnce legacy accepted-legacy accepted-legacy;rev3=PROPOSED-seed;basis=census-ruling-FS-R6; registry remains legacy; PROPOSED-plans-2-box-limits: the sweep also narrows an entry's idle window to its account's plan idle through the SetIdleFor hook (never lengthens it; always-on workers and held probe entries are untouched; the hibernate, inflight and held-for-tick guards are unchanged).;rev3=census-ruling-plans-4c-box-throttle;basis=after the worker max_run branch, stops a non-worker entry past the plans continuous-awake ceiling (maxRunFor, passed the row), busy or not, never mid-command (plans 4c). One more whole-row read: the row handed to the hook, as idleFor already is. This bypasses the inflight and held-for-tick protections the idle stop keeps, on purpose: escalated by Astra and ACCEPTED by Paul (census owner), 2026-10-25. registry:Hibernate@12971,registry:Hibernate@22142,registry:Hibernate@5124,registry:Hibernate@6794,registry:Hibernate@9319,registry:Host@22211,registry:Host@22269,registry:Host@22641,registry:Host@22734,registry:Host@23469,registry:Host@23551,registry:Host@24616,registry:Host@24795,registry:Host@24844,registry:NextDue@23424,registry:Status@22158,whole:Route@10074,whole:Route@12973,whole:Route@14906,whole:Route@16616,whole:Route@16806,whole:Route@17099,whole:Route@17271,whole:Route@17418,whole:Route@21629,whole:Route@23138,whole:Route@23478,whole:Route@23485,whole:Route@24431,whole:Route@24828,whole:Route@5126,whole:Route@6796,whole:Route@7230,whole:Route@9321 3180204acfaf05f0798b0e22bc2eda7e64b0375a4b1c1b62a09cd5c64fa7dab8 |
| +@coverage internal/activator 16c5cfa55eaf72198f6185406e0ab6fa95d7a9d9006cd89c87e28650b1992a6b |
| +@coverage internal/console 62e4a8807a7fae53a3f8923ba7ac6f0d0af447ece7379b8175a7bcc0c388a14a |
| +@coverage internal/edge a6ed5c973d7bb791fb887f159a1fd9e5cb2f35b3d5dc40bcf09399c4185bec44 |
| +@coverage internal/host 350eca1265c29c7beebe4925e3b01b1254a85889004e35197ec7b4d8bafa3352 |
| +@coverage internal/plans 69df5bdee2fff4d10a8ff01ba7d102f54ae1f9693fec3ac40506b80fb9805768 |
| +@coverage internal/usage 24f3a53a77464a2d2a3c439f4481c1784a1ef7782a1d5b5f578d7e44a4fe1107 |
diff --git a/internal/provision/testdata/plan14-root-reads-plans-4c-units.tsv b/internal/provision/testdata/plan14-root-reads-plans-4c-units.tsv| new file mode 100644 |
| index 000000000..bd40f19cb |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-plans-4c-units.tsv |
| @@ -0,0 +1,21 @@ |
| +# Census overlay plans-4c-units, written by hand: ten new units of the plan throttle (plans 4c), a decision. census-ruling-plans-4c-units; the card is docs/superpowers/notes/census-proposal-plans-4c-box-throttle.md. |
| +@legacy 9cff55a799d0e60ca9f87136ddacce145d9e906a708308e5241515caa81da999 internal/console/accountplans.go Store.SetAccountThrottle legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=root-input; console SQL on its own account_plans table, as its store siblings (J4); stores the account's plan throttle and bumps the revision the publish pass reads (plans 4c). file:Exec@259 ef845d77170669b221e19a6494f5a8f587ee966ae25425e2e7ff2912b0f29a5c |
| +@legacy 3f029515e7217870013d543067cda5f58779eb23a8af5f97bd062c7239546a34 internal/edge/planthrottle.go Edge.notePlanThrottled legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), serving only: counts one plan-throttle refusal on the usage meter (UsageMeter.RecordPlanThrottled, passed the row) and logs the row's host, throttled, as noteRateLimited does (plans 4c). registry:Host@172,registry:Host@220,whole:Route@132 0d7a8faf05ee9518e96cfd2350b1d4982b6b9d7764267276d409e0935008c997 |
| +@legacy 3cf6775da772ee264d7420254a80e8fa4ed062a4f44811b2e0924daef820767f internal/edge/planthrottle.go Edge.planThrottleAdmit legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), serving only: spends one token of a throttled account's shared in-memory bucket keyed 'plan:'+release.RouteAccount(row) and writes the rate limit's 429, counted through notePlanThrottled. Grants nothing (plans 4c). whole:Route@281,whole:Route@400 476886e9f06ff8b1e39cfe113f4b310636518fc58e683beb3827189edd6af8a5 |
| +@legacy 3d4c8b3684fb3838dadeaffe82b3f2bef7df3da18c572bfbf247f2b6016b494d internal/edge/planthrottle.go Edge.planThrottleOf legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), serving only: asks the plan throttle hook (planThrottleFor, passed the row) whether an instance row's account is slowed down; door, hop-door and tunnel callers exempt as from the rate limit; reads only the row's kind (plans 4c). registry:Kind@129,whole:Route@132,whole:Route@353 0158379953353dcd65e108eb8168e55cb8fe4171ebc7ba1d63cb41b7999a2bd9 |
| +@legacy 084b116f99077f9de68ac3d9de3dc91e4138ac7ea8abac04106794bc89c63b24 internal/edge/planthrottle.go Edge.planUpgradeAdmit legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), serving only: refuses a new upgrade for an awake-throttled account's instance row (the rate limit's 429, counted through notePlanThrottled), else planThrottleAdmit (plans 4c). whole:Route@173 b4921b4b5b07f8efe33b19fa770e5967d9d2d1fa52c5e9345c040c030c7bc9c2 |
| +@legacy 3403dcb7a90dc428c31f75b43faeaa38e06d639d8a74325f34f0f479a3307eb3 internal/edge/planthrottle.go Edge.trackUpgrade legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), serving only: for an instance row whose account plans govern (planGoverned, passed the row), wraps the upgrade request in a cancellable context registered under release.RouteAccount(row), so CloseAccountUpgrades can end it (plans 4c). registry:Kind@128,whole:Route@131,whole:Route@168,whole:Route@235 4ec05529f11871f7ec117adce005cecaa10486922dfc42395cf1ea849378c713 |
| +@legacy cacf061f941e1aff97f11a591b7bf0f93e2fcb18728b4d5fa22c5c6a597fb2b2 internal/edge/usagemeter.go UsageMeter.RecordPlanThrottled legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), serving only: RecordRateLimited's twin: adds one to the row's in-memory PlanThrottled counter, labelled with the row's account and app (plans 4c). registry:App@136,registry:Host@170,registry:Host@87,whole:Route@131 e2aa8eda9429824b36aa8313fa495ce718aedbda4d0a728e0b52e7fe3e8534bd |
| +@legacy d4f6b2f2bfed78a4306c87b30000cd1d17296a76acd934e547a36e7637c97847 internal/host/plans_pass.go planGoverned legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), as a hook armed in runAgent: planIdleFor's and planRateCeilingFor's twin, it reads the row's account (release.RouteAccount) and kind and the plans pass's in-memory cache; says whether the row's account has a limits record in the cache (plans on), so the edge tracks its upgrades only then. No root decision (plans 4c). whole:Route@89 7905844800553d44b33afe4f61c61199d075af6bc251da228cd5f9cdf16a5ae8 |
| +@legacy 5d88c05d4629f5bff8e2112acef89aa4aede8b28276bd324ce8307f43333c691 internal/host/plans_pass.go planMaxRunFor legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), as a hook armed in runAgent: planIdleFor's and planRateCeilingFor's twin, it reads the row's account (release.RouteAccount) and kind and the plans pass's in-memory cache; returns 15 minutes for an awake-throttled account's instance row, else 0, for the activator's continuous-awake ceiling. Only shortens; no root decision (plans 4c). whole:Route@84 66bab854b4d55d69b14dc3220bf42842e925054872848aff7644c1d0fd611256 |
| +@legacy 9e520471c29c0912e5b15071f0ea959411cc6f5d25970eb0c60ac948a9e2e387 internal/host/plans_pass.go planThrottleFor legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), as a hook armed in runAgent: planIdleFor's and planRateCeilingFor's twin, it reads the row's account (release.RouteAccount) and kind and the plans pass's in-memory cache; returns the account's published throttle while it is in force, for instance rows only. Only slows; no root decision (plans 4c). registry:Kind@69,whole:Route@256 e9d8aae73b5736f9d097d672e58442da5fbe993abf89d0747f12d4708fa22516 |
| +internal/console/accountplans.go Store.SetAccountThrottle legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=root-input; console SQL on its own account_plans table, as its store siblings (J4); stores the account's plan throttle and bumps the revision the publish pass reads (plans 4c). file:Exec@259 ef845d77170669b221e19a6494f5a8f587ee966ae25425e2e7ff2912b0f29a5c |
| +internal/edge/planthrottle.go Edge.notePlanThrottled legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), serving only: counts one plan-throttle refusal on the usage meter (UsageMeter.RecordPlanThrottled, passed the row) and logs the row's host, throttled, as noteRateLimited does (plans 4c). registry:Host@172,registry:Host@220,whole:Route@132 0d7a8faf05ee9518e96cfd2350b1d4982b6b9d7764267276d409e0935008c997 |
| +internal/edge/planthrottle.go Edge.planThrottleAdmit legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), serving only: spends one token of a throttled account's shared in-memory bucket keyed 'plan:'+release.RouteAccount(row) and writes the rate limit's 429, counted through notePlanThrottled. Grants nothing (plans 4c). whole:Route@281,whole:Route@400 476886e9f06ff8b1e39cfe113f4b310636518fc58e683beb3827189edd6af8a5 |
| +internal/edge/planthrottle.go Edge.planThrottleOf legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), serving only: asks the plan throttle hook (planThrottleFor, passed the row) whether an instance row's account is slowed down; door, hop-door and tunnel callers exempt as from the rate limit; reads only the row's kind (plans 4c). registry:Kind@129,whole:Route@132,whole:Route@353 0158379953353dcd65e108eb8168e55cb8fe4171ebc7ba1d63cb41b7999a2bd9 |
| +internal/edge/planthrottle.go Edge.planUpgradeAdmit legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), serving only: refuses a new upgrade for an awake-throttled account's instance row (the rate limit's 429, counted through notePlanThrottled), else planThrottleAdmit (plans 4c). whole:Route@173 b4921b4b5b07f8efe33b19fa770e5967d9d2d1fa52c5e9345c040c030c7bc9c2 |
| +internal/edge/planthrottle.go Edge.trackUpgrade legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), serving only: for an instance row whose account plans govern (planGoverned, passed the row), wraps the upgrade request in a cancellable context registered under release.RouteAccount(row), so CloseAccountUpgrades can end it (plans 4c). registry:Kind@128,whole:Route@131,whole:Route@168,whole:Route@235 4ec05529f11871f7ec117adce005cecaa10486922dfc42395cf1ea849378c713 |
| +internal/edge/usagemeter.go UsageMeter.RecordPlanThrottled legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), serving only: RecordRateLimited's twin: adds one to the row's in-memory PlanThrottled counter, labelled with the row's account and app (plans 4c). registry:App@136,registry:Host@170,registry:Host@87,whole:Route@131 e2aa8eda9429824b36aa8313fa495ce718aedbda4d0a728e0b52e7fe3e8534bd |
| +internal/host/plans_pass.go planGoverned legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), as a hook armed in runAgent: planIdleFor's and planRateCeilingFor's twin, it reads the row's account (release.RouteAccount) and kind and the plans pass's in-memory cache; says whether the row's account has a limits record in the cache (plans on), so the edge tracks its upgrades only then. No root decision (plans 4c). whole:Route@89 7905844800553d44b33afe4f61c61199d075af6bc251da228cd5f9cdf16a5ae8 |
| +internal/host/plans_pass.go planMaxRunFor legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), as a hook armed in runAgent: planIdleFor's and planRateCeilingFor's twin, it reads the row's account (release.RouteAccount) and kind and the plans pass's in-memory cache; returns 15 minutes for an awake-throttled account's instance row, else 0, for the activator's continuous-awake ceiling. Only shortens; no root decision (plans 4c). whole:Route@84 66bab854b4d55d69b14dc3220bf42842e925054872848aff7644c1d0fd611256 |
| +internal/host/plans_pass.go planThrottleFor legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4c-units;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), as a hook armed in runAgent: planIdleFor's and planRateCeilingFor's twin, it reads the row's account (release.RouteAccount) and kind and the plans pass's in-memory cache; returns the account's published throttle while it is in force, for instance rows only. Only slows; no root decision (plans 4c). registry:Kind@69,whole:Route@256 e9d8aae73b5736f9d097d672e58442da5fbe993abf89d0747f12d4708fa22516 |
diff --git a/internal/usage/edge.go b/internal/usage/edge.go| index 68ab20eb8..f37bc0987 100644 |
| --- a/internal/usage/edge.go |
| +++ b/internal/usage/edge.go |
| @@ -40,6 +40,10 @@ type EdgeRow struct { |
| // added to it. Additive and omitempty, for the hop counters' reason. |
| RateShed int64 `json:"rate_shed,omitempty"` |
| RateCeiling int64 `json:"rate_ceiling,omitempty"` |
| + // PlanThrottled counts requests refused because the account is slowed |
| + // down by its plan (plans 4c), apart from the per-instance rate limit's |
| + // two reasons. Inside Requests; additive and omitempty. |
| + PlanThrottled int64 `json:"plan_throttled,omitempty"` |
| } |
| // SetOwner labels the row with the route's current account and app. When |
| @@ -51,7 +55,7 @@ type EdgeRow struct { |
| // AddDeltas). |
| func (r *EdgeRow) SetOwner(account, app string) { |
| if r.Account != account || r.App != app { |
| - r.RateShed, r.RateCeiling = 0, 0 |
| + r.RateShed, r.RateCeiling, r.PlanThrottled = 0, 0, 0 |
| } |
| r.Account, r.App = account, app |
| } |
| @@ -102,6 +106,7 @@ func (d *EdgeDay) AddDeltas(hour string, deltas map[string]EdgeRow) { |
| row.HopBytesOut += delta.HopBytesOut |
| row.RateShed += delta.RateShed |
| row.RateCeiling += delta.RateCeiling |
| + row.PlanThrottled += delta.PlanThrottled |
| rows[host] = row |
| } |
| } |
diff --git a/internal/usage/edge_test.go b/internal/usage/edge_test.go| index 97f1a382f..c3393a437 100644 |
| --- a/internal/usage/edge_test.go |
| +++ b/internal/usage/edge_test.go |
| @@ -154,3 +154,17 @@ func TestUpsertEdgeDayEmptyDeltasIsNoop(t *testing.T) { |
| t.Fatalf("noop wrote %v", keys) |
| } |
| } |
| + |
| +func TestPlanThrottledSumsAndResetsWithOwner(t *testing.T) { |
| + var d EdgeDay |
| + d.AddDeltas("10", map[string]EdgeRow{"h": {Account: "bdk", App: "web", PlanThrottled: 2}}) |
| + d.AddDeltas("10", map[string]EdgeRow{"h": {Account: "bdk", App: "web", PlanThrottled: 3}}) |
| + if got := d.Hours["10"]["h"].PlanThrottled; got != 5 { |
| + t.Fatalf("summed = %d, want 5", got) |
| + } |
| + r := d.Hours["10"]["h"] |
| + r.SetOwner("bdm", "web") |
| + if r.PlanThrottled != 0 { |
| + t.Fatal("a new owner sees the old owner's plan-throttle count") |
| + } |
| +} |