Skip to content

fix(backend): bound Firestore list reads to stop 30s GET 504s - #10750

Merged
Git-on-my-level merged 4 commits into
BasedHardware:mainfrom
Git-on-my-level:fix/bound-firestore-list-reads-504
Jul 28, 2026
Merged

Git-on-my-level merged 4 commits into
BasedHardware:mainfrom
Git-on-my-level:fix/bound-firestore-list-reads-504

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Jul 28, 2026 •

Copy link
Copy Markdown
Member

Summary

Bound production Firestore list reads that caused GET routes to hit HTTP_GET_TIMEOUT=30 → HTTP 504 on large accounts.

Closes #10746

Root cause

  • get_action_items: full-collection stream() + in-process active-first sort, then offset/limit (FirestoreReadMode.UNBOUNDED).
  • get_knowledge_graph: unbounded nodes + edges streams.
  • Canonical/legacy /v3/memories first page forced limit=5000.

Fix

  1. Action items — active-first via incomplete then completed buckets with hard scan caps; legacy missing/null completed harvested via bounded unfiltered scan; due-range streams ASC to match product sort prefix. Telemetry mode bounded.
  2. Knowledge graph GET — limit() caps (2000 nodes / 5000 edges) + truncated/node_limit/edge_limit on the HTTP response model.
  3. Memories — remove first-page 5000 force; hard max page size 500. Flutter MemoriesProvider and Windows desktop bulk pager now page until short page.

Product invariants affected

  • INV-CHAT-1
  • INV-MEM-1

Failure-Class

Failure-Class: none

Verification

cd backend && BACKEND_UNIT_TEST_FILE_LIST=... bash test.sh
# action_items pagination, memories clamp/parity, v3 router, ws_i, bounded list reads — green

Non-goals

  • No timeout increase as “fix”
  • No merge/deploy/traffic/GKE changes beyond this PR merge authorization

Client impact

  • Memories clients must page (Flutter + Windows bulk updated in-tree).
  • KG response may include truncated / limits.

Action-items lists no longer full-stream the collection before active-first
sort; incomplete then completed buckets are scanned with hard caps.
Knowledge-graph GET applies node/edge limits and reports truncation.
Memories drop the forced first-page limit=5000 (hard max 500).

Failure-Class: none

Closes BasedHardware#10746

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ffcad695e3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/database/action_items.py Outdated
Comment on lines +425 to +426
if completed is not None:
query = query.where(filter=FieldFilter('completed', '==', completed))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Include legacy tasks in the completed buckets

When completed is omitted from the request, the new split path queries only completed == false and completed == true. Firestore equality filters exclude documents where completed is absent or null, even though _prepare_action_item_for_read explicitly supports those legacy/partial documents and derives their state from status; affected users will therefore have existing tasks disappear from every unfiltered action-items page.

Useful? React with 👍 / 👎.

Comment thread backend/database/action_items.py Outdated
Comment on lines +431 to +436
if due_at_filtering:
if due_start_date is not None:
query = query.where(filter=FieldFilter('due_at', '>=', due_start_date))
if due_end_date is not None:
query = query.where(filter=FieldFilter('due_at', '<=', due_end_date))
query = query.order_by('due_at', direction=firestore.Query.DESCENDING)

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 Badge Stream due-date ranges in the returned order

When a due-date range contains more rows than the new scan budget, this descending query reads only the latest deadlines, after which the in-process ascending sort can reorder only that subset. For example, a 50-row page over hundreds of matching tasks omits the actually soonest-due tasks and returns later ones instead; use an ascending Firestore order or otherwise ensure the bounded query selects the same prefix as the product sort. The added fake makes order_by a no-op, so it does not exercise the production query ordering required for this boundary.

AGENTS.md reference: backend/AGENTS.md:L237-L237

Useful? React with 👍 / 👎.

Comment on lines +212 to 216
# Do NOT force first-page limit=5000: that unbounded first load caused prod GET /v3/memories
# to hit HTTP_GET_TIMEOUT (30s) → 504 on large accounts. Callers must page via limit/offset.
offset = max(0, offset)
# Use high limits for the first page
# Warn: should remove
if offset == 0:
limit = 5000
limit = max(1, min(limit, 5000))
limit = max(1, min(limit, 500))
memories = memories_db.get_memories(uid, limit, offset)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Page the Flutter client before shrinking the first page

For accounts with more than 100 memories, this changes the Flutter app from receiving the historical expanded first page to receiving only its requested default of 100. MemoriesProvider.loadMemories() makes one getMemoriesResult(limit: 100) call with no offset/load-more path and renders/category-counts only that list, so older facts now appear to vanish. Update that in-tree client to paginate as part of this contract change rather than deferring it.

AGENTS.md reference: AGENTS.md:L91-L91

Useful? React with 👍 / 👎.

Comment on lines 293 to +298
return {
'nodes': get_knowledge_nodes(uid, db_client=client),
'edges': get_knowledge_edges(uid, db_client=client),
'nodes': nodes,
'edges': edges,
'truncated': nodes_truncated or edges_truncated,
'node_limit': MAX_KNOWLEDGE_GRAPH_NODES,
'edge_limit': MAX_KNOWLEDGE_GRAPH_EDGES,

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 Badge Expose the graph truncation fields through the route

When either cap is exceeded, these fields never reach GET /v1/knowledge-graph: the router still constructs KnowledgeGraphResponse(nodes=..., edges=...), whose model contains only those two fields. Dense graphs therefore return a silently partial snapshot with no truncated signal, contrary to this new contract; the regression test calls the database function directly and misses the production HTTP serialization boundary.

AGENTS.md reference: AGENTS.md:L49-L49

Useful? React with 👍 / 👎.

- Keep active-first action-item lists bounded without dropping legacy
  missing/null completed docs; due-range stream ASC for sort prefix.
- Expose KG truncation fields on the HTTP response model.
- Page Flutter MemoriesProvider and Windows bulk memory fetch after
  removing the server first-page 5000 expansion.
- Update unit expectations for the new bounds.

Failure-Class: none
@Git-on-my-level
Git-on-my-level merged commit aad6f23 into BasedHardware:main Jul 28, 2026
25 of 26 checks passed
Git-on-my-level added a commit that referenced this pull request Jul 28, 2026
)

After #10750, Windows CI failed: get_memories tool still clamped to 5000
and useMemories tests still expected forced first-page 5000.

Failure-Class: none
Git-on-my-level added a commit that referenced this pull request Jul 28, 2026
… event-payload SHA (#10784)

## Summary

`PR Metadata Preflight` (repo-checks.yml `metadata-preflight` job)
diffed against `github.event.pull_request.base.sha` — a value frozen at
whatever PR event last delivered it. That job only runs on metadata-only
`edited`/`labeled`/`unlabeled` events, which fire with no new commit and
don't refresh that field. On PR #10758, `main` had advanced 37 commits
(including a change to `backend/routers/memories.py` in an unrelated PR)
since the last time an event refreshed `base.sha`, so the diff scope
silently ballooned to include those unrelated commits and the job failed
on a false `INV-MEM-1` citation requirement for files the PR never
touched.

The sibling `changes` job in the same workflow already avoids this: it
resolves `origin/${{ github.base_ref }}` live against the job's own
`fetch-depth: 0` checkout instead of trusting a payload field. This PR
points `metadata-preflight` at the same thing.

## Fix

- `.github/workflows/repo-checks.yml`: `metadata-preflight`'s
`scripts/pr-preflight --base` now uses `origin/${{ github.base_ref }}`
instead of `github.event.pull_request.base.sha`.
- `.github/scripts/test_pr_preflight.py`: updated the workflow-content
regression test to assert the live-resolved base and guard against
reintroducing the stale payload field.

No behavior changes for the `changes`/`hygiene` (code) lane — it already
used the correct pattern.

## Product invariants affected

none

## Failure class (fixes)

Failure-Class: new

Registered `FC-stale-event-payload-diff-base`: a check that diffs a PR
against a base ref must resolve that ref live from the checkout, not
from a value captured in an event payload that isn't refreshed by every
trigger type that can run the check. No existing registered class covers
event-payload staleness driving an incorrect diff scope. `evidence_prs`
points at #10758, where this exact failure surfaced. Guard artifact:
`test_repo_checks_routes_metadata_events_to_the_narrow_preflight` now
asserts the live-resolved base and would fail if the stale field were
reintroduced.

## Verification

- `python3 .github/scripts/test_pr_preflight.py` — 26/26 pass (updated
regression test covers this exact case).
- `scripts/pr-preflight --pr-body-file <this file>` — passes locally
with `files=2` against `origin/main`.
- Live-reproduced the bug on PR #10758 before this fix: confirmed the
branch was 37 commits behind `main`, confirmed the exact upstream commit
(#10750) that touched the flagged memory files, and confirmed `git diff
origin/main...HEAD` (fresh, correct base) shows 27 files with no memory
files touched — matching what `metadata-preflight` should have reported.

## Related

Filed a follow-up issue: the same `github.event.pull_request.base.sha`
pattern also appears in `backend-unit-tests.yml`,
`desktop-swift-ci.yml`, `backend-hermetic-e2e.yml`, and
`desktop-backend-image-checks.yml`. Those jobs trigger on code-changing
events (`synchronize`/`opened`) where the payload field is refreshed by
the same event that needs it, so the staleness window is much narrower —
but not zero under queued/delayed runs. Left out of this PR to keep the
fix scoped and verifiable; tracked separately.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/10784?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
undivisible pushed a commit to Archit-lal/omi that referenced this pull request Jul 29, 2026
…ardware#10750)

* fix(backend): bound Firestore list reads to stop 30s GET 504s

Action-items lists no longer full-stream the collection before active-first
sort; incomplete then completed buckets are scanned with hard caps.
Knowledge-graph GET applies node/edge limits and reports truncation.
Memories drop the forced first-page limit=5000 (hard max 500).

Failure-Class: none

Closes BasedHardware#10746

* fix(backend): address PR BasedHardware#10750 review + unit regressions

- Keep active-first action-item lists bounded without dropping legacy
  missing/null completed docs; due-range stream ASC for sort prefix.
- Expose KG truncation fields on the HTTP response model.
- Page Flutter MemoriesProvider and Windows bulk memory fetch after
  removing the server first-page 5000 expansion.
- Update unit expectations for the new bounds.

Failure-Class: none

* style(app): wrap memories_provider for CI dart format

Failure-Class: none

* style(app): dart-format memories_provider with resolved analysis_options

Failure-Class: none
undivisible pushed a commit to Archit-lal/omi that referenced this pull request Jul 29, 2026
…edHardware#10761)

After BasedHardware#10750, Windows CI failed: get_memories tool still clamped to 5000
and useMemories tests still expected forced first-page 5000.

Failure-Class: none
Git-on-my-level added a commit that referenced this pull request Jul 30, 2026
## Summary

Tighten `GET /v1/knowledge-graph` to a deterministic snapshot of at most
500 nodes, 1,000 edges, and 500 canonical assertions, and expose
additive returned-count metadata.

Multica:
[SCA-261](https://multica-01.tail76ea03.ts.net/scaling-forever/issues/1b92e010-c172-496a-829a-74407c911d6d)

## Root cause

`TimeoutMiddleware` applies `HTTP_GET_TIMEOUT` and returns a bare 504
when the request exceeds the production 30-second GET budget. The
deployed commit already contains #10750's original 2,000-node /
5,000-edge caps, but production heavy-tail requests still pin that
ceiling. Including the canonical assertion and privacy-fence reads, that
path could consume roughly 11,500 Firestore documents before
serialization.

The prior cap was therefore bounded in name but still too large for the
request budget. Raising `HTTP_GET_TIMEOUT` would retain the excessive
read and worker cost, so this PR does not change any timeout.

## Fix

- Reduce the server-enforced snapshot to 500 nodes, 1,000 edges, and 500
assertions (roughly 3,000 maximum Firestore documents including
active-item and citation-fence reads).
- Explicitly order each capped Firestore page by document ID so repeated
reads select a deterministic subset without requiring a new composite
index.
- Preserve the required `nodes` and `edges` arrays and existing
truncation/limit fields.
- Add optional-compatible `node_count` and `edge_count` fields
describing the records returned in the bounded snapshot.
- Keep edges referentially closed over the returned node page.

## Product invariants affected

- INV-MEM-4 (proposed): the canonical assertion privacy fence and
derived-view ownership remain intact.

## Failure-Class

Failure-Class: new

Guard artifact: the 20,000-node / 20,000-edge behavioral fixture fails
if the production loader omits its Firestore cap or deterministic
ordering, while the HTTP-level regression verifies the additive response
and unchanged Firebase dependency.

## Verification

- `backend/.venv/bin/python -m pytest -q
backend/tests/unit/test_bounded_firestore_list_reads.py
backend/tests/unit/test_memory_graph_assertion_read.py
backend/tests/unit/test_knowledge_graph_canonical_mutation_routes.py
backend/tests/unit/test_timeout_middleware.py
backend/tests/unit/test_http_timeout_defaults.py` — 47 passed.
- `backend/.venv/bin/pyright --pythonpath backend/.venv/bin/python
backend/database/knowledge_graph.py backend/routers/knowledge_graph.py`
— 0 errors.
- App-client OpenAPI, Dart DTO, and TypeScript client generation checks
— current.
- `OMI_PR_BODY_FILE=pr-body.md make preflight` — 27 checks passed.

The repository `backend/test.sh` wrapper executed all focused assertions
successfully, but its Mac CPU-time ratchet rejected an unchanged
5,000-item action-items fixture at 0.17–0.19s (limit 0.12s). The same
files pass under focused pytest; this PR does not alter action-items
policy.

## Operational notes

- No production deployment, traffic change, rollback, Firestore
mutation, or timeout increase.
- A rollback is not recommended for this chronic heavy-tail class; the
serving revision is healthy and the mechanism predates the current
chat-stream revision.
- Action-items, memories, and other GET heavy tails remain outside this
PR and require separate production validation even where #10750 added
initial caps.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/10902?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
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.

[P1] Prod GET action-items/memories/knowledge-graph hit HTTP_GET_TIMEOUT (30s) → 504; unbounded Firestore reads

1 participant