Repository navigation
fix(billing): hold an AI call's share of the budget before it runs - #1387
Conversation
The workspace's one AI budget (Improve, the Content Editor's AI and the Action Center's task writer) had no meter: the first sign of it was an "AI usage is used up" error. Migration 00242 records what each AI call was for (prompt_improve_usage.feature, backfilled) and sums the period's spend by feature (ai_usage_by_feature). GET /api/billing/ai-usage returns the shares of the plan's budget, and the Billing page shows the share used, when it resets and what used it, with Agent Chat noted as running on the workspace's own key. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The workspace's AI budget was checked by reading the period's spend; the call's cost was written once the model answered. Calls running at once (two tabs, a teammate, an Action Center sweep) all read the same spend and all ran past the budget. 00243's reserve_ai_usage takes a per-organization lock, reads the spend with the calls in flight, and holds the call's estimated cost; reserveAiBudget turns the hold into the real cost or releases it. Improve, the brief rebuild, Apply rules with Agent, Start Agent and the Action Center task writer use it in place of enforceImproveQuota, which goes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
gkhngyk
left a comment
There was a problem hiding this comment.
One fix before merge; the core is right. The check and the hold are one locked step per organization: the advisory lock comes first, then a fresh read of the spend. Every caller lets the hold go in a finally, retries add rows instead of charging twice, and an unlimited budget holds nothing.
-
Content Agent and Start Agent still don't charge a schema miss. Improve, the brief rebuild and the task writer charge
err.usageonNoObjectGeneratedError.fixDraftRules(server/src/lib/content-agent.js:321-334) andrunDraftWriting(server/src/lib/content-writer.js:477-485) let the hold go instead. So an answer the provider billed runs free, and so does each retry after it. A full Start Agent page is the most expensive call on this budget.
Fix: in both, before the hold is let go,if (NoObjectGeneratedError.isInstance(err) && err.usage) await budget.charge(err.usage);. That needs a newcatchinfixDraftRules;runDraftWritingalready has one. -
The hold is about half of what these calls cost (optional).
p_cost: typicalCostUsd(modelId)(server/src/lib/plan-guard.js:378) holds 7k in / 2k out, which is $0.0095 on gemini-3-flash.- The usage rows so far average about $0.021 a call (about 6k output tokens) and reach $0.05.
- So each call in flight can still pass the budget by about $0.01.
Holding the org's recent median instead would close most of that, never less than
typicalCostUsd;improveSpendThisPeriodalready computes it. A leaked hold would then cost a little more, which still errs high.
Merge note: this conflicts with the open content PRs from #1371 up (#1371–#1374, #1383, #1384) in content-agent.js and content-writer.js, which still call enforceImproveQuota and recordUsage. Whichever lands second has to carry the hold over to the other's code. Apply 00242 before 00243: the function writes feature.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes: - Apply rules with Agent and Start Agent charge an answer the provider billed but that missed the schema (NoObjectGeneratedError), as Improve, the brief and the task writer do; before, the hold was let go and the call ran free. - A call holds the org's median cost over its last 20 calls this period, never less than the model's typical cost, so calls in flight pass the budget by far less. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@gkhngyk Both are in 0bfbb6a, on top of a merge of main (1539b5e). The content PRs from #1371 up landed first, so I carried the hold over to their code in that merge. Nothing calls
Server: 2,105 tests, lint and format pass. The PR body is updated, including the apply order 00242 → 00243. |
gkhngyk
left a comment
There was a problem hiding this comment.
Looks good. Both earlier items are fixed, and the merge of main carries the hold over to the content stack.
-
Schema miss: done.
fixDraftRules(server/src/lib/content-agent.js:530-534) andrunDraftWriting(server/src/lib/content-writer.js:502-505) chargeerr.usageonNoObjectGeneratedErrorbefore the hold is let go. The writer still endsfailed. Each has a test. -
Hold size: done.
holdCostUsd(server/src/lib/plan-guard.js:443-458) holds the org's median over its last 20 calls, never less thantypicalCostUsd, and falls back to the typical cost when the read fails.- The read is a backward scan of
prompt_improve_usage_org_used_idxthat stops after 20 rows, so its cost stays flat as the table grows. - Before this change, the check read up to 5,000 rows a call, so the path before each call is now cheaper.
- The read is a backward scan of
-
Merge 1539b5e: no hidden changes. Re-merging its parents conflicts in the five callers, their tests and
schema.sql. Each conflict was resolved to the hold:fixDraftRulesreads the link targets, then holds, then calls withlinkTargets.- The writer's suggestion run keeps main's link targets and charges the hold.
- The old
recordUsage/recordImproveUsagehelpers are gone. - The auto-merge also left two copies of
getAiUsage/AI_USAGE_FEATURESinplan-guard.js. The merge keeps main's copy.
Nothing in
server/srccallsenforceImproveQuotaor writesprompt_improve_usageoutsidereserveAiBudgetany more.
Optional follow-up: the header comment at server/src/lib/content-writer.js:35-37 still says "the budget is checked before a run, so runs started together could all pass it". It is out of date now that Start holds its share.
Summary
AI calls of one workspace that run at once can no longer overrun its AI budget: each call holds its share before it runs.
The gap.
enforceImproveQuotaread the period's spend, then the call ran, then its cost was written once the model answered. Calls running at once for one workspace all read the same spend and all ran, so the budget could be passed by as many calls as were in flight. That happens with two tabs, a teammate, or an Action Center sweep over several actions.Migration 00243:
reserve_ai_usage(org, since, budget, cost, feature, model, prompt/action/draft)typicalCostUsd). Calls average about twice that estimate and reach five times it. The read uses the existing(organization_id, used_at)index; when it fails, the server holds the typical cost.reserve_suggestion_relevance.Server:
reserveAiBudget(orgId, { feature, modelId, promptId | actionId | draftId })inplan-guard.jsPlanLimitError(429) once the budget is spent, with the same message as before.charge(usage): the first charge turns the hold into the real token cost; later attempts (retries, the task writer's second call) add their own rows. Write errors are logged, not thrown.release(): drops the hold when nothing was charged (a timeout, a refusal). Called in afinally.chargewrites rows as before.enforceImproveQuota+ the per-module usage inserts at all five callers:routes/prompts.js)improvewithRetrycontent-brief.js)contentcontent-agent.js)contentcontent-writer.js)contentaction_centerThe rule doesn't change. A call runs while the period's spend is under the budget. Only now the calls in flight count too.
NoObjectGeneratedError) is charged everywhere, as Improve's always was. Before this, the Content Agent and Start Agent let the hold go, so such a call and every retry after it ran free.enforceImproveQuotais removed: nothing calls it now.Deploy order
Apply 00243 before the server deploy. On a database without
reserve_ai_usage, every AI call on a paid plan would fail (the RPC is missing). The old read-only check let a call through on a read error; the hold doesn't.Verified on the dev DB:
Related issue
Sprint item "Billing AI usage meter + pre-reservation" (follows #1386). No issue.
Type of change
feat— New featurefix— Bug fixchore— Maintenance / dependenciesdocs— Documentation onlyrefactor— Code change that neither fixes a bug nor adds a featuretest— Adding or updating testsHow to test
select count(*) from prompt_improve_usage where …doesn't grow.Tests:
plan-guard-ai-budget.test.js:failed);Checklist
feature/,fix/,chore/,docs/) — see CONTRIBUTING.mdyarn lintpasses (run fromweb/): web not touchedyarn typecheckpasses (run fromweb/): web not touchedyarn format:checkpasses (run fromweb/): web not touchedAlso run:
npm run format,npm run lintandnpm test(2,105 tests);bash supabase/build-schema.sh.🤖 Generated with Claude Code