Repository navigation
fix(backend): deduplicate all-time usage reads - #11062
Conversation
Failure-Class: none
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
There was a problem hiding this comment.
2 issues found across 3 files
Confidence score: 4/5
- In
backend/database/user_usage.py, the new all-time read path bypasses the injectable Firestore client seam and relies on the module-globaldb, which makes tests and future integrations harder to isolate and increases coupling to legacy globals—accept afirestore_clientparameter (or thread the existing seam through) for this branch as well. - In
backend/database/user_usage.py, the new helper duplicatesget_yearly_historylogic while the updatedall_timebranch no longer usesget_yearly_history, creating a divergence risk where one path gets fixed and the other drifts—reuseget_yearly_historyfor aggregation or remove/replace the now-unreferenced path to keep a single source of truth.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/database/user_usage.py">
<violation number="1" location="backend/database/user_usage.py:442">
P3: The new helper duplicates the existing `get_yearly_history` aggregation, while the changed `all_time` branch no longer calls `get_yearly_history` and there are no other repository callers. This leaves the old function dead and creates two independent implementations of the same yearly-history logic, so future fixes can update one path while the other silently diverges. Consolidating the shared aggregation (for example, making `get_yearly_history` delegate to a shared helper or removing it after migrating callers) would keep the database layer maintainable.</violation>
<violation number="2" location="backend/database/user_usage.py:444">
P3: The new all-time read bypasses the backend’s injectable Firestore-client seam, forcing tests and future callers to patch the module-global legacy `db` proxy instead of supplying a fake client. Accept `firestore_client` on `_read_all_time_usage` (and thread it through its callers), resolving it with `get_firestore_client()` when omitted.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
|
|
||
| def _read_all_time_usage(uid: str) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: | ||
| """Read hourly usage once while building both the total and yearly history.""" | ||
| user_ref = db.collection('users').document(uid) |
There was a problem hiding this comment.
P3: The new all-time read bypasses the backend’s injectable Firestore-client seam, forcing tests and future callers to patch the module-global legacy db proxy instead of supplying a fake client. Accept firestore_client on _read_all_time_usage (and thread it through its callers), resolving it with get_firestore_client() when omitted.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/database/user_usage.py, line 444:
<comment>The new all-time read bypasses the backend’s injectable Firestore-client seam, forcing tests and future callers to patch the module-global legacy `db` proxy instead of supplying a fake client. Accept `firestore_client` on `_read_all_time_usage` (and thread it through its callers), resolving it with `get_firestore_client()` when omitted.</comment>
<file context>
@@ -440,6 +439,47 @@ def get_yearly_history(uid: str) -> List[Dict[str, Any]]:
+def _read_all_time_usage(uid: str) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]:
+ """Read hourly usage once while building both the total and yearly history."""
+ user_ref = db.collection('users').document(uid)
+ hourly_usage_collection = user_ref.collection('hourly_usage')
+ stats: Dict[str, Any] = {
</file context>
| return history | ||
|
|
||
|
|
||
| def _read_all_time_usage(uid: str) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: |
There was a problem hiding this comment.
P3: The new helper duplicates the existing get_yearly_history aggregation, while the changed all_time branch no longer calls get_yearly_history and there are no other repository callers. This leaves the old function dead and creates two independent implementations of the same yearly-history logic, so future fixes can update one path while the other silently diverges. Consolidating the shared aggregation (for example, making get_yearly_history delegate to a shared helper or removing it after migrating callers) would keep the database layer maintainable.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/database/user_usage.py, line 442:
<comment>The new helper duplicates the existing `get_yearly_history` aggregation, while the changed `all_time` branch no longer calls `get_yearly_history` and there are no other repository callers. This leaves the old function dead and creates two independent implementations of the same yearly-history logic, so future fixes can update one path while the other silently diverges. Consolidating the shared aggregation (for example, making `get_yearly_history` delegate to a shared helper or removing it after migrating callers) would keep the database layer maintainable.</comment>
<file context>
@@ -440,6 +439,47 @@ def get_yearly_history(uid: str) -> List[Dict[str, Any]]:
return history
+def _read_all_time_usage(uid: str) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]:
+ """Read hourly usage once while building both the total and yearly history."""
+ user_ref = db.collection('users').document(uid)
</file context>
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thanks for the focused fix here. I reviewed the current head and this looks directionally good to me: the all_time response path now streams hourly_usage once, derives both the aggregate totals and yearly history from that same pass, and records a low-cardinality all_time_usage read metric without user identifiers/content. The added unit test covers the important regression that totals/history come from one stream, and the backend checks are passing.
I don’t see a blocking implementation issue in this diff. Because this touches backend Firestore usage/metrics behavior, I’m leaving it as a maintainer-review signal rather than a formal approval.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
kodjima33
left a comment
There was a problem hiding this comment.
all_time usage streamed the full hourly_usage collection twice (totals + yearly history); now built from one stream with the same response shape. Unit tests green. 5/5 confidence - merging.
… dedup re-ported 22 upstream commits. New pure-logic module utils/memory/graph_enrichment.py (fenced canonical graph enrichment BasedHardware#11095) — no storage, no port needed. Two conflicts resolved keeping product logic verbatim, storage delta preserved: - database/user_usage.py: upstream's single-read all-time dedup (BasedHardware#11062) — _read_all_time_usage building total + yearly history in one pass — re-expressed on the store port (_store().query), not raw db.collection().stream(). - utils/memory/canonical_graph.py (auto-merged): upstream's catalog_nodes boundary (BasedHardware#11089) kept; storage stays document_store.query_collection (our delta). 0 raw firestore. Tests re-expressed on the neutral seam (no db_client, ADR-0028), no test removed: - test_knowledge_graph_canonical_pagination: adopts upstream's linked/unlinked catalog_nodes assertions via _fake_db_for (dropped the raw db_client _FakeDB setup). - test_user_usage: the all-time dedup test moved from the mock_db raw-Firestore fixture to the FakeDocumentStore store seam; kept the single-read invariant (record_firestore_read once, count 2), dropped the raw .stream() assertion. Audit ADR-0030: guard 0 · storage port byte-identical (empty diff on database/store/ + document_store.py) · sweep file-isolated 64/64 green · contract dual-backend 66 passed (Firestore emulator + Mongo real).
Summary
Fixes the all-time usage read amplification identified in #10950 and #9889.
GET /v1/users/me/usage?period=all_timepreviously streamed the completehourly_usagecollection once for aggregate totals and a second time for yearlyhistory. The duplicated unbounded read grew with every user's history and could
amplify Firestore document reads under concurrent usage-page traffic.
The endpoint now builds both response sections from one stream, preserving the
existing totals and history shape. It also records a low-cardinality
all_time_usageread family with only boundedness and document-count metrics,so future Firestore alerts can attribute this query family without logging user
content or identifiers.
This PR does not claim to identify the sole source of the production 10k/s alert;
the alert contains no query attribution. It removes one confirmed duplicate
read path and adds privacy-safe attribution for subsequent measurement.
Verification
python3 -m pytest backend/tests/unit/test_user_usage.py -qpython3 -m black --check --line-length 120 --skip-string-normalization backend/database/user_usage.py backend/database/firestore_read_metrics.py backend/tests/unit/test_user_usage.pypython3 backend/scripts/scan_async_blockers.py --dirs backend/routers backend/utilsInvariants
No product invariants are affected.
Failure-Class: none