Skip to content

SCA-458: cut Firestore memory unbounded queries and NOT_FOUND misses - #13233

Merged
Git-on-my-level merged 5 commits into
BasedHardware:mainfrom
Git-on-my-level:sca458/firestore-memory-query-fanout
Sep 9, 2026
Merged

Git-on-my-level merged 5 commits into
BasedHardware:mainfrom
Git-on-my-level:sca458/firestore-memory-query-fanout

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

Summary

Cuts two production Firestore bleed classes from the 2026-09-08 DATA_READ window (backend SA nik-164@):

  1. NOT_FOUND pair (~20.4M users/memory_items + ~20.5M users/memory_historical_overrides / day). canonical_statuses no longer get_alls override docs for IDs whose canonical item is present and parseable. Override reads run only for the missing-item subset. Search historical dedup uses that batch instead of per-match _canonical_status. Legacy append_commit still probes the override when the item is live (delete_batch writes suppression first).

  2. Unbounded memory QUERY on request paths. Chat/product search_canonical_memories hydrates merged_ids plus lineage pointers via fetch_authoritative_product_memory_items_by_ids instead of a full memory_items .stream(). count_memories_created keeps a date-range ID union when both stores have rows (no count()+count() double-count of dual-store IDs) and uses aggregation count() only when the other store is empty.

Also labels users/memories, users/candidates, users/knowledge_nodes, and users/knowledge_edges on omi_firestore_document_reads_total so the QUERY slice is not dumped into other. Knowledge-graph assertion loads now require scan_limit (GET already passed 500).

Addresses #11282 #9889
SCA-458

Does not close #9889 (broader epic). Does not close #11282: account_deletions NOT_FOUND (~4M/day) and other unbounded privacy/deletion scans are intentionally left alone.

Product invariants affected

  • INV-MEM-3
  • INV-MEM-4
  • INV-MEM-1

Path-matched (not intent-matched). This PR does not change tier inventory, promotion routes, or fail-open historical admission: present-but-unparseable canonical authority still 503s, and override-only tombstones still suppress.

503 vs suppression contract

Pinned in unit tests:

  • both item and override absent → historical admitted (not 503)
  • override present (item missing) → suppressed (hidden/404), not 503
  • item or override present but unparseable → 503, historical never admitted
  • item exists with valid status → no override read
  • malformed item + valid override → still 503 (override is not used to paper over a broken item)

memory_state/apply_control is not used as a "no overrides" selector. Historical-only privacy deletes write an override without apply-control.

Out of scope (deliberate)

  • No global Query.stream cap
  • No account_deletions skip / negative cache
  • No per-uid breaker
  • No ripple-index redesign
  • Privacy delete / account wipe paths still complete or fail loudly

Test plan

  • backend/.venv/bin/python -m pytest backend/tests/unit/test_universal_memory_service.py — triad, skip-override, batched search suppression
  • backend/.venv/bin/python -m pytest backend/tests/unit/test_ws_m_atom_keyword_index.py — product search hydrates candidate+lineage without full collection scan; supersede chain still collapses to the survivor
  • backend/.venv/bin/python -m pytest backend/tests/unit/test_memory_ledger.py — legacy commit skips override when item exists; override-only tombstone still fenced
  • backend/.venv/bin/python -m pytest backend/tests/unit/test_desktop_daily_usage.py — dual-store ID union still dedupes; SoT-only uses aggregation count
  • backend/.venv/bin/python -m pytest backend/tests/unit/test_firestore_document_probe.py — new collection patterns stay in the bounded label set
  • backend/.venv/bin/python -m pytest backend/tests/unit/test_memory_offset_read_cost.py backend/tests/unit/test_memory_graph_assertion_read.py backend/tests/unit/test_memory_visibility_export_fixes.py

Failure-Class

Failure-Class: none

Line-Count-Exception: backend/database/memories.py | 1527 -> 1560 | date-range existence probe plus SoT-only aggregation count without dual-store double-count
Line-Count-Exception: backend/utils/memory/memory_service.py | 4057 -> 4063 | skip override get_all except missing-item subset; batched search suppression

Review in cubic

Git-on-my-level and others added 4 commits September 8, 2026 18:09
Skip historical-override batch reads when the canonical item is present
and valid, hydrate chat search by candidate and lineage ids, and keep
dual-store daily counts as an ID union. Label the QUERY collections that
were collapsing into other.

Failure-Class: none
Co-authored-by: Cursor <[email protected]>
callable() narrowed the helper to object and pyright rejected .get().

Failure-Class: none
Co-authored-by: Cursor <[email protected]>
The suppressed-prefix walk is already grandfathered for the second test in
this file; the first test pays the same ~0.5s plus module-reload amortization.

