Repository navigation
perf(backend): bound the chat-quota month read to the current month - #11197
Merged
Merged
Conversation
`get_monthly_chat_usage` is called from `enforce_chat_quota`, so it runs on
every chat request (and from the overage check and `/v1/users/me/usage-quota`).
It listed every `llm_usage/{YYYY-MM-DD}` document the account had ever written,
filtered by date prefix in Python, then fetched each in-month day with its own
`get()`. Both the billed reads and the round-trips grew with account age: a
two-year daily-active account paid ~730 listed document ids plus ~30 sequential
fetches to answer "how many questions this month".
Replace that with a single document-id range query over
`[YYYY-MM-01, <next month>-01)` and record it as a bounded read family, matching
how `get_monthly_usage_stats_since` and `_read_all_time_usage` already report.
Same documents, same totals — only the read shape changes.
Verified against a real Firestore emulator (not a mock): seeded 56 llm_usage
docs spanning 2025-2027 and compared the old reader with the new one for
2026-08 (28 questions / $2.75, 61 docs read -> 5), the 2026-12 -> 2027-01
rollover (38 questions, 60 -> 4) and an empty month (0, 56 -> 0). Totals match
in all three; the July 31 / September 1 / January 1 boundary docs stay excluded.
Refs #9889, #10950, #10817
Collaborator
Author
|
CI note: the one red check (
Nothing in this diff touches Locally I also ran the full |
This was referenced Aug 9, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
get_monthly_chat_usage— the chat-quota counter read — now issues one boundeddocument-id range query over the current month instead of listing the account's
entire
llm_usagecollection and fetching the in-month days one at a time.Why
This is not a reporting path. It runs inside
enforce_chat_quota, so everychat request pays for it (
backend/routers/desktop_chat.py:1217,backend/routers/chat.py:299,586), plus the overage check(
backend/utils/overage.py:112) and/v1/users/me/usage-quota.The old shape (
backend/database/user_usage.py):llm_usageholds oneYYYY-MM-DDdoc per day of activity, so both the reads andthe round-trips grew with account age: a two-year daily-active account listed
~730 document ids and then made ~30 sequential
get()calls to answer "how manyquestions this month". New accounts are cheap; the longest-tenured, heaviest users
— the ones behind the read spikes in #10950 / #10817 — are charged the most per
message, and they pay it in latency on every send.
This is the "narrowly scoped first implementation" #9889 asks for, with the source
and measurement its last triage comment asked for before another change landed.
What changed
_current_month_llm_usage_docs()streams[YYYY-MM-01, <next month>-01)bydocument id — a single-field
__name__range, so no composite index (thefirestore-query-coveragepreflight check agrees).record_firestore_readtelemetry asa new
chat_quota_monthly_usagebounded family, matching howget_monthly_usage_stats_sinceand_read_all_time_usagealready report — theper-family, no-user-content attribution Reduce Firestore query and listener read amplification #9889 wants.
_next_month()extracted so the query boundary and thereset_atboundarycannot drift apart.
No change to which documents are summed or how their fields are interpreted.
Verification
Differential run against a real Firestore emulator (
gcloud emulators firestore, 56 seededllm_usagedocs spanning 2025–2027 for one uid), executingthe old reader and the new one side by side:
nowRESULT: PASS — identical totals, bounded reads. Boundary documents2026-07-31,2026-09-01and2027-01-01stay excluded;2026-08-01and2026-08-31stay included.Regression tests (
backend/tests/unit/test_user_usage.py): the collectionfake now applies the real
__name__range filters instead of returningeverything, and raises if anything calls
list_documents(), so an all-time scancannot come back unnoticed. Both new tests fail on the parent commit
(
AssertionError: chat-quota reads must stay bounded to the current month) andpass here.
The full suite also caught a first attempt that imported
google.cloud.firestore_v1.field_path: several backend tests stubgoogle.cloud.firestore_v1as a plain module, so that submodule import broketest_users_add_sample_transaction.pyat import time. The field path is nowspelled literally (
'__name__', which is exactly whatFieldPath.document_id()returns) and that file passes again.
Commands run:
pytest tests/unit/test_user_usage.py tests/unit/test_chat_quota.py→ 27 passedbackend/test.sh(full, 841 files) → the 14 failing files are identical onthis branch and on
origin/mainwhen re-run with the same runner(
test_agent_vm_startup,test_sync_v2,test_http_timeout_defaults,test_action_item_canonical_contract, … — local CPU-time guard/environmentfailures, none of them touched here)
backend/scripts/typecheck.sh→ 0 errorsmake preflight→ 24 checks passedblack --line-length 120 --skip-string-normalization→ cleanRefs #9889, #10950, #10817.
Auto-generated from issue feedback by the mini issues-improver — tested and merged.