Skip to content

fix(backend): stop listing GETs decrypting/overscanning past the 30s GET timeout - #11830

Merged
Git-on-my-level merged 5 commits into
mainfrom
fix/memories-list-504-dual-window
Aug 18, 2026
Merged

Git-on-my-level merged 5 commits into
mainfrom
fix/memories-list-504-dual-window

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Summary

Prod GET listings 504 at exactly 30.0s (HTTP_GET_TIMEOUT). Cloud Run timeout is 3600s; empty 504s are TimeoutMiddleware. Two failure classes sharing that deadline, not one shared query.

  • GET /v3/memories: dual-window updated_or_created_desc streamed two windows of min(limit+offset, 5000) full docs and decrypted the offset prefix. First-page keyset read_page used max(page_limit, 50) = 500-doc chunks and decrypted before the 6s scan budget could charge(), so fallback get_memories often started at t+17s.
  • GET /v1/action-items: Windows omi-windows/1.0.0 (Electron still emits 1.0.0) sent limit=500 on both completed= buckets. The completed filter scanned 2× the page as full documents. One saturated Cloud Run instance (containerConcurrency=20) then 504'd cheap GETs in the same minutes.

Do not raise HTTP_GET_TIMEOUT. Firestore select() still bills 1 read/doc — this drops CPU/payload, not billed reads.

Memories

Index the two windows as metadata (updated_at/created_at/user_review/invalid_at/visibility/capture_device_ids), merge, then hydrate only the returned page. Mixed-list expansion uses the same stubs (hydrate=False) and decrypts kept historical page rows only — not suppressed ids that collided with canonical (migrated memories share ids). Index stubs keep real visibility (missing → public; unknown → skip) and capture_device_ids. Keyset fetches are 50-doc chunks with the 6s budget checked before each fetch.

Action items + Windows

List reads select() lean fields (omit provenance), Firestore limit(page + 32 deleted slack) instead of 2× overscan, and apply offset as a live-item slice after product sort so it stays aligned with Windows offset += items.length. Do not use Firestore .offset() — that counts deleted documents and would skip/duplicate pages. Windows populate/reconcile pages at 100 (macOS TasksStore) and stamps roundServedBackendRead before the request so a 15s client abort does not retry a still-running 30s Cloud Run worker.

Product invariants affected

  • INV-MEM-1 — path glob only (backend/database/memories.py, backend/utils/memory/**). Historical stubs still classify as long_term. Default access policy and the three product tiers are unchanged.
  • INV-MEM-3 — mixed-origin reads still go through MemoryService. Canonical failure still 503s; historical is a read-only input. Hydration of index stubs does not bypass canonical suppression or fail open onto a direct legacy reader.

Failure class (fixes)

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

A request-scoped collection read must bound its aggregate document work low enough to finish within the request middleware budget; a large per-query limit is not a sufficient bound when several reads compose (two 5000-doc windows + prefix decrypt; 2× full-document overscan). Guard artifact: backend/tests/unit/test_bounded_firestore_list_reads.py.

Line-Count-Exception: backend/utils/memory/memory_service.py | 2595 -> 2735 | Page-only hydrate and 50-doc keyset chunks have to live on HistoricalMemoryAdapter; splitting that owner is a follow-up, not this timeout fix.

Test plan

  • Backend focused units (142 passed): test_memory_offset_read_cost.py, test_universal_memory_service.py, test_universal_memory_list_cursor.py, test_memories_pagination_clamp.py, test_memory_service_parity.py, test_memory_visibility_export_fixes.py, test_bounded_firestore_list_reads.py, test_action_items_pagination_order.py, test_action_items_due_range_index_contract.py, test_firestore_query_contract.py, test_action_item_lists_hide_soft_retired_rows_before_pagination
  • Windows taskSyncEngine.test.ts: 50 passed (pages at limit=100, offset advances by delivered length)
  • make preflight against this body (local lane, origin/main)
  • CI backend unit selection for the touched paths
  • After deploy: Cloud Logging for /v3/memories and /v1/action-items 504s over a comparable 3h window; Windows populate should not stampede limit=500

Not exercised here: live prod accounts, a real Windows populate against prod. Hermetic fixtures cover the dual-window hydrate bound, live-item offset vs Firestore offset, and the 100-item page step.

Verification

cd backend && python -m pytest -q -m "not integration and not slow" \
  tests/unit/test_memory_offset_read_cost.py \
  tests/unit/test_universal_memory_service.py \
  tests/unit/test_bounded_firestore_list_reads.py \
  tests/unit/test_action_items_pagination_order.py
# 142 focused tests passed across the listing files above (full command in commit)

cd desktop/windows && npx vitest run src/main/tasks/taskSyncEngine.test.ts
# 50 passed

Review in cubic

Git-on-my-level and others added 5 commits August 18, 2026 17:55
…prefix

GET /v3/memories 504'd at HTTP_GET_TIMEOUT after the first-page keyset
scan fell back to updated_or_created_desc: two windows of min(limit+offset,
5000) full docs were decrypted, including the skipped offset prefix.
Index those windows as metadata, hydrate the returned page, and cap
keyset fetch chunks so the 6s scan budget is checked between 50-doc
pages instead of after a 500-doc decrypt.

Failure-Class: FC-bounded-read-exceeds-request-budget
Co-authored-by: Cursor <[email protected]>
…ents

GET /v1/action-items 504'd in 30.0s bursts from omi-windows: completed=
pages scanned 2x the limit as full docs, and populate paged at 500.
Project list fields (omit provenance), scan page+deleted-slack, keep
live-item offset aligned with the client, and page Windows populate at
100 with offset += delivered length.

Failure-Class: FC-bounded-read-exceeds-request-budget
Co-authored-by: Cursor <[email protected]>
Migrated memories share ids across stores. Hydrating every historical
index stub on the page treated a canonical winner as a stub and swapped
it for the grandfathered document (or dropped it). Only decrypt ids that
were actually appended from historical.

Failure-Class: FC-bounded-read-exceeds-request-budget
Co-authored-by: Cursor <[email protected]>
Pyright reportPrivateUsage failed the pre-push typecheck: scan-page
decrypt called database.memories._prepare_memory_for_read, and mixed-list
hydrate called HistoricalMemoryAdapter._hydrate_records from MemoryService.

Failure-Class: FC-bounded-read-exceeds-request-budget
Co-authored-by: Cursor <[email protected]>
HistoricalMemoryAdapter.read now always lists via
list_memory_updated_or_created_index. Chat/developer/product fixtures
still only mocked get_memories, so mixed-list reads hit Firestore fakes
without .document() and 503'd as Historical memory unavailable.

Failure-Class: FC-bounded-read-exceeds-request-budget
Co-authored-by: Cursor <[email protected]>
@Git-on-my-level
Git-on-my-level merged commit b27420e into main Aug 18, 2026
44 of 46 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/memories-list-504-dual-window branch August 18, 2026 23:19
Git-on-my-level added a commit that referenced this pull request Aug 19, 2026
…ifact (#11841)

## The defect

`google-github-actions/deploy-cloudrun` stamps a `commit-sha` label from
`GITHUB_SHA` — the ref the workflow run was **triggered** on. A pinned
deploy checks out and builds `release_sha`. Those differ on exactly the
deploys that were deliberate, so the label names a commit that was never
deployed.

Measured on the 2026-08-19 production deploy of `backend`, dispatched
with `release_sha=2ebef0dc12`:

| Marker | Value | Derived from | Truthful |
| --- | --- | --- | --- |
| revision name `backend-2ebef0d-…` | `2ebef0dc12` | `git rev-parse
--short=7 HEAD` after checkout | yes |
| image tag `gcr.io/…/backend:2ebef0d` | `2ebef0dc12` | same short SHA |
yes |
| **`commit-sha` label** | **`b27420e01c`** | **`GITHUB_SHA`** | **no**
|

`b27420e01c` was `main` HEAD when the run was dispatched. It was never
built and never deployed.

## Why this is worse than publishing nothing

`commit-sha` is the first marker an operator reads to answer *"what is
running in production"*. During the 2026-08-19 incident it produced two
reversals in one session: first the conclusion that production carried
five commits it did not, then a latency improvement re-attributed to
`#11830` — a fix that was not actually deployed. The truthful signals
(revision-name suffix, image tag) sat unread beside it, because nobody
reaches for an image digest when a field literally named `commit-sha` is
present.

`desktop-backend` was unaffected: it already publishes
`OMI_DESKTOP_BACKEND_RELEASE_SHA` from its admitted source SHA, and
reading that env var resolved the same incident in one query.

## The fix

Propagate the pattern that already works, and prove it:

1. **`OMI_BACKEND_RELEASE_SHA`** is published on the `backend` Cloud Run
service from `inputs.admitted_sha` — the `release_sha` that
`verify_backend_release_admission.py` validated as an ancestor of `main`
and that the job checked out. True by construction.
2. **A post-deploy readback** describes the revision that was actually
created, extracts the marker, and fails the deploy on mismatch. An
untrue provenance marker now stops the release rather than outliving it.

The misleading `commit-sha` label cannot be suppressed from inside the
action, so this adds a marker that is correct rather than trying to
correct one that is structurally wrong. The failure-class definition
records that asymmetry so the next person does not read the label and
re-derive the same wrong answer.

## Scope

`backend` only, matching the service the incident touched.
`backend-sync`, `backend-sync-backfill` and `backend-integration` deploy
through the same action and have the same gap — deliberately left for a
follow-up rather than widening a production deploy path in one change. A
per-service serving-SHA drift view is the natural next step, and it is
only meaningful once the markers it reads are trustworthy.

## Verification

- `jq` extraction expression validated against a live revision: returns
`b27420e01cd7a48cecc7f75107895feb45dafcc9` from
`desktop-backend-b27420e01cd7-32203390739-1`
- YAML parses; the readback is a single piped line, so it cannot break
the block scalar the way an inline heredoc did
- `make preflight` green

Failure-Class: new


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/11841?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. -->
Git-on-my-level added a commit that referenced this pull request Aug 19, 2026
…tion-item ID scan, and meter it (#11849)

## What

`get_visible_action_item_ids()` (`backend/database/action_items.py`)
backs
`GET /v1/action-items/ids?completed=...` and used to stream the entire
per-user `action_items` collection with a bare projection query,
filtering
`completed` in Python. A projection query still bills one document read
per
document scanned, so every call cost one read per action item the user
has
ever created, regardless of how many were actually in the requested
bucket.
The function also never called `record_firestore_read`, so this scan was
invisible in `backend/database/firestore_read_metrics.py`, unlike every
other reviewed read path in the module.

This PR:

1. Pushes the `completed` filter server-side with
`.where(filter=FieldFilter('completed', '==', completed))`, so Firestore
only streams (and bills) documents in the requested bucket instead of
the
   whole collection.
2. Adds a `record_firestore_read` call with a new
`FirestoreReadFamily.ACTION_ITEMS_VISIBLE_IDS` family, so this path is
   finally counted.
3. Drops `status` from the field projection — it is fetched but never
read
   in the function body.

## What this does NOT change: the `deleted` semantics

The trap in this change is `deleted`. It is tempting to also push
`.where('deleted', '==', False)` server-side. **Don't** — Firestore
equality
filters never match a document where the field is absent, and most
action
items have no `deleted` field at all (it is only ever set on
soft-deleted
rows). A server-side `deleted` filter would silently drop every
ordinary,
undeleted row from every bucket. The `if data.get('deleted'): continue`
check stays in Python, and the diff adds a comment on the function
saying
why.

## Does the `completed` semantics shift?

Current code matched with `completed_value is completed` — Python
identity
against a bool, so a doc with `completed` absent/`None` or any non-bool
value (e.g. a stray `1`/`0`) never matched either bucket, since `is`
requires the exact `True`/`False` singleton, not just equality.
Firestore's
`== True` / `== False` also never matches a missing field, and Firestore
equality does not coerce an int `1`/`0` into a bool match either. So the
server-side filter returns exactly the same document set the old Python
identity check selected, and that check is now redundant and was
removed.
The new unit test

`test_visible_action_item_ids_matches_explicit_bucket_and_excludes_deleted`
still exercises the same legacy-row fixtures (`completed: None`,
status-only rows) to pin this.

## Value — please read this section literally

**This is a correctness and instrumentation fix, not a measured cost
win.**
PR #11835's follow-up notes attributed a large share of the Windows
app's
backend request volume to this function, estimating "24 full collection
scans per idle hour per running client." Production log sampling on
2026-08-19 found that attribution is wrong: there is effectively zero
traffic to `GET /v1/action-items/ids`. The ~60k req/hr Windows volume
goes
to `GET /v1/action-items` (the listing endpoint), a different code path
already addressed by #11830. This PR does not claim to reduce measured
load.

The reason to land it anyway: the scan this function runs is unbounded
per
call and, until this PR, completely unmetered. It is a latent cliff —
cost
grows linearly with each user's lifetime action-item count — that we
currently cannot see coming because nothing records it. Fixing the query
shape and adding the metric closes both problems at once, independent of
today's traffic level.

## Testing

`backend/tests/unit/test_action_item_ids_endpoint.py` already covered
`get_visible_action_item_ids`; extended rather than duplicated:

- Updated the fake Firestore query fixture (`_Query`) to implement real
  equality-filter semantics for `.where()` — a filter only matches a
  document where the field is present and matches by both value and type
(so a stray `int` 1/0 is never treated as `True`/`False`), same as real
Firestore. This lets the tests actually distinguish server-side
filtering
  from the old Python-side filtering it replaces.
-
`test_visible_action_item_ids_matches_explicit_bucket_and_excludes_deleted`:
  now also asserts the projection is `['completed', 'deleted']` (not
  `status`) and that the `completed` filter was pushed to Firestore.
- `test_visible_action_item_ids_excludes_legacy_null_completion_rows`:
  unchanged behavior, kept as a regression pin.
- New
`test_visible_action_item_ids_includes_docs_with_absent_deleted_field`:
the trap case — rows with no `deleted` field, and rows with an explicit
  `deleted: False`, must both still come back; only `deleted: True` is
  excluded, and no `deleted` filter reaches Firestore.
- New `test_visible_action_item_ids_records_firestore_read`: asserts the
`omi_firestore_read_operations_total{family="action_items_visible_ids",
  mode="unbounded"}` counter increments by exactly one per call.

Ran locally via `backend/test.sh` with a scoped file list
(`BACKEND_UNIT_TEST_FILE_LIST`) covering the touched test file plus the
neighboring action-item pagination and Firestore-read-cache suites — all
pass.

### Mutation testing

Four mutations against `database/action_items.py`, each turned red by an
existing or new test, then reverted:

| Mutation | Caught by |
| --- | --- |
| Remove the `.where(filter=FieldFilter('completed', ...))` push-down
(revert to scanning the whole collection) |
`test_visible_action_item_ids_matches_explicit_bucket_and_excludes_deleted`,
`test_visible_action_item_ids_excludes_legacy_null_completion_rows`,
`test_visible_action_item_ids_includes_docs_with_absent_deleted_field` |
| Add the forbidden `.where('deleted', '==', False)` server-side filter
|
`test_visible_action_item_ids_matches_explicit_bucket_and_excludes_deleted`,
`test_visible_action_item_ids_includes_docs_with_absent_deleted_field` |
| Remove the Python `if data.get('deleted'): continue` guard |
`test_visible_action_item_ids_matches_explicit_bucket_and_excludes_deleted`,
`test_visible_action_item_ids_includes_docs_with_absent_deleted_field` |
| Remove the `record_firestore_read(...)` call |
`test_visible_action_item_ids_records_firestore_read` |

## Product invariants affected

None — `scripts/pr-preflight --suggest` reports no locked invariant
paths
touched by this diff.

## Failure class

`scripts/pr-preflight --suggest` confirms this is a `fix:` commit
requiring a declaration. I checked `.github/failure-classes/` for a
genuine match: the closest candidates —
`FC-bounded-read-exceeds-request-budget` (about per-query limits
composing
against a request-scoped middleware budget, not applicable here —
there's
no request budget in play, just an unbounded per-user scan),
`FC-unbounded-user-collection-in-prompt` (about rendering a full
collection
into a provider/LLM prompt, not a Firestore billing concern), and
`FC-unthrottled-read-revalidation` (about a *client's* revalidation
cadence
lacking a throttle; that class already exists and its
`canonical_prevention_artifact` targets `desktop/windows` — this PR is
the
backend-side query fix, not the client cadence fix, and doesn't produce
a
new reusable guard surface) — none genuinely describe this specific
defect (a per-user Firestore scan filtering in Python instead of pushing
an equality predicate server-side, paired with a missing metering call).
Declaring `new` isn't warranted either: this is a narrow, already-tested
query and instrumentation fix, not a recurring class worth a permanent
registry entry on its own evidence.

Failure-Class: none


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/11849?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.

1 participant