Repository navigation
fix(backend): declare opposite-direction Firestore list-scan indexes (#11684) - #11687
aryanorastar wants to merge 3 commits into
Conversation
…asedHardware#11684) Automatic single-field indexes only cover field+__name__ in the same direction. The canonical /v3/memories scan uses updated_at DESC + __name__ ASC, which was dropped from the manifest and 503s in prod. Emit those composites and pin regression tests. Co-authored-by: Cursor <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
@kodjima33 @mdmohsin7 @Git-on-my-level sequencing call for #11684: This PR is the registry/manifest lock + regression tests. Please APPLY the four indexes in prod first ( I do not have prod APPLY rights; holding merge until a maintainer confirms apply. |
…11684) The registry dropped every single-field+__name__ spec from the composite manifest, but Firestore automatic indexes only cover field+__name__ in the same direction. updated_at DESC + __name__ ASC (and status ASC + __name__ DESC) are real composites; prod FailedPrecondition 400 'The query requires an index' surfaced as 503 Canonical memory unavailable. Narrow the predicate: opposite-direction __name__ tie-breaks are declared; same-direction singles and array-contains pairs stay out. Regenerates firestore.indexes.json with the four missing indexes (memory_items updated_at, memories updated_at/created_at, memory_review_queue status). Absorbs and supersedes #11687 (conflicting against current main; predicate re-expressed on the refactored _query_spec_index_requirements()). Merge only after the four indexes are APPLYed in prod via 'Reconcile Firestore Indexes' — firestore_readiness --check-only fails closed until they are READY. Co-authored-by: multica-agent <[email protected]>
…11684) The registry dropped every single-field+__name__ spec from the composite manifest, but Firestore automatic indexes only cover field+__name__ in the same direction. updated_at DESC + __name__ ASC (and status ASC + __name__ DESC) are real composites; prod FailedPrecondition 400 'The query requires an index' surfaced as 503 Canonical memory unavailable. Narrow the predicate: opposite-direction __name__ tie-breaks are declared; same-direction singles and array-contains pairs stay out. Regenerates firestore.indexes.json with the four missing indexes (memory_items updated_at, memories updated_at/created_at, memory_review_queue status). Absorbs and supersedes #11687 (conflicting against current main; predicate re-expressed on the refactored _query_spec_index_requirements()). Merge only after the four indexes are APPLYed in prod via 'Reconcile Firestore Indexes' — firestore_readiness --check-only fails closed until they are READY. Co-authored-by: multica-agent <[email protected]>
|
Conflicts with current main resolved on tip
Standing by on hold until a maintainer runs |
…+ converge cascade-retract CAS (#11684, #11726) (#11731) ## What changed and why Two production 5xx classes from the 2026-08-17 incident window (watchdog `75afe342f6f8`, serving SHA `6316415` = merged #11627), fixed in two independent commits: 1. **Missing opposite-direction Firestore list-scan indexes → 503 (#11684).** Serving queries order `updated_at DESC, __name__ ASC` (`read_canonical_scan_page`, plus the historical dual-stream scans and the review-queue status scan). Firestore automatic single-field indexes only cover `field+__name__` in the *same* direction, so these need real composites — but `_query_spec_index_requirements()` dropped every spec with ≤1 non-`__name__` field. Prod answered `FailedPrecondition: The query requires an index`, mapped to 503 `Canonical memory unavailable` / `Historical memory unavailable` on `GET /v3/memories` and the cascade-delete skip-guard scan. Fix: the predicate now declares exactly the opposite-direction pairs and regenerates the manifest with the four missing indexes (`memory_items` `updated_at DESC`+`__name__ ASC`; `memories` `updated_at DESC`+`__name__ ASC`; `memories` `created_at DESC`+`__name__ ASC`; `memory_review_queue` `status ASC`+`__name__ DESC`). Same-direction singles and array-contains pairs stay out (deploy rejects those as redundant). 2. **Cascade-retract CAS exhaustion → 500 (#11726).** Concurrent same-uid canonical writes all bump the one account-global `memory_state/apply_control` document. `replace_conversation_sourced_memories`' three *immediate* CAS attempts exhausted under that contention and raised an unhandled `RuntimeError` → `DELETE /v1/conversations/{id}?cascade=true` returned 500 while the Flutter client retried one conversation up to 12× and kept the storm fed. A repeat delete whose committed receipt went stale (another conversation's replacement advanced `source_generation`) livelocked on `source replacement operation already exists` the same way. Fix on the retract entry only (cascade delete + merge; the extraction replace path keeps its existing contract): bounded backoff retry (5 rounds, 0.05→0.5s), and after each conflict an epoch-guarded empty-cohort check — the same double-read control fence the replacement loop uses — returns the committed-empty result when a peer already retracted the source. Exhaustion raises typed `ConversationReplacementConflictError` (a `RuntimeError` subclass, so existing callers are unchanged), which `delete_conversation` maps to a retryable **503** *before anything is deleted*: the #11627 never-orphan-live-memories fence holds, and a retried delete is idempotent (receipt replay / already-retracted short-circuit). Closes #11684 Closes #11726 ## Relationship to open work - **Supersedes #11687** (aryanorastar's index fix). That branch conflicts with current main — main refactored the predicate into `_query_spec_index_requirements()` — so this PR re-expresses the same semantic change there, ports its test fix verbatim (`test_firestore_config_does_not_declare_same_direction_single_field_composites` + the four-tuple declaration test), and regenerates the manifest through the generator rather than hand-patched JSON hunks. Credit for the measured predicate direction belongs to #11684/#11687. - **Does not replace #11727** (draft: zero-write retraction while intake is paused). That PR targets the fenced-intake path; this PR converges the open-intake CAS path. Whichever lands second will need a small rebase; the touched regions barely overlap. - Out of scope, per #11726: #11685/#11688 extract abort, MEMORY_MODE/cohort/control-schema redesign, client-only backoff. ## Merge sequencing (required) `firestore_readiness` runs `reconcile_firestore_indexes.py --check-only` on backend deploys and **fails closed until every manifest index is READY**. Merge only after a human runs `Reconcile Firestore Indexes` → `prod` → `APPLY_FIRESTORE_INDEXES` (dev first is fine) — that APPLY alone stops the 503s even before this PR merges. Split-merging (declaration after APPLY lands separately) is a later human decision; nobody should run APPLY from this PR. ## How it was verified - `pytest tests/unit/test_firestore_index_config.py tests/unit/test_firestore_indexes.py tests/unit/test_reconcile_firestore_indexes.py tests/unit/test_firestore_query_contract.py` → **62 passed** (was 61 on the wrong predicate; the renamed same-direction test no longer codifies the bug and the new opposite-direction declaration test pins all four indexes). - `python3 backend/scripts/generate_firestore_indexes.py --write` then read-mode → `firestore.indexes.json matches the Firestore index registry`; diff adds exactly the 4 entries (+56 lines, same shape as #11687). - `python3 backend/scripts/firestore_query_coverage.py --check-ratchet` → exit 0 (coverage keys on query signatures; QUERY_SPECS unchanged → no baseline drift). - `pytest tests/unit/test_cascade_retract_convergence.py tests/unit/test_delete_conversation_cascade_retraction_fence.py` → **7 passed**: injected `ConversationSourceReplacementConflict` rounds converge with bounded backoff; repeat retract with a stale receipt returns already-retracted instead of livelocking; exhausted conflicts with live items still raise (conversation + memories intact, #11627 fence); route maps the typed conflict to 503 before any delete. - Affected memory suites: `pytest tests/unit/test_ws_i_hardening.py tests/unit/test_ws_j_delete_privacy.py tests/unit/test_memory_apply_store.py tests/unit/test_memory_replace_policy.py tests/unit/test_merge_conversations_canonical_delete.py tests/unit/test_merge_skips_retraction_without_canonical_memories.py tests/unit/test_universal_memory_service.py tests/unit/test_atomicity_lifecycle_regressions.py` → **173 passed**. - Scan-read/fake-contract: `pytest tests/unit/test_bounded_firestore_list_reads.py tests/unit/test_firestore_fake_contract.py` → **12 passed**. - `scripts/pr-preflight --suggest` → INV-MEM-1 required; failure-class protocol honored below. Not verified here: live Firestore behavior (no APPLY, no prod/dev writes — the four indexes must be provisioned by a human via the workflow above). ## Tests - Index half regression: `backend/tests/unit/test_firestore_index_config.py::test_firestore_config_declares_opposite_direction_universal_list_scans` (fails on main's manifest) and the renamed same-direction test (fails if the predicate over-declares). - CAS half regression: `backend/tests/unit/test_cascade_retract_convergence.py` (three behavioral tests: convergence under injected conflicts, stale-receipt idempotency, fail-closed exhaustion) + `test_delete_conversation_cascade_retraction_fence.py::test_exhausted_replacement_conflict_maps_to_retryable_503_before_any_delete`. ## Product invariants affected INV-MEM-1 ## Failure class (fixes) Failure-Class: FC-undeclared-serving-query-index (That class covers the index half exactly — a serving query's composite index missing from the registry manifest. The CAS half has no existing class in the registry; it is a candidate for a new class — "account-global CAS exhaustion surfaced as an unhandled 500 on a retryable, idempotent operation" — to be registered separately per the transition-narrative protocol, not inline in this fix PR.) Line-Count-Exception: backend/routers/conversations.py | 1515 -> 1527 | retryable-503 mapping for the cascade-retract conflict (#11726) is a few lines inside the existing delete route; splitting the router is out of scope for an incident fix Line-Count-Exception: backend/utils/memory/canonical_memory_adapter.py | 2388 -> 2491 | retract convergence loop + epoch-guarded completion check + typed conflict error live with the CAS loop they wrap (#11726); extraction into a new module would split the replace/retract boundary mid-incident ## Residual risk - The 503-after-exhaustion path is still a 5xx by design — but only after 5 backoff rounds *and* a proven-non-empty source, with nothing deleted and a safe client retry; the incident's unbounded 12×-retry 500 loop is gone (converges or fails closed). - The already-retracted short-circuit trusts the same double-read fence the replacement loop uses; it cannot skip a retract that still has live items (live items → keep retrying → raise). - Multi-instance Cloud Run: the backoff converges cross-instance via the control CAS itself; there is no cross-instance lock (deliberately — the smallest shape #11726 sanctioned). <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/11731?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. -->
|
Thanks for the review and write-access approval! Confirmed: holding merge until a maintainer with production permissions runs |
|
Resolve the branch conflicts before merging @aryanorastar |
…ist-scan-index # Conflicts: # backend/database/firestore_index_registry.py # firestore.indexes.json
|
@RatnamOjha conflicts resolved on tip Two conflicts, both from main-side additions rather than competing edits:
Test suite on the merged tip: 69 passed ( The new commits dismissed the prior approval, so this needs a re-approve — @kodjima33 when you have a moment. Merge sequencing is unchanged and still stands: please hold the merge until the four indexes are APPLYed in prod, or |
|
Repo check is still failing; check the formatting once. |
|
Closing this as superseded — and correcting my own last comment, which was wrong. This PR no longer contains its fix. @kodjima33 called it three days ago: "#11731 supersedes the predicate change on current main". #11731 merged on 2026-08-18 and closed #11684 in the same moment. Verified against current main:
So there is nothing left here to merge, and the merge-sequencing hold this PR was carrying is moot: the indexes it asked to have APPLYed are already declared on main. The formatting failure and the I have pinned my toolchain to the CI-matching Flutter version so it cannot recur, and I am closing rather than pushing the cleanup, since a green no-op PR still costs a review. Reopen-worthy only if someone wants the baseline decrement on its own, which I do not think is worth a PR given the ratchet passes either way. |
|
Hey @aryanorastar 👋 Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request. After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:
Before your next PR, please skim:
If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing. Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out. Thank you for being part of the Omi community! |
Summary
GET /v3/memories→ 503 Canonical memory unavailable (GET /v3/memories 503s in prod: the canonical scan orders updated_at DESC + __name__ ASC, an index Firestore never builds automatically and the registry never declares #11684):updated_at DESC, __name__ ASCis not an automatic Firestore index, butINDEX_REQUIREMENTSdropped every single-field+__name__spec.__name__tie-breaks are real composites; same-direction singles stay out (Firestore rejects them as redundant).firestore.indexes.jsonwith the four missing indexes (memory_itemsupdated_at,memoriesupdated_at/created_at,memory_review_queuestatus).Merge sequencing (required)
Do not merge this PR until the four indexes exist in prod (and preferably auto-dev).
firestore_readinessrunsreconcile_firestore_indexes.py --check-onlyon backend deploy. Merging the manifest before APPLY blocks deploys until the indexes are live.Correct order (from #11684):
Reconcile Firestore Indexes→prod→APPLY_FIRESTORE_INDEXES(stops the 503s even before this PR).Test plan
pytest tests/unit/test_firestore_index_config.py test_firestore_indexes.py test_reconcile_firestore_indexes.py test_firestore_query_contract.py→ 61 passedpython3 backend/scripts/generate_firestore_indexes.pyverify clean after--writeHonest gaps
APPLY_FIRESTORE_INDEXES(prod environment reviewers). Live 503 stop depends on that apply; this PR locks the declaration + tests.Failure-Class: none
Product invariants affected
INV-MEM-1