Failure-Class: none
Co-authored-by: Cursor <[email protected]>

@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 13 files

Confidence score: 3/5

  • backend/utils/memory/canonical_memory_adapter.py can silently discard vector-only matches when keyword search returns 60 IDs, causing relevant results to be missing after hydration; preserve a bounded but complete merged candidate set or explicitly merge the result sets.
  • backend/tests/unit/test_desktop_daily_usage.py does not cover the legacy-only usage path when the canonical store is empty, leaving the if legacy_any counting behavior less protected; add a focused regression test for that branch.
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/utils/memory/canonical_memory_adapter.py">

<violation number="1" location="backend/utils/memory/canonical_memory_adapter.py:1000">
P2: When keyword search returns 60 IDs, vector-only matches are silently dropped before hydration, even though the vector query also returned them. Preserve a bounded but complete merged candidate set, or explicitly merge and rank both provider result sets before applying the cap.</violation>
</file>

<file name="backend/tests/unit/test_desktop_daily_usage.py">

<violation number="1" location="backend/tests/unit/test_desktop_daily_usage.py:155">
P3: The new tests cover the both-stores union and the legacy-empty case, but the symmetric branch where only the legacy store has rows (canonical empty) is untested. That branch has its own logic (`if legacy_any: counted = _aggregation_count(legacy_query)`) and a regression there would ship silently. Add a case with an empty canonical query and non-empty legacy query asserting the aggregation count path, mirroring the existing legacy-empty test.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread backend/database/memory_ledger.py Resolved

now = datetime.now(timezone.utc)
policy = MemoryAccessPolicy.for_omi_chat(archive_capability=False)
hydration = _hydrate_bounded_ledger_search_items(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: When keyword search returns 60 IDs, vector-only matches are silently dropped before hydration, even though the vector query also returned them. Preserve a bounded but complete merged candidate set, or explicitly merge and rank both provider result sets before applying the cap.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/memory/canonical_memory_adapter.py, line 1000:

<comment>When keyword search returns 60 IDs, vector-only matches are silently dropped before hydration, even though the vector query also returned them. Preserve a bounded but complete merged candidate set, or explicitly merge and rank both provider result sets before applying the cap.</comment>

<file context>
@@ -997,33 +997,23 @@ def search_canonical_memories(
 
     now = datetime.now(timezone.utc)
     policy = MemoryAccessPolicy.for_omi_chat(archive_capability=False)
+    hydration = _hydrate_bounded_ledger_search_items(
+        uid,
+        merged_ids,
</file context>

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Skipped. merge_memory_search_ids is pre-existing ranking (keyword first, then vector fill). This PR only changed hydration from a full memory_items stream to merged_ids + lineage IDs. Changing the merge order would be a search-quality change, not a read-cost cut.

Comment thread backend/database/memories.py Resolved

assert result == 3

def test_memories_created_uses_sot_count_when_legacy_store_is_empty():

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 tests cover the both-stores union and the legacy-empty case, but the symmetric branch where only the legacy store has rows (canonical empty) is untested. That branch has its own logic (if legacy_any: counted = _aggregation_count(legacy_query)) and a regression there would ship silently. Add a case with an empty canonical query and non-empty legacy query asserting the aggregation count path, mirroring the existing legacy-empty test.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/tests/unit/test_desktop_daily_usage.py, line 155:

<comment>The new tests cover the both-stores union and the legacy-empty case, but the symmetric branch where only the legacy store has rows (canonical empty) is untested. That branch has its own logic (`if legacy_any: counted = _aggregation_count(legacy_query)`) and a regression there would ship silently. Add a case with an empty canonical query and non-empty legacy query asserting the aggregation count path, mirroring the existing legacy-empty test.</comment>

<file context>
@@ -116,9 +149,18 @@ def test_memories_created_counts_canonical_and_legacy_shapes_without_duplicates(
 
-    assert result == 3
+
+def test_memories_created_uses_sot_count_when_legacy_store_is_empty():
+    canonical_query = _CreatedCountQuery(['canonical-only', 'shared'])
+    legacy_query = _CreatedCountQuery([])
</file context>

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Skipped. Dual-store ID union already covers the both-nonempty path; adding the empty-canonical case would not change the count() vs union split. Not blocking the cut.

…llback

Cubic P1: delete_batch writes historical suppression before the canonical
tombstone, so a live item still needs the override probe. P2: aggregation
failure must not restore an unbounded ID stream.

Failure-Class: none
@Git-on-my-level
Git-on-my-level merged commit c0c7dee into BasedHardware:main Sep 9, 2026
36 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant