Repository navigation
perf(firestore): conversation-list cursor pagination behind conversation_list_cursor lever (WQ4) - #22450
Conversation
…ion_list_cursor lever (WQ4) - Opaque signed value cursor (created_at + doc id, HMAC, scope-bound, TTL) alongside offset; server emits next_cursor only when page_envelope is requested and the lever is on for the uid; clients ignore it until adopted. - BookmarkDict: the SDK deep-copies bookmarks and plain-dict deepcopy truncates DatetimeWithNanoseconds to microseconds, which re-served the boundary row every page; the cursor dict copies around it. - Budgeted page fill with the existing rule-discard skip cap; invalid/expired cursors fall back to offset pagination with a fallback metric. - Lever unregistered in this PR (like WQ2b): enabling is a follow-up config change after KNOWN_LEVERS registration. Tests: 31 new unit tests (read counts 2/2/2/2 vs offset 2/8, visibility flips, codec TTL/signature/scope, SDK compile path).
…istry (WQ4) get_conversations/get_conversations_without_photos gain cursor/page_envelope/cursor_page neutrals (no filter or order effect), _collect_cursor_conversation_page is a covered-by helper pinned expect_observed=False (it only runs with the lever on; drivers run levers off) with a body digest so any edit re-triggers review.
…ype clean) encode_cursor's timestamp param is typed datetime and decode_cursor's token is typed str; the runtime ValueError paths for wrong types are already covered by the codec's broad except-clause. Unblocks the pre-push backend typecheck phase.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 18e020cde3
ℹ️ 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".
| reason='cursor page collector only runs when the conversation_list_cursor lever is on; drivers run with levers off', | ||
| expect_observed=False, | ||
| body_digest='1d5fc817a402bd5bb5cb8fae5492d29b1e34cb4a15405bd06a784fc8730fa4e9', |
There was a problem hiding this comment.
Exercise the cursor query in the Firestore guard
This entry explicitly marks the new cursor collector as unobserved because every registered driver runs with the lever off. Consequently, the guard only validates the legacy offset queries and never sees the lever-on branch that appends order_by('__name__') and applies a value cursor across the supported filter/projection profiles; registering or enabling the lever later can therefore ship that serving shape without the repository's query/index validation. Add a lever-on driver profile with a valid cursor rather than exempting the branch from observation.
AGENTS.md reference: backend/AGENTS.md:L177-L181
Useful? React with 👍 / 👎.
| if timestamp.tzinfo is None: | ||
| raise ValueError('cursor ordering key must be a timezone-aware timestamp') |
There was a problem hiding this comment.
Handle legacy non-datetime ordering keys when issuing cursors
When a returned legacy conversation has a string-valued created_at/started_at, Firestore can still order and return it, and the existing read path can pass an ISO string through for response-model coercion. Cursor issuance now dereferences timestamp.tzinfo, however, so this raises AttributeError; _collect_visible_conversation_page.finish() only catches ValueError, turning an otherwise readable page into a 500 whenever such a row is the page boundary. Validate or coerce the ordering value and raise ValueError so the documented “next cursor omitted” fallback is used.
Useful? React with 👍 / 👎.
| component='firestore_read', | ||
| from_mode='cursor', | ||
| to_mode='offset', | ||
| reason='invalid_payload', |
There was a problem hiding this comment.
Use a registered fallback reason for invalid cursors
invalid_payload is not in utils.observability.fallback.ALLOWED_REASONS, so record_fallback() normalizes every invalid, expired, tampered, or cross-scope cursor event to reason="other". Once this lever is ramped, the fallback metric therefore loses the reason label this callsite intends to emit and pollutes the unknown-reason bucket used for operational monitoring; use an existing registered reason such as malformed, or register the new bounded reason.
Useful? React with 👍 / 👎.
- finish() catches (ValueError, TypeError, AttributeError): a null/corrupt ordering key must omit the cursor, not 500 the route. - fallback reason invalid_payload -> malformed (an ALLOWED_REASONS member); drop the duplicate warning line next to record_fallback. - decode_cursor tolerates 60s of issuer-ahead clock skew (age < -60) to stop spurious fallbacks. - registry covered-by entry references BODY_DIGEST instead of a second literal; BookmarkDict comment pins the immutable-value invariant. - tests assert on the record_fallback log line instead of the removed warning. Verdict chain: glm-5.3 r1 FIX-REQUIRED (exec-attend-foster-option-all-journey-upgrade, 2 real + 3 minor + 3 nit; both real fixed, minors 3/4/5/8 addressed, nit 6/7 addressed; minor 4 (empty-page contract) and 5 (envelope shape parity) are router/PR-documentation items tracked for the enable PR).
|
Review round 1 (zcode glm-5.3, exec-attend-foster-option-all-journey-upgrade): FIX-REQUIRED with 2 real + 3 minor + 3 nit findings. All addressed in 1c2a19b:
|
…flict refresh) # Conflicts: # backend/tests/support/firestore_query_driver_registry.py
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 697982b27d
ℹ️ 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".
| conversations: List[Dict[str, Any]] = [] | ||
| try: | ||
| for doc in budgeted_stream_iter(conversations_ref, budget): | ||
| last_doc = doc |
There was a problem hiding this comment.
Preserve the unfinished offset before issuing a cursor
When include_discarded=True, a lever-on request with a nonzero offset can exhaust its ListReadBudget while skipped_visible < offset; because last_doc is already set, finish() issues a cursor after the last scanned document. Following that cursor then starts returning rows immediately instead of skipping the remainder of the requested offset, so a truncated deep page can expose earlier rows or duplicate rows from preceding pages. Do not issue this cursor until the offset has been fully consumed, or encode the remaining offset in the continuation.
Useful? React with 👍 / 👎.
…lation fixture (WQ4) The fixture replaces the utils package with stubs; database.conversations now imports utils.conversation_page_cursor at module level, so shard 4's ModuleNotFoundError came from the stubbed path, not a missing file. Load the real codec before stub_modules closes utils.
…22450, #22497 sync) E1 (batch policy snapshot) conflicted with legacy-retire in 7 files; per-owner resolutions: - lane 8: database/batch_pipeline_intake.py, utils/batch_pipeline/intake.py, live_upload.py (E1 policy= + admit enqueue=/adopt= hooks), provider_stt.py (enqueue hook takes policy=). - lane 9: utils/sync/reprocess.py stays the alias shim; E1's first-summary policy snapshot is ported into utils/enrichment/outbox.py (mark_update/run), outbox_firestore claim_key/consumer and projection.mark_enrichment; config/policy/guard.py RESOLUTION_EDGES moved to the outbox (lead sign-off, Sol FYI). - lane 6: config/batch_live_preview.py takes E1; config/policy/batch.py reads the _ramp runtime percents in resolve_batch_policy when flags is None (lead sign-off; Sol no objection). test_runtime_percent.py covers ramp wins/recorded, env fallback, explicit flags never read _ramp, retire clamped after runtime batch, and source-blind policy_id. - lane 1: routers/batch_pipeline.py drops the env read (E1) and keeps the 409 kill switch. Verified (unit, m5): runtime_percent, batch_unit_policy (E1 guard), batch_stage_policy, batch_pipeline_serving, quarantine_recovery, batch_provider_stt, outbox_firestore, enrichment_route, task_target_retry_semantics, app_roles census: 359 passed, 3 xfailed.
…_queries lever keys (dark, config unchanged) (#23390) ## Summary Register `conversation_list_cursor` and `finjob_candidate_queries` in backend `KNOWN_LEVERS`, with their origin callers documented. Registration makes both keys addressable; an absent percentage remains 0/off. No `FIRESTORE_READ_LEVERS` YAML literal or other config value changes. The cursor behavior is already merged in #22450. Finalization candidate-query behavior remains separate on `lane/firestore-reads-wq13-candidates` at `13e1eeea47`; this PR neither imports nor depends on that code. The cursor tests now use the production registry instead of patching in the key. ## Product invariants affected - INV-FSR-LEVERS — registration only; missing keys remain off, and runtime configuration remains the sole rollout authority. - INV-READ-BUDGET — query behavior and read budgets are unchanged; query-shape and cursor read-count coverage run unchanged apart from removing the registry patch. - INV-CONTRACT-LIST-PAGE — existing pagination behavior and response contracts remain unchanged while the cursor lever is absent/off. These are the IDs cited by #22450; #22205's registration pattern cited no invariant IDs. ## Verification - 674 tests passed: lever registry 19, cursor contracts 31, rendered runtime-env literal contracts 93, pusher config references 28, query-shape suite 503. Each suite ran in a separate pytest process using `backend/.venv` through `omi-heavy`. - Command: `backend/.venv/bin/python -m pytest backend/tests/unit/<suite>.py -q` for each of the five suites above; rendered-literal expectations unchanged. - Broader Firestore index guard: all seven contract files passed. - `make preflight`: all 32 checks passed. Pre-push also validated the committed three-file diff and the real PR body file: all 32 checks passed. - No GCP tier used; no cloud access needed. UI-Evidence: none — backend registry only, no UI change. Failure-Class: none ## Rollout and rollback Both keys remain dark because their config percentages are absent. No rollout is requested here; deployment and any later configuration change belong to the rollout lead. Revert this registration commit to roll back. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/23390?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="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <a href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/23390?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F23390&source=description" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img alt="Turn on auto-fix" src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
…-key delta, umt split preserved) (#24088) ## Summary Firestore read lever config — enable `conversation_list_cursor` 0 -> 5. Single-key delta on main's 19-key literal (20-key result); every other key byte-identical, including the `usage_month_total` split (0 base/charts + pins / 100 prod.overlay Cloud Run-only, `FSR_USAGE_MONTH_TOTAL_EPOCH` epochs unchanged). Reason: the cursor code path is merged-dark since #22450 (WQ4) and its `KNOWN_LEVERS` registration landed with WQ15; the enable path has been unblocked since WQ13 shipped. `conversations:_collect_visible_conversation_page` is the top surviving lane-owned origin (~1.27M reads/h backend, snapshot 2026-10-30T05:00:17Z, ~30M/day at 1hx24). Server-side enable is capability-only — savings land when clients adopt the opaque cursor — so the ramp is expected to run dark (verify WEAK) until then; 5% now starts that clock. ## Product invariants affected - INV-FSR-LEVERS (replace-mode literal rule respected; the new key rides KNOWN_LEVERS already on main, default-off sites unchanged) - INV-READ-BUDGET (cursor pages charge only rows actually streamed; list reads stay under the ListReadBudget) - INV-CONTRACT-LIST-PAGE (offset behavior unchanged; `page_envelope=True` + lever-on is the only path that returns `next_cursor`; 5% cohort only) - INV-MEM-4 (required by the `backend/deploy/runtime_env.yaml` generated-manifest lock; the change is the rendered FIRESTORE_READ_LEVERS literal only — no intake, promotion, or authority-path semantics) Failure-Class: none ## Verification - `set_levers.py` REPLACE-mode with the full 20-key literal; `prod.overlay.yaml` hand-patched (set_levers does not match its inline literal form) to keep the `usage_month_total` Cloud Run-only 100 override; `compose_runtime_env.py` + `render_feature_flag_registry.py` re-run. - Diff audit: every changed literal differs ONLY in `conversation_list_cursor` (0 -> 5); value-multiset invariant check vs HEAD green for all other lever keys across all 10 touched files; `usage_month_total` split preserved. - Contract tests: 174/174 pass on the branch (`test_render_backend_runtime_env.py` + `test_verify_pusher_config_references.py` + `test_fsr_wq4_cursor.py` + `test_firestore_read_levers.py`, lane venv 3.11.15). - Full CI: running on this head. ## Lead-owned ship plan Deploy needed: listen -> pusher -> Cloud Run (train order per RUNBOOK). Config rides the next routine trains; GKE legs additionally still owe the #23939 people:0 roll — this key joins the same catch-up train, not a new one. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/24088?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="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <a href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/24088?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24088&source=description" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img alt="Turn on auto-fix" src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
…-key delta, umt split preserved) WQ4 enable step: cursor code merged-dark in BasedHardware#22450, KNOWN_LEVERS registration on main. 20-key literal; usage_month_total split preserved (0 base/charts/pins, 100 prod.overlay). Contract tests 174/174 (lane venv). Loop: firestore-reads.
Product invariants affected
conversation_list_cursorlever, default-off, replace-mode literal rule respected — the key is simply absent from the prod literal until KNOWN_LEVERS registration lands, which makes it a no-op)ListReadBudget; cursor pages charge only rows actually streamed)page_envelope=True+ lever-on is the only path that returnsnext_cursor)Line-Count-Exception: backend/database/conversations.py | 4276 -> 4423 | cursor pagination lives beside the offset collector it must stay byte-compatible with; splitting the collector family mid-lever would desync the two paging paths this PR keeps under one review
Failure-Class: none
What
Conversation list pagination gains an optional opaque value cursor (
created_at+ doc id, HMAC-signed, scope-bound to uid+filters+sort, 1h TTL) served alongside the existingoffsetcontract. The server emitsnext_cursoronly when the caller asks forpage_envelope=TrueAND theconversation_list_cursorlever is on for that uid; existing clients keep usingoffsetand see byte-identical responses.Why
_collect_visible_conversation_pageis ~22–24M billed reads/day (snapshot 2026-10-19T02Z: 1.02M reads/h ≈ 24.5M/day at 1h×24) because every list page re-scanslimit+offsetrows. A value cursor turns page N into a bounded scan oflimit(+ the existing rule-discard skip cap) regardless of depth.Behavior map (before → after, lever on, cursor provided)
limit + offset (+ skip-cap walk)→limit (+ skip-cap walk); unit tests assert 2/2/2/2 vs offset's 2/8.BookmarkDictkeeps Firestore timestamp precision through the SDK's bookmark deepcopy — plain-dict deepcopy truncates to microseconds and re-served the boundary row on every page).record_fallbackmetric, never a 5xx.include_discarded=Trueand=Falseboth cursor-capable; MCP/desktop paths unchanged while off.Safety
conversation_list_cursorabsent from the prodFIRESTORE_READ_LEVERSliteral → 0 perfirestore_read_levers.py); registration intoKNOWN_LEVERSis a separate dark PR like WQ2b, then a config ramp 5% → 100% behind the verify gate.ENCRYPTION_SECRET, scope-hash-bound (uid, filters, sort), TTL-limited (default 3600s), doc-id validated (no/, length caps).Rollback
Revert; or set the lever key to 0 / drop it from the literal (config-only, no code roll needed). Old clients never send cursors, so nothing else changes.
Verification
backend/.venv/bin/python -m pytest backend/tests/unit/test_fsr_wq4_cursor.py -q→ 31 passed (m5-mbp, 2026-10-19).