Skip to content

fix(backend): stop the legacy memory offset read costing O(rounds x prefix) Firestore work (#11803) - #11816

Merged
kodjima33 merged 1 commit into
mainfrom
watchdog/issue-11803-memory-offset-scan-cost
Aug 18, 2026
Merged

kodjima33 merged 1 commit into
mainfrom
watchdog/issue-11803-memory-offset-scan-cost

Conversation

@kodjima33

@kodjima33 kodjima33 commented Aug 18, 2026 •

Copy link
Copy Markdown
Collaborator

Bug

GET /v3/memories 504s at the 30s edge for accounts whose newest-first historical prefix is fully suppressed by canonical. Live in prod on 2026-08-18 at ~26/h across 18 client IPs — the Windows desktop app (omi-windows/1.0.0 Electron, limit=5000&offset=0), iOS (Omi/12187 CFNetwork), and API clients — hitting both the offset>0 pages and the first page's documented scan-budget fallback. The user-visible result is a memory list that never loads.

This is the residual class left open on #11803 after PR #11805: "4x limit=5000&offset=0 (a 5000-row page pays for rows it EMITS)".

Root cause

MemoryService.read (the legacy offset path, and the first page's fallback target) deepens an adaptive historical scan when canonical suppression hides the rows a page needs. Two costs compound inside that loop:

  1. Every round re-reads the prefix from the start. HistoricalMemoryAdapter.read(limit=L, offset=0) always pages Firestore from db_offset=0, and the loop stepped L linearly: 500, 1000, 1500, … 5000.
  2. Every round re-read the canonical status of the whole prefix. canonical_statuses was called with every scanned row's id each round, so round k paid for rounds 1..k-1 again.

One page therefore cost O(rounds x prefix). Measured for the prod shape (window=500, 5000 suppressed rows):

queries documents
get_memories 55 27,500
get_all (statuses) 275 55,000
total 330 sequential round trips 82,500

330 sequential Firestore round trips is what takes the request past the 30s edge timeout. This is also a direct contributor to the standing "Firestore Document Reads exceeded 10k/s" alerts (#11282, #10950, #10817).

Fix

Two surgical changes in the same loop, no contract change:

  • Read each memory id's canonical status once per request. It is a stable read within one request, so a repeated prefix must not be re-queried. 275 batch gets → 50.
  • Grow the scan at least geometrically (_next_historical_scan_limit). The first expansion is still current + step, so an account needing one expansion is completely unchanged; a heavily suppressed account now needs a logarithmic number of rescans instead of a linear one. 55 queries → 25.
before after
round trips 330 75 (4.4x)
documents 82,500 22,500 (3.7x)

What I tested

  • backend/test.sh over all 84 memory test files: 801 passed, exit 0.
  • New guards in backend/tests/unit/test_memory_offset_read_cost.py fail on clean main with the source hunks stashed — assert 55 <= 30 (queries) and assert 2750 == 500 (status reads for 500 unique ids, the 5.5x amplification) — and pass with the fix.
  • test_first_expansion_step_is_unchanged_for_a_lightly_suppressed_account passes both with and without the fix, proving the geometric growth does not over-scan the light case.
  • make preflight green.

Not verified live yet: prod backend deploy is workflow_dispatch-only behind two approval gates, so this lands on main first and is measured on the real route after deploy.

Not fixed here

The historical prefix is still re-read from db_offset=0 on each remaining expansion round (25 queries / 12,500 docs). Removing that needs an incremental historical page reader, which would reintroduce the offset-scan shape read_scan_page was deliberately retired to prevent. Left tracked on #11803.

Product invariants affected:

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

Line-Count-Exception: backend/utils/memory/memory_service.py | 2558 -> 2587 | adds a 12-line documented scan-growth helper and a status cache inside the existing read loop; splitting the file is a separate refactor with far wider blast radius than this 504 fix

Failure-Class: none

🤖 automated by hourly watchdog — tested and merged

Review in cubic

…refix) Firestore work (#11803)

GET /v3/memories 504s at the 30s edge for accounts whose newest-first
historical prefix is fully suppressed by canonical — ~26/h in prod on
2026-08-18 across the Windows desktop app, iOS and API clients, on both
the offset>0 pages and the first page's documented scan-budget fallback.

MemoryService.read deepens an adaptive historical scan when suppression
hides the rows a page needs. Every round re-reads that prefix from the
start, and the round's canonical status lookup covered the whole prefix
again, so one page cost O(rounds x prefix):

  window=500, 5000 suppressed rows
    get_memories  55 queries  / 27,500 documents
    get_all      275 batch gets / 55,000 documents
    -> 330 sequential round trips, 82,500 document reads, > 30s

Two fixes in the same loop:
- Read each memory id's canonical status once per request (it is a stable
  read within one request), instead of once per expansion round.
- Grow the scan at least geometrically. The first expansion is still
  current + step, so an account needing one expansion is unchanged; a
  heavy account now needs a logarithmic number of rescans, not linear.

  after: 25 queries / 12,500 docs + 50 batch gets / 10,000 docs
    -> 75 round trips, 22,500 document reads (4.4x / 3.7x)

This is also a direct contributor to the standing "Firestore Document
Reads exceeded 10k/s" alerts (#11282, #10950, #10817).

Failure-Class: none

Verification:
- backend/test.sh over 84 memory test files: 801 passed, exit 0.
- New guards in tests/unit/test_memory_offset_read_cost.py fail on clean
  main (55 > 30 queries; 2,750 status reads for 500 unique ids) and pass
  with the fix. The light-suppression guard passes both ways, proving the
  first expansion step is unchanged.
@kodjima33
kodjima33 merged commit 2976cc3 into main Aug 18, 2026
40 checks passed
@kodjima33
kodjima33 deleted the watchdog/issue-11803-memory-offset-scan-cost branch August 18, 2026 13:02
kodjima33 added a commit that referenced this pull request Aug 18, 2026
…offset walk (#11803) (#11819)

GET /v3/memories still 504s at the 30s edge on the current prod image
(backend-2976cc3, which carries PR #11816): ~20/h over 2026-08-18 13:30Z
to 14:20Z, on the Windows desktop app, iOS and Python API clients, on
both `limit=5000&offset=0` (the first page's documented scan-budget
fallback) and the `offset>0` pages.

The remaining cost is what Firestore *reads*, not what the page returns.
`get_memories(sort="updated_or_created_desc")` has no index to order by —
`updated_at` is absent from a material slice of the collection — so it
streams two candidate windows of `limit + offset` documents and applies
the final order in Python. Every row an offset skips is still read and
billed. `HistoricalMemoryAdapter.read` walked the prefix in MAX_PAGE_SIZE
chunks with a growing `db_offset`, so each chunk rescanned everything the
previous chunks had already scanned: O(prefix^2 / page) instead of
O(prefix).

Measured on a fully suppressed 5,000-row account, one page:

  before  25 queries / 105,000 documents scanned
  after    5 queries /  25,000 documents scanned

Ask for the whole prefix in one query instead. `needed` is already
bounded by MAX_COMPATIBILITY_WINDOW, and each chunked query's candidate
window had grown to that size anyway, so a single query reads no more at
once than the last chunked query already did. MAX_PAGE_SIZE keeps its
real job as the API page cap.

The guard added with #11816 counted only the rows a query returned, which
is why a 105,000-read page passed it at 12,500. It now charges the
scanned candidate windows, and fails on the chunked walk (10,500 scanned
at test scale, budget 3,000).

This is also a direct contributor to the standing "Firestore Document
Reads exceeded 10k/s" alerts (#11282, #10950, #10817).

Failure-Class: none

Verification:
- backend/test.sh over the 84 memory test files: 856 passed, exit 0.
- The updated cost guard fails on the chunked walk (10,500 > 3,000
  scanned) and passes with the fix (2,500).
- Page-content equivalence checked against the pre-fix chunked walk over
  25 scenarios — suppression density 0/33%/100%, malformed rows forcing
  over-fetch continuation rounds, offsets 0 through the window edge —
  identical ids in every case.
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