Skip to content

SCA-4102: v3 Home reads recent history through the visibility index, no backfill - #26684

Merged
Git-on-my-level merged 5 commits into
mainfrom
lane/sca4102-cutoff-reader
Nov 29, 2026
Merged

Git-on-my-level merged 5 commits into
mainfrom
lane/sca4102-cutoff-reader

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

SCA-4102: v3 Home reads about one document per row for recent history, with no backfill.

Why

Home's first request (GET /v1/conversations?limit=50) is what users wait on when they open the app. In ro-prod sampled request logs read 2026-11-29 01:24Z, it took 1.46 s at p50, 9.8 s at p90 and 24 s at p99. Hidden v3 rows (raw recordings and hidden windows) make the legacy scan read many more documents than it returns. SCA-4102 records about 550 documents per 50-row page on v3 accounts. #26204 added and stamped home_list_visible, but rows written before those writers have no bit. So the reader only admitted owners whose whole collection had been backfilled, and none were.

What changes

Hybrid reader (database.conversations.get_home_hybrid_conversations). This follows the no-backfill design approved on SCA-4102.

  • On first use, each admitted owner gets a cutoff: the newest created_at across all of their conversations. One descending probe reads it, at limit 1 with a created_at field mask, and it is stored once at users/{uid}/home_list_index/cutoff. Every row above the cutoff was created or moved there by a stamping writer.
  • A page reads created_at > cutoff through the index. When that slice runs out, the rest of the page comes from the legacy scan, which starts at the cutoff inclusive via start_at, not a range filter.
  • Cursors bind the branch and the cutoff into their signed scope.
  • The owner stays on legacy when the newest key is in the future, is not a timestamp, or the lookup fails.
  • A stored cutoff never moves. Two pods certifying at once keep the first create.

Route negotiation. No app change is needed. The app already sends auto on page one and repeats the server's answered mode afterwards.

  • auto page one is served hybrid and answers indexed. indexed with a valid cursor continues the hybrid read.
  • These cases return page one and answer legacy, which makes the app re-fetch from the top: an auto continuation (F3), a cursorless indexed continuation, and a cursor from another cutoff or an expired or tampered one.
  • Released clients that send no header are unchanged.

Controls.

  • OMI_HOME_VISIBILITY_INDEX_ENABLED is the kill switch, on unless set off.
  • The served cohort is OMI_HOME_VISIBILITY_INDEX_OWNERS plus OMI_HOME_VISIBILITY_INDEX_PERCENT, which defaults to 0.
  • OMI_HOME_VISIBILITY_INDEX_AUDIT_PERCENT (default 0) is the production shadow. Legacy-served pages check each visible row above the owner's cutoff for home_list_visible == true. A missing or false bit is exactly a row the index would hide. The audit reads no extra rows; certifying the cutoff costs one read and one write per owner, once.
  • Metrics: omi_home_index_{cutoff,pages,storage_rows,audit_rows}_total, plus home_branch on the conversation_list_read log line. All are aggregate counts with no ids or content.

Writer fixes from the R42 triage of #26204.

  • F1 (separate field) was already fixed before SCA-4102: Index visible v3 Home conversations #26204 merged.
  • F2: update_conversation retries a fenced visibility patch up to 3 times, re-reading and restamping, instead of raising on a concurrent write.
  • F3: covered by the route negotiation above.
  • F4: a test pins that a processing result with neither flag writes no bit.
  • New, from the writer audit: a created_at move now restamps in update_conversation and in the processing-result write, but only when the value actually changes. Unchanged results stay write-free.

Writer audit. Every production path that creates a conversation, changes recording or home_hidden, or moves created_at either stamps the bit or cannot change it. That covers Python request routes, Cloud Tasks jobs, the v3 builder and rederive, sync assignment and Go finalization. The only unstamped creators are staging, harness and emulator seeders and one one-off timestamp migration. Those are listed in the SCA-4102 comment.

Ramp plan (default-off cohort)

The design requires a shadow and Margin GO before serving, so the served cohort ships at 0.

  1. Audit. Pipeline sets AUDIT_PERCENT=100 once David approves the one-time certification writes. Clean metric: omi_home_index_audit_rows_total{result!="ok"} stays at 0 for a full day. Done by 2026-12-05.
  2. Named owners, then percentage. Release adds named owners (David first), then ramps PERCENT through 1, 10, 50 and 100, one full lookback per stage, after Margin GO under SCA-3891. Clean metric: the audit stays at 0, recent pages read about 1 document per row, and list p95 and 5xx are no worse than the legacy arm. Done by 2026-12-12.
  3. Rollback. Set OMI_HOME_VISIBILITY_INDEX_ENABLED=false. Indexed continuations restart at page one. Keep the stamps and the stored cutoffs.

Data and privacy

The cutoff document holds only a timestamp, the certification time and a version. Account erasure already enumerates and deletes every subcollection under users/{uid}. The bit stays in storage; the API's response model drops it.

Verification

Hermetic unit tests, run through test.sh:

  • test_home_hidden_run_pagination.py: full walks show the hybrid read serves exactly the legacy rows in order, for 5 shapes with and without tied timestamps. The recent slice reads one document per row across 1,200 hidden rows. A page crossing the cutoff keeps rows tied at the cutoff in the tail exactly once. Restart cases, the kill switch and the audit are covered.
  • test_home_index_cutoff.py: certification, memoization, refusals, the concurrent-create race, cohorts, the F2 retry, and created_at restamping.
  • test_conversation_terminal_family.py: F4, and restamping only when created_at actually moves.
  • Contract suites: caller witnesses, query-shape registry, reason labels, archive filter.

No production reads or writes, deploys or config changes were made in this PR.

🤖 Generated with Claude Code

Product invariants affected

none

Line-Count-Exception: backend/database/conversations.py | 5681 -> 5841 | the hybrid Home reader must share the private list collector, cursor scope and page fill it extends; a split would duplicate that path or widen private helpers
Line-Count-Exception: backend/routers/conversations.py | 3482 -> 3523 | the Home page-mode negotiation lives with the list route it governs

Git-on-my-level and others added 2 commits November 28, 2026 22:42
…ckfill

Default v3 Home pages read created_at > cutoff through home_list_visible,
then fill from the legacy scan positioned at the cutoff. The cutoff is the
owner's newest created_at, certified once after the stamping writers and
stored at users/{uid}/home_list_index/cutoff. Cursors bind branch and
cutoff; ambiguous or foreign continuations restart at page one (F3).

Adds the OMI_HOME_VISIBILITY_INDEX_ENABLED kill switch, a percent cohort
(default 0), a zero-read bit audit for legacy-served owners (default 0),
and aggregate counters. update_conversation retries a fenced visibility
patch (F2); created_at moves restamp; F4 is pinned by a test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-29T04:51:53.336555Z 284013c 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: 4a9d34722f

ℹ️ 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 thread backend/database/conversations.py Outdated
changes_visibility = any(flag in prepared_data for flag in home_visibility_index.FLAGS)
# A created_at move can carry an unstamped row above an owner's Home index cutoff, so it
# restamps (from the fenced snapshot) like a change to either source flag.
changes_visibility = any(field in prepared_data for field in _HOME_INDEX_TRIGGER_FIELDS)

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 Fence created_at updates only when the timestamp changes

For existing conversations with a created_at, _prepare_conversation_for_write copies that field from conversation_state even when the caller only updates an unrelated field. Consequently, this presence check now treats ordinary language, title, or calendar edits as visibility changes, rewrites the index bit, and applies an update-time precondition. On actively updated conversations, previously independent edits can therefore exhaust the three retries and fail with FailedPrecondition. Compare the prepared timestamp with the stored timestamp, as the processing-result path does, and add created_at to the unrelated-patch test fixture so it covers normal stored rows.

Useful? React with 👍 / 👎.

Comment on lines +224 to +225
if client is None:
from database._client import db as client

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 Resolve the cutoff client through the required Firestore getter

When no client is injected, this new helper imports the legacy db proxy instead of resolving get_firestore_client() at the call boundary. backend/AGENTS.md explicitly says that the proxy is for legacy compatibility only: “do not use it in new code.” Use the getter here and expose the documented keyword-only firestore_client injection parameter so the new persistence boundary follows the repository's client-selection and testing convention.

AGENTS.md reference: backend/AGENTS.md:L179-L179

Useful? React with 👍 / 👎.

Comment on lines +248 to +251
except Exception as error: # the legacy read is always correct; never fail Home over the index
_CUTOFF['error'].inc()
logger.warning('home_index_cutoff unavailable exception_type=%s', type(error).__name__)
return None

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 Record the cutoff-error fallback through the shared helper

If a cutoff lookup or certification fails, this branch makes an otherwise eligible indexed Home request fall back to the legacy scan, but emits only a domain counter and warning. The fallback is therefore absent from the shared resilience telemetry used to observe degraded serving modes. backend/AGENTS.md requires new fallbacks to call utils.observability.fallback.record_fallback; record the indexed-to-legacy degradation at this branch or its routing boundary, retaining the cutoff counter as supplemental diagnostics.

AGENTS.md reference: backend/AGENTS.md:L326-L326

Useful? React with 👍 / 👎.

Comment on lines +2912 to +2914
has_more=bool(tail_report.get('has_more')),
hidden_rows=(recent_report.get('hidden_rows') or 0) + (tail_report.get('hidden_rows') or 0),
next_cursor=tail_report.get('next_cursor'),

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 continuation when the tail exhausts its budget before reading

If the recent branch returns a nonempty short page and the remaining read budget expires before the tail consumes its first row, _PageFill.run returns an empty tail with has_more=False and no cursor. This merge then reports end-of-history and discards the recent branch's usable cursor, even though the historical tail was never read. The Flutter client's ConversationPageHeaders.more honors the explicit false value even on a truncated response, so users cannot load their older conversations until refreshing. When the tail makes no progress because of budget exhaustion, retain the recent continuation and report that more rows may remain rather than treating the unread tail as empty.

Useful? React with 👍 / 👎.

Git-on-my-level and others added 3 commits November 28, 2026 22:59
Callers that write the whole processed conversation back echo the stored
created_at; they keep the plain unfenced write.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Panel review-20261129t035130-7d7e F2: default to get_firestore_client()
imported at module level instead of the legacy db proxy. Pin F1 (an
echoed created_at keeps the unfenced write) with a row that stores
created_at. Drop an unreachable offset guard.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

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

ℹ️ 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 +1439 to +1442
except conversations_db.HomeCursorInvalid:
# Expired, tampered, or issued under another cutoff: restart at page one.
home_cutoff_at = None
page_offset, page_cursor = 0, None

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 Record the rejected Home cursor fallback

When an indexed Home continuation has an expired, tampered, or different-cutoff cursor, this handler silently switches to the legacy reader and restarts pagination. Unlike the existing invalid-cursor path in _collect_visible_conversation_page, it never calls utils.observability.fallback.record_fallback, so these degraded requests disappear from shared fallback telemetry. Instrument this rejection boundary with the indexed-to-legacy transition and degraded outcome; the page counter does not capture why serving changed.

AGENTS.md reference: backend/AGENTS.md:L326-L326

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit d173b71 into main Nov 29, 2026
69 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/sca4102-cutoff-reader branch November 29, 2026 05:20
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