Skip to content

perf(firestore): conversation-list cursor pagination behind conversation_list_cursor lever (WQ4) - #22450

Merged
Git-on-my-level merged 6 commits into
mainfrom
lane/firestore-reads-wq4-cursor
Oct 19, 2026
Merged

Git-on-my-level merged 6 commits into
mainfrom
lane/firestore-reads-wq4-cursor

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Product invariants affected

  • INV-FSR-LEVERS (firestore read lever plumbing: new conversation_list_cursor lever, 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)
  • INV-READ-BUDGET (list reads stay under the backend: prevent large list GETs from exhausting the 30s request budget #11831 ListReadBudget; cursor pages charge only rows actually streamed)
  • INV-CONTRACT-LIST-PAGE (offset pagination behavior and response shape unchanged while the lever is off; page_envelope=True + lever-on is the only path that returns next_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 existing offset contract. The server emits next_cursor only when the caller asks for page_envelope=True AND the conversation_list_cursor lever is on for that uid; existing clients keep using offset and see byte-identical responses.

Why

_collect_visible_conversation_page is ~22–24M billed reads/day (snapshot 2026-10-19T02Z: 1.02M reads/h ≈ 24.5M/day at 1h×24) because every list page re-scans limit+offset rows. A value cursor turns page N into a bounded scan of limit (+ the existing rule-discard skip cap) regardless of depth.

Behavior map (before → after, lever on, cursor provided)

  • page read cost: limit + offset (+ skip-cap walk) → limit (+ skip-cap walk); unit tests assert 2/2/2/2 vs offset's 2/8.
  • visibility flips mid-scroll: cursor advances past the boundary row exactly once (BookmarkDict keeps Firestore timestamp precision through the SDK's bookmark deepcopy — plain-dict deepcopy truncates to microseconds and re-served the boundary row on every page).
  • invalid/expired/tampered/cross-scope cursor: fallback to offset pagination + record_fallback metric, never a 5xx.
  • include_discarded=True and =False both cursor-capable; MCP/desktop paths unchanged while off.

Safety

  • Default-off lever (conversation_list_cursor absent from the prod FIRESTORE_READ_LEVERS literal → 0 per firestore_read_levers.py); registration into KNOWN_LEVERS is a separate dark PR like WQ2b, then a config ramp 5% → 100% behind the verify gate.
  • Cursor is HMAC-signed with ENCRYPTION_SECRET, scope-hash-bound (uid, filters, sort), TTL-limited (default 3600s), doc-id validated (no /, length caps).
  • No index changes, no schema changes, no client changes required.

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).
  • WQ1/WQ3 lease + queue-age suites still green: 50 passed.

View guided diff Turn on auto-fix

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

chatgpt-codex-connector Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-19T10:23:34.341476Z 697982b New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

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

Comment on lines +888 to +890
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',

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 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 👍 / 👎.

Comment on lines +34 to +35
if timestamp.tzinfo is None:
raise ValueError('cursor ordering key must be a timezone-aware timestamp')

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 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 👍 / 👎.

Comment thread backend/database/conversations.py Outdated
component='firestore_read',
from_mode='cursor',
to_mode='offset',
reason='invalid_payload',

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 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).
@Git-on-my-level

Copy link
Copy Markdown
Member Author

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:

  • real 1: finish() now catches (ValueError, TypeError, AttributeError) — null/corrupt ordering key omits the cursor instead of 500ing.
  • real 2: fallback reason invalid_payload -> malformed (ALLOWED_REASONS member).
  • minor 3: decode_cursor tolerates 60s issuer-ahead skew (age < -60).
  • nit 6/7: BODY_DIGEST reference used; BookmarkDict memo invariant documented.
  • minor 8: duplicate warning dropped (record_fallback's log line remains).
  • minor 4 (empty-page + next_cursor contract) and 5 (envelope shape parity across ramp) are router/enable-PR documentation items, noted here: clients must keep paging on empty conversations + non-null next_cursor; the router PR will document this and consider always-envelope under page_envelope=True.
    Suites after fixes: wq4 31/31, query_shapes 479/479 (m5-mbp).

…flict refresh)

# Conflicts:
#	backend/tests/support/firestore_query_driver_registry.py

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

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 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.
@Git-on-my-level
Git-on-my-level merged commit deeaba9 into main Oct 19, 2026
59 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/firestore-reads-wq4-cursor branch October 19, 2026 13:08
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
…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.
Git-on-my-level added a commit that referenced this pull request Oct 24, 2026
…_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. -->
Git-on-my-level added a commit that referenced this pull request Oct 30, 2026
…-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. -->
YinkaAdepoju pushed a commit to YinkaAdepoju/omi that referenced this pull request Oct 30, 2026
…-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.
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.

2 participants