Skip to content

fix(billing): chat refuses a request over the user's or company's budget before the LLM call (#16845) - #20589

Merged
mrveiss merged 7 commits into
mainfrom
issue-16845-chat-budget-stop
Nov 3, 2026
Merged

mrveiss merged 7 commits into
mainfrom
issue-16845-chat-budget-stop

Conversation

@mrveiss

@mrveiss mrveiss commented Nov 2, 2026 •

Copy link
Copy Markdown
Owner

Refs #16845

Thinking Path

Normal chat never reached the budget check, because that check needs an agent, and it pauses after the spend rather than refusing. The maintainer ruled the budget is checked before the chat LLM call, against the user's or company's budget, with a clear refusal. Per-tenant spend didn't exist, and chat records carried no user, so the first step was recording them. Reading the paths showed several set no LLM principal at all, which would have made the check a no-op there.

What Changed

  • services/chat_budget_gate.py: enforce_chat_budget looks up user and tenant policies against that scope's spend. pause and alert_then_pause policies refuse with a 402 carrying an i18n key; every refusal writes one audit event.
  • Called from LLMService.chat, chat_optimized and stream, the workflow's LLM iteration, both compat gateways, and the compare endpoint.
  • record_response_usage and record_token_usage default to the principal's user and add tenant spend under llm_cost:by_tenant.
  • The REST send route, transcript websocket, transcriber ask and graph resume now run under the principal. Resume previously left provider tokens unscoped too.
  • The REST reply and both transcript paths show the refusal instead of a generic failure, recognised by a marker in the response metadata, not by text.
  • Seeding happens once per tenant, by a marker, so a disabled or deleted default stays that way. A tenant with any policy no longer gets the monthly default.
  • chat_budget_bounds.py: timeout, a 5s spend cache so a refusal can lag by that much, and outage logging, all env-backed.
  • chat_optimized split to meet the function limit; services/llm_optimized_prompt.py is new. Ceilings lowered: llm_service.py, manager.py.

A user will notice:

  • A request at or over a pausing user or tenant policy is refused. The seeded $500 monthly policy names tenant "default"; login tokens carry a UUID org or none, so by reading the code it matches no token and stays inert. Not run.
  • Chat spend now appears under usage by user.
  • Spend inside a chat turn is attributed to that person, including non-chat calls in the turn.

Chosen, and open to reversal:

  • If the budget store is unavailable or the check exceeds its 2s timeout, the request is allowed and logged once per interval, as trigger_budget_evaluation does. The per-key check_budget fails closed instead. STORE_OUTAGE_ALLOWS_REQUEST in chat_budget_bounds.py flips it; the workflow would then show a generic error. Awaiting the maintainer.
  • 402, not the per-key route's 429, so OpenAI-style clients don't retry automatically.

Not covered, on purpose or not yet:

Lands after #20379 and #20401, which also change chat_workflow/manager.py.

Verification

From autobot-backend: pytest services/chat_budget_gate_entries_test.py services/chat_budget_gate_test.py services/llm_usage_recording_stream_test.py services/llm_usage_recording_test.py services/llm_spend_call_sites_test.py api/openai_compat_test.py tests/integration/test_budget_hard_stop.py api/chat_generate_ai_response_test.py: plus services/chat_budget_gate_bounds_test.py: 103 passed. repo_tests/i18n_untranslated_ratchet_test.py: 13 passed. Frontend specs for streamErrorText and locale parity pass. Removing each fix made its tests fail, apart from the transcriber/routes/ai.py catch and the anthropic gateway, which weren't mutated.

A code review found the compare bypass, the hourly over-refusal, the swallowed REST error and the transcript handling; all are fixed here.

Not verified: no live host run, so criterion 4 stays unticked and the issue stays open. chat_optimized has a source check only. The full REST send route and a refusal inside a full graph turn weren't run end to end. Other locales lack the new key, by the English-first rule.

Criterion 3: the per-conversation limiter stays unused, per the maintainer decision on the issue.

Model Used

Claude Sonnet 5.5 for implementation and review, Claude Opus 5.5 for direction.

🤖 Generated with Claude Code

…t is exhausted (#16845)

Budget policy only acted after spend on an agent, so a budget set for a user or company never stopped a chat request. A pre-call gate now reads the LLM principal, compares the user and tenant policies with that scope's spend and refuses with a 402 / error message carrying an i18n key. Chat spend is attributed to the principal's user and tenant so there is something to compare. Gate sits in LLMService chat/chat_optimized/stream, the workflow's ollama call and both compat gateways; each refusal is audited. An unreadable store allows the request and logs, as budget evaluation does. chat_optimized is split (prompt assembly, vLLM model lookup, post-call bookkeeping) to stay under the length limit.
Gate compare before its SSE stream; skip hourly policies until an hourly counter exists; mark budget refusals with an error_code so the REST send path and both transcript streams show the message instead of a generic retry or failure; key transcript spend and gate on the canonical principal id; run resumed graph turns under the caller's principal.
@mrveiss mrveiss added this to the M2 - Company OS workflow-ready milestone Nov 2, 2026
@mrveiss mrveiss added the phase:M2.6 Budgets enforced and costs recorded label Nov 2, 2026
@coderabbitai

coderabbitai Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 40 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration
Commits

Reviewing files that changed from the base of the PR and between 1416e3d and 435f2b0.

Files ignored due to path filters: 1
  • scripts/python_file_size_known_large.py is excluded by !scripts/python_file_size_known_large.py
Files selected for processing: 27
  • autobot-backend/api/anthropic_compat.py
  • autobot-backend/api/budget_policies.py
  • autobot-backend/api/chat.py
  • autobot-backend/api/chat_compare.py
  • autobot-backend/api/chat_streaming.py
  • autobot-backend/api/openai_compat.py
  • autobot-backend/api/transcripts.py
  • autobot-backend/chat_workflow/attachment_bounds_20195_test.py
  • autobot-backend/chat_workflow/budget_refusal.py
  • autobot-backend/chat_workflow/manager.py
  • autobot-backend/services/budget_policy.py
  • autobot-backend/services/chat_budget_bounds.py
  • autobot-backend/services/chat_budget_gate.py
  • autobot-backend/services/chat_budget_gate_bounds_test.py
  • autobot-backend/services/chat_budget_gate_entries_test.py
  • autobot-backend/services/chat_budget_gate_test.py
  • autobot-backend/services/llm_optimized_prompt.py
  • autobot-backend/services/llm_service.py
  • autobot-backend/services/llm_usage_recording.py
  • autobot-backend/transcriber/deps.py
  • autobot-backend/transcriber/routes/ai.py
  • autobot-frontend/src/i18n/locales/en.json
  • autobot-frontend/src/models/controllers/ChatController.ts
  • autobot-frontend/src/utils/__tests__/errorExtract.streamErrorText.spec.ts
  • autobot-frontend/src/utils/errorExtract.ts
  • autobot_shared/env_registry_rag.py
  • docs/developer/ENV_VARS.md
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Notice: 29 open PRs — past the runaway threshold (25)

This is not a request to defer this PR. There is no cap on open PRs (#19397) -- nothing blocks opening or pushing a PR.

This notice only means the count is high enough to be worth a glance for a runaway — something opening PRs in a loop, or a merge pipeline that has stalled so nothing is draining.

Currently open:

If the queue is draining normally, ignore this. Otherwise:

  1. Check whether CI is dispatching at all — see the ci-dispatch-watchdog status on these PRs
  2. Approved PRs land through the merge train the coordinator sequences (merge commits, never squash) -- check the open chore(merge-train) PR is moving, not each PR on its own
  3. Look for a loop opening near-identical PRs

Warn-only runaway detector — .github/workflows/pr-queue-gate.yml. It never blocks a merge.

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

✅ SSOT Configuration Compliance: Passing

🎉 No new hardcoded values of either class — ssot and other both block.

Known backlog in pipeline-scripts/hardcoded_values_baseline.txt is suppressed and tracked in #14371.

@mrveiss

mrveiss commented Nov 2, 2026

Copy link
Copy Markdown
Owner Author

Code review on PR #20589 (head 13b9a15): changes needed.

Read only; nothing was run. The gate reaches the workflow iteration, LLMService, compat gateways, compare, REST and resume; refusals are audited and reach the UI through an i18n key.

  • High, services/budget_policy.py:484-505 and initialization/lifespan.py:1057-1061: the seed check sees only enabled policies, so a disabled or deleted $500 policy returns enabled on the next start. It was inert before this PR and now blocks chat. Only a raised threshold survives.
  • Medium, chat_budget_gate.py:153-167: no timeout. A hung store delays every turn and every tool-loop iteration rather than failing open, and each check reads up to 31 daily keys per monthly policy. Bound it, and cache for a few seconds.
  • Medium, chat_workflow: _process_single_llm_iteration is gated but records no spend, per its self-hosted exemption (bug(billing): three live LLM call sites bypass spend recording entirely #16924). The cap therefore counts other paths only, and a metered endpoint on this path would be gated but unmetered.

Owner decisions, not in the ruling: whether a dormant org-wide $500 monthly cap should go live on existing installs (the counter starts at $0 at deploy, so no immediate stop, and users get no warning before refusal); and fail open versus closed on a store outage, since the per-key check_budget fails closed, the opposite. logger.exception per call would also flood the log during an outage.

Low: period and scope are English words inside the translated string; a token with no org_id isn't checked at tenant scope, and whether default-install tokens carry default wasn't verified; the gate-call tests read source text.

… policy once (#16845)

The default tenant policy is seeded once per tenant (marker stored with the policies) so a disabled or deleted default stays gone. The gate's store reads are time-bounded, spend is cached per scope for a few seconds, failures are logged once per interval, and the outage decision lives in one named flag. The refusal sentence no longer embeds English scope/period words: they are i18n keys of their own. Workflow gate documents why it records no spend.
@mrveiss

mrveiss commented Nov 2, 2026

Copy link
Copy Markdown
Owner Author

Code review on PR #20589 (head e90b597): approve, with the store-outage behaviour awaiting the owner, currently allow, in one flag.

Read only; I didn't run the tests. The check is bounded by a timeout with cached spend, and seeding is once per tenant. By the author's reading, the seeded policy names tenant default while tokens carry a UUID org or none, so it stays inert unless a matching org exists. Low: the once-only marker is a Redis key, so after eviction a deleted default returns once; a disabled one doesn't.

@github-actions

github-actions Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Auto-sync: merging main into issue-16845-chat-budget-stop conflicts

The sync aborted the merge and pushed nothing. Conflicts are information, so it never resolves one itself. Below, for each conflicted file, are the commits that touched it on each side since the merge base 87eae8acf8. Merge main in yourself and push; the label clears on the first run that finds this branch 0 behind.

repo_tests/i18n_untranslated_ratchet_test.py

side commit subject issue refs
main fd42d03b5 Merge #20543 @ d1d1a11 into the merge train #20543
main f8e3fb9fa test(i18n): record the English-only key the pattern analysis error adds (#17651) #17651
main 42d3afc4a test(i18n): record the English-only key the analytics load failure adds (#17651) #17651
this branch 13b9a15f3 chore(guards): the untranslated baseline counts the one new English-only budget key (#16845) #16845

@github-actions github-actions Bot added the sync-conflict Set by the branch sync (#19548) label Nov 2, 2026
…et-stop

# Conflicts:
#	repo_tests/slm_node_id_one_home_19322_test.py
@github-actions github-actions Bot removed the sync-conflict Set by the branch sync (#19548) label Nov 2, 2026
… attachment verdict and the caller's budget scope (#16845)
@mrveiss

mrveiss commented Nov 3, 2026

Copy link
Copy Markdown
Owner Author

Code review on PR #20589 (head 435f2b0): approve.

Covers the merge of main on the resume path, read only. resume_graph runs the resumed stream inside llm_principal_scope_for(auth_scope) (manager.py:3745-3749). The one production caller passes both the attachment verdict and auth_scope (chat_streaming.py:168), and chat.py keeps no duplicate of _stream_graph_resume. The changed tests only update signatures and stubs; their assertions are unchanged.

Not checked: the rest of the ~100 merged files beyond the resume path.

mrveiss added a commit that referenced this pull request Nov 3, 2026
…ew module, and the error params spread drops its empty fallback (#20589)
mrveiss added a commit that referenced this pull request Nov 3, 2026
@mrveiss
mrveiss merged commit 4808407 into main Nov 3, 2026
52 of 85 checks passed
@mrveiss
mrveiss deleted the issue-16845-chat-budget-stop branch November 3, 2026 16:54
timothybrush pushed a commit to timothybrush/AutoBot-AI that referenced this pull request Nov 3, 2026
…watchdog test uses the shared repo root, and the reach floors follow the merged tree (mrveiss#20589)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

phase:M2.6 Budgets enforced and costs recorded sync-conflict Set by the branch sync (#19548)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant