Skip to content

perf(backend): bound the chat-quota month read to the current month - #11197

Merged
kodjima33 merged 1 commit into
mainfrom
issues-improver/9889-bounded-chat-quota-reads
Aug 7, 2026
Merged

kodjima33 merged 1 commit into
mainfrom
issues-improver/9889-bounded-chat-quota-reads

Conversation

@kodjima33

@kodjima33 kodjima33 commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

What

get_monthly_chat_usage — the chat-quota counter read — now issues one bounded
document-id range query over the current month instead of listing the account's
entire llm_usage collection and fetching the in-month days one at a time.

Why

This is not a reporting path. It runs inside enforce_chat_quota, so every
chat 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):

for doc in llm_usage_ref.list_documents():      # every day the account ever wrote
    if not doc.id.startswith(month_prefix):     # filtered client-side
        continue
    snap = doc.get()                            # one more RPC per in-month day

llm_usage holds one YYYY-MM-DD doc per day of activity, so both the reads and
the 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 many
questions 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) by
    document id — a single-field __name__ range, so no composite index (the
    firestore-query-coverage preflight check agrees).
  • The read is reported through the existing record_firestore_read telemetry as
    a new chat_quota_monthly_usage bounded family, matching how
    get_monthly_usage_stats_since and _read_all_time_usage already report — the
    per-family, no-user-content attribution Reduce Firestore query and listener read amplification #9889 wants.
  • _next_month() extracted so the query boundary and the reset_at boundary
    cannot 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 seeded llm_usage docs spanning 2025–2027 for one uid), executing
the old reader and the new one side by side:

now old new docs read
2026-08 28 questions / $2.75 28 / $2.75 61 → 5
2026-12 (Dec→Jan rollover) 38 questions 38 60 → 4
2024-03 (month with no data) 0 0 56 → 0

RESULT: PASS — identical totals, bounded reads. Boundary documents
2026-07-31, 2026-09-01 and 2027-01-01 stay excluded; 2026-08-01 and
2026-08-31 stay included.

Regression tests (backend/tests/unit/test_user_usage.py): the collection
fake now applies the real __name__ range filters instead of returning
everything, and raises if anything calls list_documents(), so an all-time scan
cannot come back unnoticed. Both new tests fail on the parent commit
(AssertionError: chat-quota reads must stay bounded to the current month) and
pass here.

The full suite also caught a first attempt that imported
google.cloud.firestore_v1.field_path: several backend tests stub
google.cloud.firestore_v1 as a plain module, so that submodule import broke
test_users_add_sample_transaction.py at import time. The field path is now
spelled literally ('__name__', which is exactly what FieldPath.document_id()
returns) and that file passes again.

Commands run:

  • pytest tests/unit/test_user_usage.py tests/unit/test_chat_quota.py → 27 passed
  • backend/test.sh (full, 841 files) → the 14 failing files are identical on
    this branch and on origin/main
    when 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/environment
    failures, none of them touched here)
  • backend/scripts/typecheck.sh → 0 errors
  • make preflight → 24 checks passed
  • black --line-length 120 --skip-string-normalization → clean

Refs #9889, #10950, #10817.

Auto-generated from issue feedback by the mini issues-improver — tested and merged.

Review in cubic

`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

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

No issues found across 3 files

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Re-trigger cubic

@kodjima33

Copy link
Copy Markdown
Collaborator Author

CI note: the one red check (Backend unit suite → tests/unit/test_kg_user_type_mismatch.py) is pre-existing on main, not from this PR.

  • This PR's run: 31196375116 — only test_kg_user_type_mismatch.py fails, with ModuleNotFoundError: No module named 'utils.conversations.transcript_for_llm' raised from utils/conversations/process_conversation.py:15.
  • main's own Backend Unit Tests run from before this branch existed, 31188359943, fails on the same single file with the same error.

Nothing in this diff touches utils/conversations/. Every other check on this PR is green (26 pass), including the firestore-query-coverage and backend-module-isolation manifest checks and the cubic review (no issues, 5/5).

Locally I also ran the full backend/test.sh on this branch and on a origin/main worktree with the same file list — identical failure sets, all environment/CPU-time-guard noise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant