Skip to content

fix(backend): prevent large list GETs from exhausting the 30s request budget - #11858

Merged
Git-on-my-level merged 6 commits into
BasedHardware:mainfrom
Git-on-my-level:fix/list-read-budget-11831
Aug 21, 2026
Merged

Git-on-my-level merged 6 commits into
BasedHardware:mainfrom
Git-on-my-level:fix/list-read-budget-11831

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Summary

GET /v1/action-items, GET /v1/conversations, and GET /v3/memories could each drive aggregate Firestore work past HTTP_GET_TIMEOUT (30s) and come back as a bare middleware 504 on large accounts (#11831). This PR makes those three reads budget-bound: they either land, or return an honest partial page with an explicit truncation surface.

Closes #11831

Design

  • Request-scoped budget — utils/other/list_budget.py owns a monotonic internal deadline (24s default: the 30s middleware cutoff minus serialization headroom), a 25k-document allowance, aggregate counters, and a typed ListReadBudgetExhausted. Created once per request at the route from the TimeoutMiddleware-stamped request start (request.state.omi_request_started_monotonic), so pre-handler time (auth, middleware) counts. TimeoutMiddleware still owns the hard 30s cutoff — unchanged.
  • Wall clock interrupts the blocking RPC — every Firestore stream() / get_all() / document.get() on these routes receives timeout=budget.rpc_timeout() derived from the remaining internal deadline. A blocked RPC raises DeadlineExceeded at the internal deadline, leaving ≥6s headroom for serialization; only that exception (and allowance exhaustion) maps to the typed outcome. Loop-side monotonic() checks alone cannot stop a blocked next() — the RPC timeout is what does.
  • Charge actual aggregate work — conversations charge the server-side offset() prefix before the query (Firestore bills and streams every skipped row); action-items share one budget across the active, legacy-harvest, and completed queries; memories charge both dual-window index scans plus emitted and suppressed rows, the canonical stream, status batches, and hydration.
  • Fallback shares the budget — the /v3/memories first-page scan-budget 503 (Memory scan budget exceeded) still falls back to the legacy offset read(), now on the same request budget; it can never start a fresh unbudgeted 5000-row window.
  • Non-breaking truncation surface — conversations and memories keep their bare JSON arrays (Flutter/macOS/Windows decode arrays; no envelope migration) and instead set the documented X-Omi-List-Truncated: true response header. Action-items gains an optional truncated: bool field on ActionItemsResponse and the same header; on exhaustion has_more is forced true so a missing lookahead can never report "complete". A truncated memory page carries no X-Omi-Memory-Next-Cursor, because its cursor state would not cover every consumed scan position.
  • Error semantics preserved — non-budget Firestore/auth/validation errors keep their current statuses (503/4xx); nothing becomes a catch-all HTTP 200 partial.
  • Telemetry — list_read_requests_total{route,outcome}, list_read_documents_total{route}, list_read_seconds{route}. Labels carry only route/outcome — no uid, query, payload, or raw URL.

HTTP defaults are untouched (action-items 50/500, conversations 100/1000 with unbounded offset, memories 100/500 with the 5000 compatibility window intact).

Tests

New backend/tests/unit/test_list_read_budget_contract.py (34 tests):

  • Fake-clock deadline/allowance unit tests incl. off-by-one exhaustion and first-reason-wins; blocked-RPC fake proving the internal deadline fires with ≥6s headroom under the 30s cutoff; middleware-stamp propagation.
  • Action items: one shared budget across active+legacy+completed; deadline cut mid-bucket returns a partial page + truncated; non-budget NotFound keeps raising.
  • Conversations: 1k/5k/20k-row large-offset fixtures served and charged (docs_scanned == offset + limit); offset beyond the allowance truncates with no stream issued; mid-page deadline cut keeps an honest newest-first prefix; budgeted/unbudgeted parity.
  • Memories: parent-budget exhaustion mid-merge returns a partial page with no cursor; complete budgeted page keeps the cursor header; scan-budget 503 → offset fallback provably reuses the same budget object; dual-window charging.
  • Route-level header/field assertions for all three routes.

Existing suites updated for the new call kwargs (budget=...) and the optional action-items truncated field: pagination order, router pagination, bounded list reads, memories pagination clamp, universal cursor/service, offset read cost, archive/read contracts, egress contract, atom keyword index, desktop migration hermetic stubs.

Product invariants affected

  • INV-INT-1: Integrations must not claim a complete export from a truncated response.
  • INV-MEM-3: Universal memory authority fails closed. The budget never
    bypasses canonical authority — typed list-read exhaustion returns a partial
    page of already-verified rows or an explicitly truncated empty page, and
    non-budget canonical/readiness failures keep their fail-closed 503s. The
    historical adapter stays a read-only input; the offset fallback runs under
    the same request budget and the same canonical suppression checks.
  • INV-MEM-4: Memory promotion authority unchanged. This PR bounds read
    work only; it does not alter intake, consolidation, promotion, or
    projection authority.
  • INV-MEM-1: Exactly three product memory tiers. The budget only bounds
    read work; it does not add tiers, collections, or archive exposure, and
    include_archive gating is threaded through unchanged.

Failure-Class: FC-bounded-read-exceeds-request-budget

Line-Count-Exception: backend/database/conversations.py | 1735 -> 1759 | Budget parameter, pre-query offset charging, and budgeted partial-page accumulation threaded into the existing no-photo list helper; no new responsibilities.
Line-Count-Exception: backend/routers/conversations.py | 1659 -> 1676 | Route creates the request-scoped budget and sets the documented X-Omi-List-Truncated header on the unchanged bare-array response.
Line-Count-Exception: backend/utils/memory/canonical_memory_adapter.py | 2593 -> 2606 | Budget threading through the canonical scan page and lineage point-reads so their RPCs run under the derived per-RPC timeout.
Line-Count-Exception: backend/utils/memory/memory_service.py | 2774 -> 2891 | Scan sub-budget derives from the shared request budget, typed-exhaustion re-raises before each broad 503 wrapper, and read/read_page return explicitly truncated partial pages without cursors.

Line-Count-Exception: desktop/macos/Desktop/Sources/MainWindow/Pages/MemoriesPage.swift | 3576 -> 3606 | Truncation-aware pagination and sync/reconcile guards added to the memory list view model.
Line-Count-Exception: desktop/macos/Desktop/Sources/MemoryExportService.swift | 1604 -> 1610 | Reject truncated memory pages during full export so exports cannot be mistaken for complete.

Review in cubic

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

Budget-bound list reads with an explicit truncation surface — approving; diff is too large (2.3k lines across the API surface) for an auto-merge under the backend confidence gate.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Monitor run — check triage for this head (bb9b9c9)

  • Hygiene ✅ fixed: product-file-line-count-ratchet failed because the body's exception for backend/routers/conversations.py said 1527 -> 1544 (merge-base numbers) while CI counts against current origin/main (1538 -> 1555; +17 delta unchanged — upstream added 11 lines to the file under this PR). Body corrected and verified: Hygiene is green in CI (run 32271542423).
  • Sync Cloud Tasks Stack Gauntlet ❌ infra flake, not this PR: three attempts all died in runner env setup, never in PR code — (1) Firestore emulator JAR download failed from storage.googleapis.com; (2) & (3) sudo apt-get hung on azure.archive.ubuntu.com (Ign: loop) until the job's 20-min timeout cancelled it at the Install Redis server step. The same workflow passed on other branches in the same window (e.g. runs 32274802318, 32275145689 at 16:14–16:18). I did not add CI plumbing to this backend PR; the next rerun that lands on a healthy runner should pass, and the merge gate result follows this job.
  • Backend Hermetic Merge Gate: aggregate-only failure — HERMETIC_E2E_RESULT=success, LISTEN_PUSHER_RESULT=success, gate blocks solely on the sync gauntlet flake above.
  • No unresolved review threads; nothing else actionable on this head.

@Git-on-my-level
Git-on-my-level force-pushed the fix/list-read-budget-11831 branch from bb9b9c9 to 5f09ad9 Compare August 19, 2026 19:32
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Monitor run — rebased onto current main (new head 5f09ad9)

Upstream main moved past this branch (notes-v2 + completed-filter fixes touched the same action-items/conversations files), leaving the PR CONFLICTING. Resolved:

  • Rebased the 3 PR commits onto current origin/main (091a65bef). One import-order conflict in backend/routers/conversations.py (upstream's emit_product_event vs this PR's list_budget imports) — both kept. Verified the seam still coexists with fix(backend): push the completed filter server-side in the visible action-item ID scan, and meter it #11849's server-side completed filter in action_items.py.
  • Targeted verification: 40 focused unit tests green through backend/test.sh (list-budget contract, action-items pagination, memory offset cost, conversations archive/events/date validation, desktop migration) + py_compile on all touched production files. Full scripts/pre-push gate vs origin/main: 36 checks passed (~10.7 min).
  • Body hygiene: updated the stale Line-Count-Exception for backend/routers/conversations.py to 1605 -> 1622 (upstream grew the file; PR delta unchanged). Other three exceptions were already current.
  • No unresolved review threads on the previous head; no code changes were needed — this is a pure conflict-resolution push, same 3 commits.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

@cursor fix CI failures in a non-flaky way

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

Request changes

The 34 list-budget contract tests pass, but the new truncation signal is not consumed by the affected clients. APIClient+Memories.getMemoriesPage only reads X-Omi-Memory-Next-Cursor; MemoryListPage has no truncated state, so MemoryExportService.fetchAllCursorPages treats the intentionally withheld cursor as a complete export. Flutter’s memory and conversation list wrappers also ignore X-Omi-List-Truncated, so they can render an incomplete page as complete.

Please surface X-Omi-List-Truncated through each affected client transport and make export/list callers fail or retry safely. The no-cursor rule is sound only once callers distinguish “truncated” from “complete final page.” Current head also has red Desktop Swift checks, so this remains review-only.

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

Re-approved on the new head. Real budget-exhaustion bug, but the diff is far past the 300-line backend merge gate, so approve-only.

Git-on-my-level and others added 6 commits August 21, 2026 00:20
…BasedHardware#11831)

GET /v1/action-items, /v1/conversations, and /v3/memories could each drive
aggregate Firestore work past HTTP_GET_TIMEOUT (30s) and surface as a bare
middleware 504 on large accounts.

Add a request-scoped ListReadBudget (utils/other/list_budget.py) created at
each route from the TimeoutMiddleware-stamped request start. It owns a
monotonic internal deadline (24s by default: the 30s cutoff minus
serialization headroom), a 25k document allowance, aggregate counters, and
a typed exhaustion. Every Firestore stream/get_all/document-get on these
routes receives a per-RPC timeout derived from the remaining deadline, so a
blocked RPC surfaces at the internal deadline instead of the edge cutoff;
DeadlineExceeded maps only to the typed exhaustion.

Charging follows actual aggregate work: conversations charge the
server-side offset() prefix before the query; action-items share one
budget across the active, legacy-harvest, and completed queries; memories
charge dual-window index scans plus emitted and suppressed rows, and the
offset fallback shares the same budget (never a fresh unbudgeted window).

Truncation surface is non-breaking: conversations and memories keep their
bare arrays and set the documented X-Omi-List-Truncated: true response
header; action-items adds an optional truncated field and forces has_more
true on exhaustion (never "complete" from a missing lookahead). A
truncated memory page carries no next-cursor, since its cursor state would
not cover every consumed scan position. Non-budget Firestore/auth/
validation errors keep their existing statuses.

TimeoutMiddleware still owns the hard cutoff; its 30s default is
unchanged. Telemetry: list_read_{requests,documents,seconds} carry only
route/outcome labels.

Failure-Class: FC-bounded-read-exceeds-request-budget
Co-authored-by: multica-agent <[email protected]>
…n guard

Move router imports to module level so file-isolated runs charge them at
collection instead of the first test's call phase; shrink the
conversations offset-exhaustion fixture to the rows the allowance gate
actually reads. Allowlist the pre-existing ~0.5s-CPU suppressed-prefix
expansion test (unchanged by, and unchanged across, the budget change).

Failure-Class: none
Co-authored-by: multica-agent <[email protected]>
…ware#11831 list-budget seam

Four hermetic unit harnesses fake utils.other as a non-package and were
missing the new utils.other.list_budget submodule the list routers now
import at module level (ModuleNotFoundError at collection). Load the real
stdlib-only budget module into each stub (same pattern as
test_desktop_migration) in test_task_sharing, the archive-filter contract,
and events-bounds; automock it in the date-validation harness whose routes
never exercise the budget.

The mobile lifecycle E2E pinned the /v1/action-items envelope to exactly
{action_items, has_more}; the budget change intentionally adds the
documented truncated flag, so the shape assertion now includes it as a
plain bool.

Failure-Class: none

Co-authored-by: multica-agent <[email protected]>
The 20k-row conversation offset fixture and the first memories-router test are

hermetic but structural; they exceed the 0.30s local fast-unit guard on the

file-isolated runner. CI uses a 1.0s ceiling and already passes them.

Failure-Class: none
…h partial from complete pages

- macOS APIClient+Memories: parse X-Omi-List-Truncated into MemoryListPage.truncated.
- macOS MemoryExportService: fail export when any page is truncated.
- macOS MemoriesPage: stop paginating on truncated, don't mark cache reconcile/default-scope sync complete.
- Flutter getMemoriesResult / getConversationsResult: carry a truncated flag.
- Flutter MemoriesProvider / ConversationProvider: stop further pages on truncated.
- Add regression tests for macOS header parsing, export rejection, and Flutter provider truncation handling.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@Git-on-my-level
Git-on-my-level force-pushed the fix/list-read-budget-11831 branch from 5853106 to 22ebaae Compare August 21, 2026 04:21
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Monitor run — Hygiene fixed via PR-body metadata refresh (22ebaae)

  • Hygiene ✅ fixed: product-file-line-count-ratchet failed because upstream main grew four of the files this PR touches (+7/+55/+39/+108 base lines), making the PR-body Line-Count-Exception counts stale (1728->1752 vs actual 1735->1759, etc.). Refreshed all four declarations to the current diff; no code change.
  • product-invariants ✅ fixed: surfaced after the ratchet passed — the touched memory paths (backend/routers/memories.py, backend/utils/memory/**) also require INV-MEM-4. Added it with a note that this PR bounds read work only and does not alter promotion authority.
  • Verified locally against origin/main (c659c322) with check_product_file_line_count_ratchet.py + check_product_invariants.py before editing; both re-ran green in CI (Metadata Preflight run 32453237247, Hygiene rerun of 32446673343).
  • No review threads were unresolved at run start; nothing to resolve. Check rollup is green except a superseded Metadata Preflight run from the first body edit (latest run is SUCCESS) and the queued Desktop Swift Release Compile.

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.

backend: prevent large list GETs from exhausting the 30s request budget

3 participants