Skip to content

fix(backend): declare opposite-direction Firestore list-scan indexes (#11684) - #11687

Closed
aryanorastar wants to merge 3 commits into
BasedHardware:mainfrom
aryanorastar:fix/11684-canonical-list-scan-index
Closed

aryanorastar wants to merge 3 commits into
BasedHardware:mainfrom
aryanorastar:fix/11684-canonical-list-scan-index

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Aug 16, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Merge sequencing (required)

Do not merge this PR until the four indexes exist in prod (and preferably auto-dev).

firestore_readiness runs reconcile_firestore_indexes.py --check-only on backend deploy. Merging the manifest before APPLY blocks deploys until the indexes are live.

Correct order (from #11684):

  1. Human: Reconcile Firestore Indexes → prod → APPLY_FIRESTORE_INDEXES (stops the 503s even before this PR).
  2. Then merge this PR so the registry matches the deployed schema and regressions stay pinned.

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 passed
  • python3 backend/scripts/generate_firestore_indexes.py verify clean after --write
  • Maintainer APPLY of the four indexes in prod / auto-dev before merge

Honest gaps

  • Author cannot run 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

Review in cubic

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

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

@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 (Reconcile Firestore Indexes → APPLY_FIRESTORE_INDEXES) — that alone stops the /v3/memories 503s. Merge this PR only after the indexes are live so firestore_readiness does not block backend deploys.

I do not have prod APPLY rights; holding merge until a maintainer confirms apply.

@cubic-dev-ai cubic-dev-ai 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.

No issues found across 3 files

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Re-trigger cubic

Git-on-my-level added a commit that referenced this pull request Aug 17, 2026
…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]>
Git-on-my-level added a commit that referenced this pull request Aug 17, 2026
…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]>

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

correct root-cause fix for the #11684 503s; holding the merge until a human runs the Firestore index APPLY (and #11731 supersedes the predicate change on current main)

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

@kodjima33 @Git-on-my-level

Conflicts with current main resolved on tip 26d50ec538:

  1. Registry Merge: Merged _index_fields_need_composite_manifest with the deduplicated _query_spec_index_requirements logic.
  2. Indexes Regenerated: firestore.indexes.json and query coverage baseline updated cleanly.
  3. Tests: All 62 unit tests passed (test_firestore_index_config.py, test_firestore_indexes.py, test_reconcile_firestore_indexes.py, test_firestore_query_contract.py).

Standing by on hold until a maintainer runs APPLY_FIRESTORE_INDEXES in prod before merge.

Git-on-my-level added a commit that referenced this pull request Aug 18, 2026
…+ 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. -->

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

Correct root-cause fix for the #11684 503s with tests. Not merging yet: per the PR's own sequencing note the four indexes must be APPLYed in prod first, or firestore_readiness blocks backend deploys.

@aryanorastar

aryanorastar commented Aug 18, 2026 •

Copy link
Copy Markdown
Collaborator Author

@kodjima33 @Git-on-my-level

Thanks for the review and write-access approval!

Confirmed: holding merge until a maintainer with production permissions runs APPLY_FIRESTORE_INDEXES in prod. Once the composite indexes are live, this PR is 100% CI green, conflict-free, and ready to merge to lock in the manifest declaration and regression tests.

@RatnamOjha

Copy link
Copy Markdown
Collaborator

Resolve the branch conflicts before merging @aryanorastar

…ist-scan-index

# Conflicts:
#	backend/database/firestore_index_registry.py
#	firestore.indexes.json
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

@RatnamOjha conflicts resolved on tip befbc309.

Two conflicts, both from main-side additions rather than competing edits:

  • backend/database/firestore_index_registry.py — main appended CHAT_FIRST_DEFERRALS_DUE_QUERY, CHAT_FIRST_DEFERRALS_SUBJECT_QUERY, and MEETING_RECEIPTS_DUE_QUERY to QUERY_SPECS while this branch touched the same tuple. Kept both sides; nothing dropped.
  • firestore.indexes.json — generated, so regenerated from the resolved registry rather than hand-merged. generate_firestore_indexes.py verifies clean: "firestore.indexes.json matches the Firestore index registry".

Test suite on the merged tip: 69 passed (test_firestore_index_config.py, test_firestore_indexes.py, test_reconcile_firestore_indexes.py, test_firestore_query_contract.py) — up from 61 pre-merge, the delta being main's three new query specs now covered.

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 firestore_readiness will block backend deploys.

@RatnamOjha

RatnamOjha commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator

Repo check is still failing; check the formatting once.
Also, resolve the remaining branch conflict in the file app/test/unit/apps_filter_labels_test.dart

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

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:

  • backend/database/firestore_index_registry.py and firestore.indexes.json on this branch are now byte-identical to main — the composite-index declarations already shipped.
  • After removing the noise described below, this branch's entire remaining diff is one file, two lines: firestore_query_coverage_baseline.json going eligible_serving 70→69 and registered_serving 24→23.
  • That change is not load-bearing either. I ran scripts/firestore_query_coverage.py --check-ratchet against both baselines on the merged tree — main's baseline passes and this branch's baseline passes. It does no work.

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 apps_filter_labels_test.dart conflict were mine, not main's. @RatnamOjha — apologies for the two passes this cost you. When I merged main in earlier, my local Flutter SDK was on the wrong channel, and the pre-commit hook reformatted and committed 25 unrelated Dart files into what is a backend-only PR. That is the whole content of the Repo Checks / Formatting failure and the remaining conflict. My "conflicts resolved" comment above was accurate about the two real conflicts and silently wrong about everything else in the diff — that is on me, and I should have checked the diff scope before claiming it was clean.

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.

@github-actions

Copy link
Copy Markdown
Contributor

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:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

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!

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.

3 participants