Skip to content

fix(billing): hold an AI call's share of the budget before it runs - #1387

Merged
gkhngyk merged 4 commits into
ansvisor:mainfrom
cihan-gyk:feature/ai-budget-reservation
Oct 23, 2026
Merged

gkhngyk merged 4 commits into
ansvisor:mainfrom
cihan-gyk:feature/ai-budget-reservation

Conversation

@cihan-gyk

@cihan-gyk cihan-gyk commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator

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.

#1386 (the Billing AI usage meter, 00242) has merged and main is merged in. Apply 00242 before 00243: the function writes feature.

The gap. enforceImproveQuota read 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)

  • Takes a per-organization advisory lock and sums the period's spend, holds included.
  • While the spend is under the budget, it writes a row for the call at the cost the server holds and returns the row's id. Once the budget is spent it returns null.
  • The server holds the org's median cost over its last 20 calls this period, never less than the model's typical cost (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.
  • Service role only, as 00138's reserve_suggestion_relevance.

Server: reserveAiBudget(orgId, { feature, modelId, promptId | actionId | draftId }) in plan-guard.js

  • It throws PlanLimitError (429) once the budget is spent, with the same message as before.
  • It returns the call's meter:
    • 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 a finally.
  • An unlimited budget (self-hosted) holds nothing, and charge writes rows as before.
  • It replaces enforceImproveQuota + the per-module usage inserts at all five callers:
Caller Feature Hold
Improve (routes/prompts.js) improve up to 3 attempts via withRetry
Content brief rebuild (content-brief.js) content one call; a schema miss is charged
Apply rules with Agent (content-agent.js) content one call; a schema miss is charged
Start Agent (content-writer.js) content held in the request; charged or released when the background run ends; released if the start is refused (409); a schema miss is charged
Action Center task writer action_center one hold for both calls; a dry run holds nothing

The rule doesn't change. A call runs while the period's spend is under the budget. Only now the calls in flight count too.

  • A leaked hold (e.g. the server restarts mid-run) stays at its size: the org's recent median, at least ~$0.0095 on gemini-3-flash. So the budget errs high, never low. Such rows have a cost and null token counts.
  • The overrun is bounded. The most a budget can be passed by is the last accepted call plus (real − hold) of the calls in flight. Before, it was every call in flight. The writer already runs one draft per workspace at a time.
  • An answer the provider billed but that missed the schema (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.

enforceImproveQuota is 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:

  • Sequential holds pass while the spend is under the budget and are refused once it reaches it.
  • Two parallel sessions serialize: the second waits for the first's lock, sees its hold and is refused.
  • All of it was rolled back or deleted.

Related issue

Sprint item "Billing AI usage meter + pre-reservation" (follows #1386). No issue.

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

  1. Apply 00243.
  2. With an org close to its budget, run two AI actions at once (e.g. two Improve generations in two tabs).
    • Only one passes once the budget is reached; the other gets "This month's suggestion budget … is used up".
  3. Make a call fail (no provider key, or a timeout). Its hold is gone: select count(*) from prompt_improve_usage where … doesn't grow.

Tests:

  • plan-guard-ai-budget.test.js:
    • the RPC arguments;
    • the hold sized on the recent median, its floor, and the fallback when the read fails;
    • the first charge turning the hold into the real cost, and later charges adding rows;
    • release when nothing was charged, and not after a charge;
    • refusal at the budget, and unlimited budgets.
  • The five callers' tests:
    • the hold's arguments;
    • release on a model failure (agent, brief, writer run, task writer) and on a refused start (writer);
    • a schema miss charged once (agent, writer run; the writer still ends failed);
    • the task writer's two charges and the dry run.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/): web not touched
  • yarn typecheck passes (run from web/): web not touched
  • yarn format:check passes (run from web/): web not touched
  • Changes are focused — one concern per PR

Also run:

  • server npm run format, npm run lint and npm test (2,105 tests);
  • bash supabase/build-schema.sh.

🤖 Generated with Claude Code

cihan-gyk and others added 2 commits October 23, 2026 02:24
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]>
@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 22, 2026
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk The pre-reservation half of the Billing item, stacked on #1386. Please apply 00243 before the server deploy (every paid AI call goes through reserve_ai_usage now). Verified on dev with two parallel sessions: the second waits for the first's lock and is refused at the budget.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

  1. Content Agent and Start Agent still don't charge a schema miss. Improve, the brief rebuild and the task writer charge err.usage on NoObjectGeneratedError. fixDraftRules (server/src/lib/content-agent.js:321-334) and runDraftWriting (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 new catch in fixDraftRules; runDraftWriting already has one.

  2. 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; improveSpendThisPeriod already 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.

cihan-gyk and others added 2 commits October 23, 2026 09:52
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]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@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 enforceImproveQuota or recordUsage any more.

  1. Schema miss: fixDraftRules has a new catch that charges err.usage on NoObjectGeneratedError and rethrows, so the route still answers 502 failed. runDraftWriting's catch does the same before it marks the run failed. Tests check one charge each, and that the writer still ends failed.
  2. Hold size: holdCostUsd holds the org's median over its last 20 calls this period (RECENT_CALLS, shared with the Improve estimate), never less than typicalCostUsd. It falls back to the typical cost if the read fails. The read uses prompt_improve_usage_org_used_idx. Holds in flight count at their own size, so they don't push the median up.

Server: 2,105 tests, lint and format pass. The PR body is updated, including the apply order 00242 → 00243.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) and runDraftWriting (server/src/lib/content-writer.js:502-505) charge err.usage on NoObjectGeneratedError before the hold is let go. The writer still ends failed. 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 than typicalCostUsd, and falls back to the typical cost when the read fails.

    • The read is a backward scan of prompt_improve_usage_org_used_idx that 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.
  • 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:

    • fixDraftRules reads the link targets, then holds, then calls with linkTargets.
    • The writer's suggestion run keeps main's link targets and charges the hold.
    • The old recordUsage / recordImproveUsage helpers are gone.
    • The auto-merge also left two copies of getAiUsage / AI_USAGE_FEATURES in plan-guard.js. The merge keeps main's copy.

    Nothing in server/src calls enforceImproveQuota or writes prompt_improve_usage outside reserveAiBudget any 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.

@gkhngyk
gkhngyk merged commit e211d4d into ansvisor:main Oct 23, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants