Skip to content

fix(backend): deduplicate all-time usage reads - #11062

Merged
kodjima33 merged 1 commit into
BasedHardware:mainfrom
aryanorastar:fix/10950-deduplicate-usage-reads
Aug 4, 2026
Merged

kodjima33 merged 1 commit into
BasedHardware:mainfrom
aryanorastar:fix/10950-deduplicate-usage-reads

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fixes the all-time usage read amplification identified in #10950 and #9889.

GET /v1/users/me/usage?period=all_time previously streamed the complete
hourly_usage collection once for aggregate totals and a second time for yearly
history. 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_usage read 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 -q
    • 8 tests passed.
  • python3 -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.py
    • Passed.
  • python3 backend/scripts/scan_async_blockers.py --dirs backend/routers backend/utils
    • Passed with zero selected blocking findings.

Invariants

No product invariants are affected.

Failure-Class: none

Review in cubic

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@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.

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-global db, which makes tests and future integrations harder to isolate and increases coupling to legacy globals—accept a firestore_client parameter (or thread the existing seam through) for this branch as well.
  • In backend/database/user_usage.py, the new helper duplicates get_yearly_history logic while the updated all_time branch no longer uses get_yearly_history, creating a divergence risk where one path gets fixed and the other drifts—reuse get_yearly_history for 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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]]]:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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 Git-on-my-level added needs-maintainer-review Needs a human maintainer to sign off before merge backend Backend Task (python) labels Aug 3, 2026

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

@kodjima33
kodjima33 merged commit 85ff626 into BasedHardware:main Aug 4, 2026
41 of 42 checks passed
abunet added a commit to abunet/omi that referenced this pull request Aug 4, 2026
… 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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants