Repository navigation
fix(backend): prevent large list GETs from exhausting the 30s request budget - #11858
Git-on-my-level merged 6 commits into
Conversation
kodjima33
left a comment
There was a problem hiding this comment.
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.
|
Monitor run — check triage for this head (
|
bb9b9c9 to
5f09ad9
Compare
|
Monitor run — rebased onto current Upstream
|
|
@cursor fix CI failures in a non-flaky way |
undivisible
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
…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>
5853106 to
22ebaae
Compare
|
Monitor run — Hygiene fixed via PR-body metadata refresh (
|
Summary
GET /v1/action-items,GET /v1/conversations, andGET /v3/memoriescould each drive aggregate Firestore work pastHTTP_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
utils/other/list_budget.pyowns a monotonic internal deadline (24s default: the 30s middleware cutoff minus serialization headroom), a 25k-document allowance, aggregate counters, and a typedListReadBudgetExhausted. Created once per request at the route from theTimeoutMiddleware-stamped request start (request.state.omi_request_started_monotonic), so pre-handler time (auth, middleware) counts.TimeoutMiddlewarestill owns the hard 30s cutoff — unchanged.stream()/get_all()/document.get()on these routes receivestimeout=budget.rpc_timeout()derived from the remaining internal deadline. A blocked RPC raisesDeadlineExceededat the internal deadline, leaving ≥6s headroom for serialization; only that exception (and allowance exhaustion) maps to the typed outcome. Loop-sidemonotonic()checks alone cannot stop a blockednext()— the RPC timeout is what does.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./v3/memoriesfirst-page scan-budget 503 (Memory scan budget exceeded) still falls back to the legacy offsetread(), now on the same request budget; it can never start a fresh unbudgeted 5000-row window.X-Omi-List-Truncated: trueresponse header. Action-items gains an optionaltruncated: boolfield onActionItemsResponseand the same header; on exhaustionhas_moreis forced true so a missing lookahead can never report "complete". A truncated memory page carries noX-Omi-Memory-Next-Cursor, because its cursor state would not cover every consumed scan position.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):NotFoundkeeps raising.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.Existing suites updated for the new call kwargs (
budget=...) and the optional action-itemstruncatedfield: 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
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.
work only; it does not alter intake, consolidation, promotion, or
projection authority.
read work; it does not add tiers, collections, or archive exposure, and
include_archivegating 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.