ADR-0013: Plan quotas resolve from the plan, and the per-user blob is an override
- Status: Accepted
- Date: 2026-08-14
- Deciders: Cardsite platform team (workstream
001-renaissance, audit 02-D3)
Context
Fifteen quota keys are registered on PlanLimitService
(apps/api/cmd/server/main.go), ten handlers call it before a create, and an
exceeded quota answers 422 plan_limit_exceeded with the key, the current
count and the maximum. The admin plan API has bound settings — the plan's
JSONB blob — since the first migration. The admin plan form never offered
it: name, description, three prices, trial days, colour, status and sort
order, and nothing else. Audit 02-D3 recorded the consequence as plan limits
are reachable only by SQL.
Reachable only by SQL was the optimistic reading. Setting the quota by SQL does nothing either, because the two blobs are disjoint stores:
- The enforcement path never reads
plans.settings.PlanLimitServiceresolves a limit throughUserRepository.GetPlanSettings—SELECT COALESCE(plan_settings,'{}') FROM users WHERE user_id = $1. It reads the user row. - Nothing populates
users.plan_settingsfrom the plan. Not signup, notActivatePlan, not the payment webhook'sActivateUserPlan, not the admin user form, not the expiry cron. The single writer in 80,000 lines isAdminUpdateUserPlanSettings, the per-user override behindPUT /admin-api/v1/users/{id}/plan-settings. The column's own comment calls itself "the denormalised copy of the plan's quotas"; no code has ever made the copy. - A missing key means unlimited.
users.plan_settingsdefaults toNULL, so on a stock database every one of the fifteen quotas is inert, for every user, and always has been. The only limit that can fire today is one an operator typed into a single user by hand.
So 02-D3 is two defects, and the second decides the shape of the fix. A form
that writes plans.settings and nothing more would have been a control wired
to nothing — the fourth on record (AGENTS.md non-negotiable #7), and the one
with the worst failure mode of the four, because an operator who sets a limit
and is not refused believes the limit is holding.
Decision
A user's quotas are the plan's settings merged under their own
plan_settings, resolved per request. The plan states what the plan
includes; the user row states what this user was granted instead.
SELECT CASE WHEN jsonb_typeof(p.settings) = 'object' THEN p.settings ELSE '{}'::jsonb END
|| CASE WHEN jsonb_typeof(u.plan_settings) = 'object' THEN u.plan_settings ELSE '{}'::jsonb END
FROM users u LEFT JOIN plans p ON p.plan_id = u.plan_id
WHERE u.user_id = $1
jsonb || is right-biased, so the override wins key by key rather than blob
by blob: a user granted links_limit keeps the plan's domains_limit. There
is no copy to keep in step and nothing to re-sync, so an operator's edit
applies on the next request — the property the plan's verification section
demands in the words without a deploy.
Each side is guarded on being a JSON object, not merely on being non-NULL.
The first version of this used COALESCE, which is the obvious guard and the
wrong one: it catches SQL NULL and lets the JSON null scalar through, and
object || 'null'::jsonb answers a JSON array rather than failing.
JSONMap.Scan cannot read an array, the read returns an error, and check()
fails open — every quota off for that user, silently. That posture is right for
a database blip and wrong for a blob that will never parse, and the difference
is not visible at the call site, so it is closed at the read. It was reachable
without SQL: PUT /admin-api/v1/users/{id}/plan-settings with a null body
decoded into a nil map and stored the literal "null", answering 200. That
path refuses a non-object body now, and validates its quotas with the same
models.ValidatePlanQuotas the plan form uses — it matters more there, because
the override wins. The guard is what repairs the rows already written.
Four parts ship with it:
models.PlanQuotas— the registry: fourteen of the fifteen registered quotas, each with the label and one-line description the portal renders, served atGET /admin-api/v1/plans/quotasso the form is built from the registry and no page holds a hardcoded list of quota keys. Fourteen, not fifteen, for the reason under Consequences: a quota nothing checks is not offered.- The plan form gains a Plan limits section, rendered from that
endpoint, editing the blob it loaded so keys the registry does not know —
api_is_enabled,affiliate_commission_percentage— survive a save. - The write path validates. A registered quota key whose value is not an
integer between
-1and one billion is400— bounded above because enforcement narrows toint, and a value pastMaxInt64converts to a negative one, which reads as a limit ofmath.MinInt64and refuses every create on the plan. Before this,"links_limit": "five"was stored without complaint and read as unlimited: a plan that says one thing and enforces another. - A gate, in
scripts/check-entitlement-parity.mjsbeside the flag rules. A key enforced byplanLimitSvc.Registerwith no registry entry is a quota the portal cannot show; a registry entry with noRegistercall is a limit the portal offers that nothing counts; and a registry entry whoseCheck…method is never called from a handler is the same lie one layer further down — the rule that caught this slice's own first draft. All three fail the build.
What deliberately does not change: the fail-open behaviour when the read
errors (ADR-0011 records that asymmetry as intended), missing key means
unlimited, -1 as the explicit unlimited value, 0 as "refuse the first
create", and the precedence of a per-user override.
Consequences
- Quotas stop being inert. This is the point, and it is also a behaviour
change: an operator who set
plans.settingsby SQL at any point in the past had those limits ignored, and after this they apply. It is a release-note event, recorded on the ROADMAP as one. - Grandfathering is inherited, not built. Every registered quota is checked on create only, so rows already over a newly-effective limit stay readable, editable and deletable. Phase 02 task 3 will need the audit query the plan names before it gates anything on the write path more broadly; this slice needs no migration and no backfill.
- Legacy accounts are untouched.
users.plan_iddefaults to0and noplansrow has id0, so the join yields no plan and those users resolve to their own blob — exactly today's behaviour. Moving them onto a real plan row is an operator action, not a migration this slice can make on their behalf. - A registry entry is a promise the gate now has to keep. The first draft
of this slice listed
biolink_blocks_limit, whose counter is registered and whoseCheckBiolinkBlockshas never had a caller —BiolinkBlockHandlertakes noPlanLimiter. The portal would have rendered the field, saved the number, and gated nothing: this finding, reproduced inside its own fix. The key ships absent and the gate gained the rule that catches it (a registry key whose check is never called), so the registry is a list of quotas that are actually enforced rather than a list of quotas that exist. Wiring block creation is on the ROADMAP under LATER. - The AI quotas are not covered.
repository/ai.goreadsusers.plan_settingsdirectly forwords_per_month_limitand its four neighbours, on its own query. Same class, different path; recorded on the ROADMAP under LATER rather than folded in, because it is a second read path with its own semantics and folding it in would make this ADR unreviewable. GET /api/v1/account/planstill answers with the raw user blob.handlers/account.goreturnsuser.PlanSettings, so a user on a plan withlinks_limit: 5is told they have no limit and then refused at create. No page renders those values today, so nothing is visibly wrong, but an API consumer is now misinformed. It wants the same effective read; out of scope here because it is a response-shape change on a published endpoint.plan_id = 0is a convention, not a constraint. The claim that legacy accounts are untouched rests on noplansrow carrying id 0, and nothing enforces that — inserting one would apply its quotas to every legacy account at once. ACHECK (plan_id > 0)would make the claim true rather than customary, and needs a migration this slice does not take.AdminUsersPage's per-user override panel still carries a hand-written list of 27 keys, twelve of which noRegistercall exists for. The new gate does not police that file, because the per-user blob legitimately carries keys the quota registry does not define. It is now visibly the odd one out; recorded under LATER.
Alternatives considered
- Denormalise on write — fan
plans.settingsout to everyusersrow on plan save, and copy it at signup, activation, payment, admin edit and the expiry cron. Rejected: five write paths to keep in step forever, and it collides head-on with the per-user override the same column already carries — the save would have to decide, per key, whether a value there was a grant or a stale copy. A copy that must be re-synced is how the two stores diverged in the first place. - Leave the read path and have the form write per-user blobs — rejected: it turns a plan-level statement into a per-user chore and leaves the operator unable to say what a plan includes, which is phase 02's whole objective.
- Ship the form alone — rejected: it is the fourth dead subsystem, wearing a save button.
- Make a missing quota deny rather than allow — rejected here. The plan
names deny-by-default as the rule for capabilities (task 2, blocked on
decision 005); applying it to quotas would mean every install with an empty
settingsblob refuses every create the moment this ships.
Source: docs/decisions/0013-plan-quotas-resolve-from-the-plan.md