Skip to content

feat(backend): add list metadata projections and conditional version checks - #23394

Merged
Git-on-my-level merged 11 commits into
mainfrom
lane/fs-p1
Oct 23, 2026
Merged

Git-on-my-level merged 11 commits into
mainfrom
lane/fs-p1

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

What changed and why

Repeated conversation/action list polls reread unchanged source pages. Python Firestore atomic commits now maintain content-free metadata rows and per-owner/family versions. Existing If-None-Match requests on /v1/conversations, /v1/action-items and /v1/dev/user/action-items can return 304 after one version lookup without querying the list. Existing clients keep their response shapes and source-query behavior; no client release is required.

Metadata rows are a migration substrate: legacy partial updates never claim full coverage. Source writes/preconditions/transforms, authorization dependencies, privacy/hold/deletion fences, Free behavior, transcript/speaker data and polling limits retain their paths.

Authentication's platform telemetry patches preserve both list versions and add zero projection writes, including when Redis is unavailable and every request writes telemetry. Only exact audited platform fields are exempt; unknown/mixed fields, replacements, creates and root deletion still invalidate both families.

Version reads resolve the Firestore factory and missing-head initializer when called. Importing the action-item router therefore works with the existing isolated task-sharing stubs, without editing those stubs.

Product invariants affected

None by protected path. Task completeness and current access decisions remain on the existing source readers for all 200 responses.

Rollout and rollback

Writer defaults ON; kill switch OMI_LIST_PROJECTION_WRITER_ENABLED=false. Reader activation requires OMI_LIST_VERSION_EPOCH and OMI_BACKEND_RELEASE_SHA. The epoch attests that every writer runtime is covered. Clear it BEFORE disabling or rolling back any writer; re-audit and rotate it before reactivation.

The two-lane lead owns merge/deploy, writer coverage audit (including direct/non-Python/non-atomic BatchWrite paths), synthetic staging parity/update/delete/correction checks, and the reader ramp. Target train: 2026-10-24 08:00Z, cutoff 07:30Z. Reader ramp: 5%, then 100% only after two clean hours of parity, net cost and p95. Lead must publish a revised ramp date or explicit hold by 2026-10-24 08:00Z if this train cannot meet that gate. No production activation was performed by this lane. Contract: list-serving projection runbook.

Attribution and economics

omi_list_version_checks_total{origin,outcome} uses the fixed origins http:/v1/conversations, http:/v1/action-items, http:/v1/dev/user/action-items. Marker SDK reads retain the request origin.

Booked savings: zero. The sprint's 50M/day is an unverified ceiling. Existing explicit validator adoption was not found in shipped client source; automatic HTTP-cache revalidation remains unmeasured. The reads loop owns adoption and net-cost measurement before expansion.

Unchanged eligible 100-row polls become one marker read and zero source queries. Nonconditional requests add zero marker reads. Conversation responses may issue a random initial lp0 validator; the first conditional poll must still query the source before graduating to lp1. Changed conditional conversation requests add two marker reads. Missing heads get one create-only baseline write under the existing transactional deletion fence, including three cold-path reads. Unavailable/malformed heads fall back to source. Partial/locked conversation pages omit validators so locked-content recovery still runs.

Count metadata/version writes, storage and indexes in net economics. Recursive account erasure clears final heads even when the root is absent. No new production configuration or workflow.

Validation

  • Prior published source head 251a7630136b322d82a2197019a10ef8dea7d963: Luna R2 and Sol/P88 SHIP. Four real loopback Firestore emulator cases covered 450/499 source rows, 901/999 expanded writes, source/mirror recursive-delete parity and 179,662-byte maximum Commit. Actual production GET/auth mounted locally over TCP with synthetic authority proved initial source200, later one-marker304, changed-source200 and missing-auth401. Evidence: original handoff.
  • Telemetry correction 35888d9fc0b7a7a24420c1141170c82708e8128a: 56 targeted projection/platform tests passed on m1. Real record_user_platform before conditional GET preserves both heads; repeated auth writes append zero projection writes; warm polls use the existing auth read plus one marker and zero source reads; subscription changes return source200. Masks/transforms, unknown/mixed paths, replacements/creates/deletes covered.
  • Main typecheck blocker was fixed by #23440 and merged into this branch at 416bf600eed714b660225afb1c969252e27f799b. The subsequent task-sharing collection failure is addressed by deferred imports in this follow-up. Fresh focused validation, lead-authorized single Luna delta review, normal push gates and exact-head CI are recorded in the latest handoff comment.
  • Focused import/telemetry regression on m1: 89 passed (33 task-sharing, 50 list-projection/version, 6 platform normalization), through the three-file omi-heavy command below. Existing task-sharing stubs are unchanged. The initial marker lookup bounds timeout/retry and falls back on outage. Total missing-head initialization RPC deadline remains a tracked P2 follow-up (card:fs-p1-head-initialization-deadline), owned by fs-p1 for lead disposition before reader activation, due2026-10-24T07:30Z.
  • Single lead-authorized Luna delta review: no P0/P1 findings for telemetry commit 35888d9f plus import fix fd570d8c. Execution exec-narrow-category-rifle-tunnel-hotel-arctic, collected on m1. Reviewer checked code statically; the lane's locked Python 3.11 environment supplies the dynamic 89-test proof above.

Tests

backend/tests/unit/test_list_projection.py: sync/async SDK batches and transactions, atomic rejection, masks/transforms, owner/family separation, nested corrections, conditional HTTP/auth, counted reads, races, truncation, rollback, release/epoch rotation, marker outage, telemetry and source equivalence. Focused resume list adds test_task_sharing.py and test_platform_normalization.py; executed via omi-heavy run -- nice -n 19 env BACKEND_UNIT_TEST_FILE_LIST=<three-file-list> BACKEND_PYTEST_WORKERS=2 bash backend/test.sh.

UI evidence

UI-Evidence: none -- server-only change.

Failure-Class: none

Line-Count-Exception: backend/routers/conversations.py | 2425 -> 2435 | Wire the shared version helper before list I/O and after lock recovery; all protocol logic stays in utils/list_version_check.py.
Line-Count-Exception: backend/routers/developer.py | 2819 -> 2828 | Wire the shared conditional check after existing auth and before source I/O; no protocol implementation is added to the oversized router.

🤖 Generated with Claude Code

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 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-23T20:07:27.974148Z fd570d8 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: 30a5d85b4b

ℹ️ 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 +104 to +106
row = _row_write(write, parts) if len(parts) == 9 else None
if row is not None:
additions.append(row)

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 Reserve batch capacity for projection writes

When a commit contains 250 or more conversation/action-item mutations, this appends one projected-row write per source write plus a version write, producing 2N+1 writes and exceeding Firestore's 500-write limit. Existing paths intentionally commit up to 499 action-item deletions in delete_action_items_batch and 450 conversation updates in _rehome_folder_conversations, so sufficiently large batch deletions and folder rehomes will now fail atomically with 999 and 901 writes respectively. Reduce those source chunk sizes or otherwise ensure the expanded commit remains within the limit.

Useful? React with 👍 / 👎.

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SHIP — Sol / P88, round 1, exact head 30a5d85b4b89af604bb22f5a2791627cee0943b0.

No P0/P1 findings. Source queries remain authoritative; conditional bypass requires the explicit writer-coverage epoch and release identity. Version writes compose atomically with source writes, and missing-head initialization reuses the existing destructive-operation transaction fence. Validators exclude truncated/racing/locked conversation pages; auth and route dependencies still execute before 304.

Reviewed the SDK sync/async mutation/retry tests, 100→1 counted poll proof, unchanged response/auth tests, locked-allowance recovery and root-missing erasure cleanup tests. These are mechanism/equivalence evidence, not fleet savings. The all-writer audit, synthetic canary and dated ramp in the PR remain required before activating readers. No local test rerun in this review.

The automated comment about a 500-write Commit limit is not a supported blocker: Google removed that limit on 2023-03-29 (request-size and transaction-time limits still apply): https://docs.cloud.google.com/firestore/docs/release-notes#March_29_2023 .

Code-review verdict only; exact-head CI and lead-owned merge/deploy gates remain separate. No merge performed.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

The reported 500-write server Commit limit was removed on March 29, 2023 (Google release notes). The Python server SDK here uses Commit, rather than a client SDK batch-count guard. Current request-size and per-document transform quotas still apply. Source atomicity is preserved rather than splitting source transactions to accommodate the old count limit.

The added loopback emulator integration test uses the real Python SDK RPC and the actual recursive deletion helper for both conversations and action items, with 450 and 499 source rows. All four cases passed at head251a7630136b322d82a2197019a10ef8dea7d963. Expanded requests contained901/999 writes; maximum request size was179,662 bytes. Original caller-visible result lengths, metadata parity and complete source/mirror deletion were preserved. This is localhost emulator evidence, separate from the primary documentation of the server quota; no cloud credentials or production data were used.

The projection writer is unchanged; the delta updates isolated test fixtures, adds that integration proof and documents the server quota contract. A separate reader adjustment gives nonconditional clients zero added marker reads, with an initial tag that must read the source before graduating to a version-backed tag. The independent Sol/P88 review marked the original production-code head SHIP with this same primary-source correction. Required Luna delta review and exact-head CI remain separate gates.

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

ℹ️ 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 +864 to +865
if version_check.not_modified is not None:
return version_check.not_modified

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 usage headers on conditional developer responses

When ladder daily caps are enabled and this endpoint receives a matching lp1 validator, get_api_key_auth has already populated the injected response with X-Omi-Usage-State, X-Omi-Usage-Reset-At, and possibly X-Omi-Storefront-Trigger, but this early return substitutes the separate Response created by ListVersionCheck.start, whose headers contain only the ETag/cache metadata. FastAPI does not merge the injected response headers into an explicitly returned Response, so these conditional polls consume daily capacity while dropping the nudge and reset metadata; merge the existing response headers into the 304 before returning it.

Useful? React with 👍 / 👎.

Comment on lines +81 to +84
if not request.headers.get('if-none-match'):
if family == 'conversations':
check.etag = f'W/"lp0-{uuid4().hex}"'
check.initial_validator = True

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 Bootstrap validators for developer action-item lists

When /v1/dev/user/action-items is called normally without If-None-Match, this branch emits an initial validator only for conversations. Unlike the first-party action-item route, the developer route had no body ETag before this change, and its external-list cache does not add one, so ordinary clients and HTTP caches never receive any validator to return; consequently this route never reaches the version-backed 304 path unless a client invents an initial header. Emit an initial validator for this developer action-item route as well while retaining the existing first-party action-item cache path.

Useful? React with 👍 / 👎.

Comment thread backend/database/list_projection.py Outdated
Comment on lines +107 to +109
# Account/entitlement/privacy changes and deletion intent invalidate
# both lists. No authorization fence is replaced by these versions.
elif len(parts) == 7 or (

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 Exclude telemetry-only root writes from list invalidation

For first-party requests carrying X-App-Platform, authentication calls record_user_platform before this version check; that helper updates users/{uid} once per platform every ten minutes, and on every request while Redis is unavailable. Treating every root-user write as affecting both families therefore appends two head writes for unrelated last-active telemetry and invalidates both list ETags, forcing the next otherwise-unchanged conversation/action poll back through its full source query. At fleet scale this can add two Firestore writes per active user per throttle window and materially undermine the read-cost experiment; restrict root invalidation to fields that actually affect list authorization or representation.

Useful? React with 👍 / 👎.

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SHIP — Sol / P88, round 2, DELTA ONLY: 30a5d85b4b89af604bb22f5a2791627cee0943b0..251a7630136b322d82a2197019a10ef8dea7d963.

No P0/P1 findings in the delta. Unconditional conversation polls now add zero marker reads and receive a random lp0 invitation tag only on full unlocked pages. That tag cannot match lp1: the first conditional response still reads the authoritative source, and only a stable version interval receives a reusable lp1 validator. Locked/truncated pages retain their exclusion and auth/epoch/writer fences are unchanged.

Reviewed initial-tag/racing-response graduation, 100→1 warm conditional read accounting, lock-recovery regression updates, bounded SDK-fixture repairs and the added loopback 901/999-write commit/delete proof. Writer source semantics remain unchanged. Docs now explicitly separate absent explicit client validators, possible HTTP-cache adoption and unmeasured fleet savings. No local test rerun in this review.

Exact-head CI and lead-owned merge/deploy/reader-activation gates remain separate. No merge performed.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Luna delta review: SHIP on 251a7630136b322d82a2197019a10ef8dea7d963, no P0/P1 findings. The reviewer explicitly withdrew the round1 P1: the old500-write server Commit count limit was removed in2023. The four passing emulator cases prove the actual901/999-write commit and recursive-delete paths; maximum request size179,662 bytes. Primary sources: server release notes, current quotas.

Local validation on that source head:88 targeted unit tests,4 real emulator cases, actual local TCP route/auth smoke,38 selected preflight checks, and full backend typecheck with zero errors. Nonconditional conversation polls add zero marker reads; an initial tag must read source before a stable version tag can produce a one-read304.

CI remains blocked, separately from code review. Run39979646496 checks the PR merge into mainc475 and reports7 type errors in main's newly changed edit_tools.py / turn_refs.py from #23408, before tests execute. Those files are outside this PR's diff. The lead has the known-red report and a recommendation that preserves runtime guards and RunnableConfig injection annotations. No checks skipped; no merge/deploy performed. Fleet savings remain unbooked pending coverage audit and measurement.

Git-on-my-level and others added 3 commits October 23, 2026 13:54
Exclude only audited platform telemetry masks and transforms from owner-list
invalidation. Unknown fields, mixed writes, root replacements and deletion
keep conservative invalidation of both families.

Exercise the real platform recorder before counted conditional HTTP polls,
including repeated writes when Redis is unavailable.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the Firestore factory only when reading a version and the initializer
only when a head is missing. This lets the action-items router load under the
existing isolated task-sharing database stubs without extending those stubs.

Patch the factory on its owning module in the version I/O regression.
Focused task-sharing, list-projection and platform tests: 89 passed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Published fd570d8c5616c6638360c32e242407da4d8da48e after fetching the lead's main merge.

The task-sharing collection error is fixed by deferring the optional Firestore factory and missing-head initializer imports until version I/O. The existing task-sharing stubs are unchanged. The second deferred import also avoids its indirect legal-hold/account-deletion-marker factory import.

Validation on m1:

  • 89 passed through an explicit three-file omi-heavy list: task sharing33, list projection/version50, platform normalization6. Real platform recording preserves both heads, adds zero projection writes, and keeps the one-marker/zero-source warm-poll proof. Subscription changes still produce source200.
  • Normal push gates passed:38 selected preflights, full backend typecheck0 errors,101 selected units,19-image source closure, pinned formatting and released-client OpenAPI/generated-schema compatibility.
  • The single lead-authorized Luna delta review reported no P0/P1 findings on telemetry commit 35888d9f and this import fix. Collected execution: exec-narrow-category-rifle-tunnel-hotel-arctic. The telemetry P1 is resolved. Prior P2 dispositions remain deferred under the P0/P1-only instruction.

Exact-head Backend Unit Tests run40016070975 is pending; the lane's fail-fast CI waiter is armed. CI green remains required. Lead owns merge/deploy, targeting2026-10-24T08:00Z (cutoff07:30Z). Reader coverage/adoption/net-cost gates remain explicit; booked savings are zero.

🤖 Generated with Claude Code

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

ℹ️ 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 +33 to +34
# Keep optional version I/O out of router import-time dependencies.
from database._client import get_firestore_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 Keep the new version-check imports at module scope

The new _version helper imports get_firestore_client and initialize_head inside the function, contrary to the explicit requirement in backend/AGENTS.md: “All imports at module top level — never inside functions.” Move these imports to module scope while preserving lazy client construction; if isolated tests require deferred attribute resolution, import the modules rather than resolving their exported functions during import.

AGENTS.md reference: backend/AGENTS.md:L161-L169

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Disposition: no code change. The lead's explicit 2026-10-23 follow-up authorizes this repair with e.g. import lazily inside the function / use the module attribute at call time, overriding the general backend/AGENTS.md import convention for this specific stub-isolation fix. Deferring only the client factory is insufficient: eagerly importing list_projection_head also loads legal_holds/account_deletion_marker and another missing factory under the same stub. Both imports are now inside the optional I/O exception boundary, preserving source fallback. Existing task-sharing stubs are unchanged; the required three-file omi-heavy run passed 89 tests (33 sharing, 50 projection/version, 6 platform), normal push gates passed including full typecheck0 errors/import purity, and the single lead-authorized Luna delta review found no P0/P1. This comment identifies the general convention, not a remaining runtime correctness defect. Evidence: #23394 (comment). Lead owns merge and exact-head CI is still being collected.

Comment on lines +19 to +20
with external_write_fence(uid, firestore_client=firestore_client, transaction=transaction):
snapshot = reference.get(transaction=transaction)

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 Bound the missing-head initialization RPCs

When a conditional request encounters a missing head, initialization performs two authority reads, another head read, and a transaction commit without explicit RPC deadlines or retry bounds. The preceding reference.get(timeout=1.0, retry=None) does not bound these subsequent calls, and max_attempts=1 only limits transaction attempts. If Firestore stalls during this cold path, the optional optimization can exhaust the HTTP timeout before the source reader or its list budget is reached, producing a 504 instead of falling back. Apply a bounded deadline to the entire initialization path, including its authority reads and commit.

Useful? React with 👍 / 👎.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Exact-head CI is green for fd570d8c5616c6638360c32e242407da4d8da48e:31 checks SUCCESS,26 expected path-selection SKIPPED, zero failures or pending checks. PR head and terminal check states were asserted after the fail-fast watcher exited0.

The backend unit suite, all six shards and guardrails passed, including formerly failing shard2. Local focused89 tests, normal push gates and clean Luna delta evidence are in the fix handoff.

The automated import-convention P1 is rebutted under the explicit lead instruction permitting local lazy imports. New P2 missing-head total RPC deadline is tracked on card:fs-p1-head-initialization-deadline, ownerfs-p1, next2026-10-24T07:30Z for lead assignment/disposition before reader activation. Existing P2 developer-header/bootstrap dispositions remain deferred under the P0/P1-only scope.

Lead owns merge/deploy for2026-10-24T08:00Z T2 (cutoff07:30Z), writer coverage audit, staged parity and reader adoption/net-cost gates. Booked savings remain zero. No production changes by this lane; no local work remains running.

🤖 Generated with Claude Code

@Git-on-my-level
Git-on-my-level merged commit e5b3a24 into main Oct 23, 2026
61 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/fs-p1 branch October 23, 2026 20:24
Git-on-my-level added a commit that referenced this pull request Oct 23, 2026
## What changed and why

Redirected sync owner reads loaded the final survivor twice. Reuse the
operation's detached raw snapshot and Firestore revision for ordinary
photo/transcript hydration. A metadata-only bridge with no donor lineage
or effect attempts reuses its initial metadata. Donor traversal and
every attempted effect retain the final refresh. Transaction reads, CAS,
deletion markers, owner/path checks and outbox custody remain
authoritative.

Redirect helpers accept a keyword-only `firestore_client`. One lazily
selected client serves redirect resolution, either hydration mode and
photo reads. This addresses the P1 injection finding at
discussion_r4360643026; scoped-client tests reject fallback to legacy
globals. Invalid paths reject before client initialization.

Default ON. Kill switch: `SYNC_OPERATION_SNAPSHOT_ENABLED=false`. Both
modes use `origin=job:sync_operation_snapshot`;
`omi_sync_operation_snapshot_reads_avoided_total{origin,operation}`
counts avoided redirect-hydration and no-effect bridge lookups. No
reads-loop configuration changes. Keep renamed caller
`sync_conversation_snapshot:resolve_snapshot` in the measurement
baseline; label movement is not savings.

Both the snapshot counter and shared origin-overflow counter reuse
existing Prometheus collectors across fresh imports. The origin helper
is copied unchanged from fs-p2's reviewed commit
`77a033e14a0a53d7eaffb04b7da3fbde2875019c`; the archive contract test is
unchanged.

This is the bounded P5 snapshot slice.
`backend/docs/sync-operation-snapshots.md` records the remaining index
contract and P4 design only. The content-free <=4KiB enrichment outbox
cannot carry structured user content. An id+writer-generation index
obligation needs all-writer coverage, live eligibility, replay/CAS and
migration proof; lead owns the scope ruling. P4 excludes every privacy
caller and requires residual phase measurement after WQ12. The 22M/day
and 25M/day figures are unverified planning ceilings; daily savings are
unknown and none are booked.

## Product invariants affected

none

No transcript, speaker, Free-plan, entitlement, polling, hold, deletion
or privacy authority changes.

## How it was verified

- Counted fake document gets: redirect hydration 5 -> 4 with identical
decoded content and unchanged compressed stored bytes; eligible bridge 2
-> 1. Scoped/default-client cases preserve photo hydration. Fresh
deletions, owner/path mismatches, revision contracts, donor lifecycle,
post-effect races, paid unlock recovery and callback parity are covered.
- Real detail handler through FastAPI TestClient: equivalent JSON across
modes, then 404 after a fresh deletion marker. This is an in-process
endpoint check.
- Snapshot metric regression proves collector identity and exported
increments survive fresh config imports. The unchanged archive-contract
tests exercise repeated database imports with both counter repairs
present.
- Follow-up integration: merged main `532990aee3` as merge commit
`252b517e11`. Conflicts were additive documentation and flag entries
only; preserved both fs-p1 #23394 entries and P5 entries. No Python
conflict resolution. Head `8de371d00851ed4b0e9bd1180633b65faa156944`
also carries the exact fs-p2 shared-origin helper (blob
`d3b25323f440457705bfd6eab3ce83a55217a176`).
- Current published head: 16 focused files PASS, 373 tests, including
all four archive-contract cases, the snapshot metric regression, list
projections and repaired merge fixtures. From `backend/`:
`/Users/david/workspace/omi-workspace/bin/omi-heavy run -- env
BACKEND_PYTEST_WORKERS=4
BACKEND_UNIT_TEST_FILE_LIST=/Volumes/scratch/m1-lanes/fs-p5/merge-focused-files.txt
nice -n 19 bash test.sh`. Log:
`/Volumes/scratch/m1-lanes/fs-p5/merge-focused.log`.
- Current head: `make preflight` PASS37/37 (169.88s) and full mandatory
pre-push PASS, including full-backend typecheck (zero errors), runtime
source closure, bounded selected tests, schema checks and formatting.
Ran through `omi-heavy`, nice19; log
`/Volumes/scratch/m1-lanes/fs-p5/merge-publish.log`. Normal push
succeeded after re-fetching main and the shared lane branch; no
force-push. Exact-head
[CI40024971016](https://github.com/BasedHardware/omi/actions/runs/40024971016)
PASS: all six unit shards, guardrails and suite gate. All PR checks
terminal at collection, 37SUCCESS and zero failures; GitHub merge state
CLEAN. No rerun needed. Lead delta review remains required before merge.
- Earlier m1 metric head `61d363f23a`: eight focused files PASS (134
tests); published CI exposed the separate fs-p2 origin-counter
dependency and main #23445 fixture mismatches. This integration contains
the origin repair and main #23447 fixture repair. Earlier full mandatory
pre-push and full-backend typecheck passed. No checks bypassed.
- Prior Luna R1/R2: SHIP on production head
`f4e376f649fac50a232ea03a929b8b395f9d92a3`. Lead must inspect the
seven-line fixture delta at `7186a6bf67d`, client-injection delta
`7186..526e` and metric delta `06d8..61d3`. No third round: two-round
cap exhausted, and current conflict resolution changes no runtime
behavior. The shared origin fix was reviewed by fs-p2's read-only Luna
delta review.

Line-Count-Exception: backend/database/conversations.py | 4431 -> 4449 |
Add scoped-client parameters and forwarding at existing
redirect/hydration boundaries for P1 correctness; operation
orchestration remains extracted in sync_conversation_snapshot.py.

## UI evidence

UI-Evidence: none -- backend read optimization with unchanged response
contract.

## Failure class (fixes)

Failure-Class: none

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Git-on-my-level added a commit that referenced this pull request Oct 23, 2026
…23402)

## Summary

Repeated released-memory reads reload identical canonical, historical
and metadata windows. This change atomically maintains a content-free
owner change head with source commits, including deletes, and reuses
exact raw-query projections at internal canonical, historical,
list-window, status-pair and MCP-card callers. Existing authorization,
policy, lineage, privacy, decryption and lever paths remain
authoritative.

Warm 100-document pages use two head reads instead of 100
source-document reads. Cold pages add head checks; queries smaller than
three rows bypass reuse. The sprint's **50M/day target is conditional
and unmeasured**. Grade avoided source reads minus marker reads and
added writes before booking savings.

This branch merges main through
`251892e223fca3bf5c90f060d3b9673683e258fa`, including P1 list
projections (#23394), fs-p5 operation snapshots (#23393), the typecheck
repair (#23440), merge-copy fixture repairs (#23447), and apt CI repair
(#23446). Conflict resolution retains BOTH writer installers, BOTH
account-erasure cleanup families, and all flag contracts. New real-SDK
sync/async mixed-batch checks verify one atomic commit, both projection
families, and unchanged source result counts. Erasure checks cover late
head recreation with both present and missing user roots. The final
fs-p5 refresh resolved only an adjacent flag insertion; its
origin-counter repair is byte-identical to P2's.

The archive-filter CI regression is fixed in production registration:
`firestore_read_origin` and `released_memory_projection` recover their
existing process-wide Prometheus counters after import-isolation
teardown evicts modules. Two re-import cycles prove collector identity
and counts survive. No test catches the error or weakens archive
behavior. The earlier shard-5 rerun passed all four archive cases in
514s against its unchanged 720s budget.

## Lane / contract

fs-p2 owns `released_memory_changes_v1`, `MEMORY_RELEASED_PROJECTION`,
`MEMORY_RELEASED_WRITERS_COVERED`, and
`omi_memory_released_projection_total`; original design bus 9012d9. MCP
consumes P1's `list_serving_versions/conversations.version`, writer kill
switch and coverage epoch (original bus dd3ecb). Missing P1 metadata
retains source reads. No additional conversation writer is introduced.

## Product invariants affected

- INV-MEM-1: existing three-tier policy, pending/expiry and
archive/device visibility checks rerun on raw candidates. No transcript,
speaker or Free-plan changes.
- INV-MEM-3: source errors and canonical/suppression/lineage checks
still fail closed. Projection faults fall back to the same authoritative
query.
- INV-MEM-4: projections grant no promotion authority. Canonical
receipts, graph transitions and lineage collapsing retain their existing
owners; source/head writes remain atomic, including deletes.

## Verification

Final focused conflict-resolution run on m1: **433 tests across 21 files
passed** through `/Users/david/workspace/omi-workspace/bin/omi-heavy run
-- nice -n 19 env
BACKEND_UNIT_TEST_FILE_LIST=/Volumes/scratch/m1-lanes/fs-p2/fs5-merge-files.txt
BACKEND_PYTEST_WORKERS=4 bash backend/test.sh`. Covers P1/P2
projections, mixed sync/async writes, erasure/privacy, archive
filtering, origin attribution/wiring, MCP consumers, memory policy, all
three shared-main merge-copy stub files, and fs-p5
snapshot/metric/tombstone/unlock contracts. Log:
`/Volumes/scratch/m1-lanes/fs-p2/fs5-merge-focused.log`. The prior P1/P2
refresh passed 353 tests across 17 files.

Full backend typecheck passed with **zero errors** (existing warnings
remain), via `omi-heavy run --cache-default backend-typecheck -- nice -n
19 bash backend/scripts/typecheck.sh`; log
`/Volumes/scratch/m1-lanes/fs-p2/merge-typecheck.log`. One read-only
Luna conflict delta review completed with **no P0/P1 findings**:
`exec-curve-yellow-plunge-fancy-pill-obtain`, result
`/Volumes/scratch/m1-lanes/fs-p2/luna-merge-result.txt`. Historical
metric delta review: `exec-rhythm-sort-chapter-traffic-comic-vendor`;
its P1 typing finding was corrected and verified.

Published final merge head: `6ac131f9f566b0eb2d35447329c685d76c951ed1`.
**Exact-head CI is green**: [Backend Unit Tests, attempt
2](https://github.com/BasedHardware/omi/actions/runs/40028276311),
[Firestore emulator
proofs](https://github.com/BasedHardware/omi/actions/runs/40028276314),
and [hermetic backend
gates](https://github.com/BasedHardware/omi/actions/runs/40028276356)
pass. All visible checks are terminal: 37 successful, 30 intentionally
skipped, no failures. Final-head shard 5 passes all four archive cases
with wall **673s/720s**. The single permitted failed-job rerun passed
shard 4 (all 66 runtime-contract assertions, GPU closure CPU
**0.88s/1.00s**, shard wall **615s/720s**). No threshold, allowlist or
source changes and no further reruns.

Attempt 1's sole failure was the unchanged GPU closure CPU guard at
1.01s against 1.00s, with all 66 assertions passing. **Exact main also
fails the same guard at 1.16s** in [run
40026957577](https://github.com/BasedHardware/omi/actions/runs/40026957577/job/120665436845);
test and closure tool blobs match. ANX `card:fs-p2-runtime-duration`
retains the shared-main timing follow-up for the lead.

**Normal pre-push exited 0**: all 37 manifest checks, full backend
typecheck with zero errors, runtime source closure and bounded selected
unit checks passed; log
`/Volumes/scratch/m1-lanes/fs-p2/fs5-merge-push.log`. The prior main
refresh also passed all normal pre-push gates; log
`/Volumes/scratch/m1-lanes/fs-p2/merge-push.log`.

Prior-head CI passed five unit shards, guardrails, Firestore emulator
proofs and hermetic gates. Shard 5 passed all four archive cases in
**635s against its unchanged 720s wall budget**. Shard 4 passed all 66
assertions in unchanged `test_runtime_image_contracts.py` but failed its
CPU guard on the GPU import-closure test at 1.05s versus 1.00s. A
focused same-runner local reproduction passed all 66 tests, that case at
0.31s; log `/Volumes/scratch/m1-lanes/fs-p2/runtime-focused.log`. No
threshold/allowlist changes and no CI rerun used. Tracking: ANX
`card:fs-p2-runtime-duration`. Main advanced with fs-p5 during this CI
run, so the final merge gets fresh CI rather than rerunning the
superseded head.

Earlier synthetic P2 Firestore emulator proof passed failed-batch
atomicity, SDK transaction retry, result cardinality, sync/async
deletes, bulk exclusion and raw-read parity at recovered head bf6f72c.
Emulator project `demo-fs-p2`, local `127.0.0.1:18585`; log
`/Volumes/scratch/m1-lanes/fs-p2/emulator.log`. This historical emulator
run is not claimed as fresh conflict-resolution evidence. New-head
registered CI emulator proofs must pass before merge.

## Rollout / rollback

Writer maintenance is on. Reader preference defaults on with
`MEMORY_RELEASED_PROJECTION=off` as kill switch. **Reuse requires
`MEMORY_RELEASED_WRITERS_COVERED=v1:<unique-epoch>`**, initially absent
until complete writer-fleet attestation. MCP additionally requires P1
writer coverage and its fresh epoch. Bulk-blocked or missing-head owners
retain source reads; no user-data backfill.

Owner: rollout lead. Target T2 **2026-10-24 08:00Z**, cutoff **07:30Z**,
only after exact-head CI is green. By cutoff, verify every
backend/sync/backfill/integration/listen/pusher/desktop/job writer
release and synthetic create/update/delete parity, including
standalone/non-Python/raw-RPC writers. If proof is missing, record the
blocker and keep reuse disabled. Once proved, enable all eligible owners
with a fresh epoch.

Metrics: bounded `surface/outcome/origin` on
`omi_memory_released_projection_total`; marker reads use
`origin=job:released_memory_projection`, and source reads retain their
existing caller/origin. Compare output/order/access parity and p95. Any
mismatch or regression disables readers. Grade net reads in equal
full-day windows and mature billing before recording savings.

Clear coverage before ANY writer rollback or gap; rotate the epoch after
restoration. Reader-only rollback keeps head writers installed. Details:
`backend/docs/released-memory-change-projection.md`.

Failure-Class: none
Line-Count-Exception: backend/database/memories.py | 1968 -> 1971 |
three raw query calls adopt the shared projection transport; query and
policy ownership remain in place

Tracking: ANX `card:fs-p2-released-memory-projection`, owner fs-p2; lead
owns merge/deploy and full writer-fleet audit/activation by 2026-10-24
07:30Z. Handoff: `/Volumes/scratch/m1-lanes/fs-p2/HANDOFF.md`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Git-on-my-level added a commit that referenced this pull request Nov 1, 2026
## Summary

**Decision PR for the rollout lead** (bus 65693f / 941502). It turns the
list-projection writer (#23394) off by default until its reader ramps.

Measured by the write probe (#24218) on 2026-11-01 (Sunday, 15-minute
window scaled per day), the list-projection version and row writes are:
- Cloud Run: **1.87M/day**, 13.6% of all Cloud Run writes.
- Listen: **2.11M/day**, 45.7% of listen's writes.
- Pusher: not on the probe yet.

So that is **≈4.0M writes/day, about $5.5/day on a Sunday and likely
$8-10 on weekdays** (weekday volume ran about 1.9x). Every conversation
update carries one version write and one row write. On listen, for
example:
- `update_conversation_segments`: 0.38M source / 0.38M version / 0.33M
row per day.
- `update_conversation_finished_at`: 0.33M / 0.33M / 0.33M per day.

Nothing reads them:
- `OMI_LIST_VERSION_EPOCH` is empty everywhere. Its ramp (owner:
two-lane lead, due 2026-10-24) never started.
- `utils/list_version_check.py` and the MCP card reader in
`database/released_memory_projection.py` both require the epoch.
- No code reads the `*_list_rows` collections.

Change:
- `config/list_projection.writer_enabled()` and the matching read in
`released_memory_projection.py` now default to `false`. Explicit `true`
still turns the writer on.
- A code default reaches every writer process (Cloud Run, listen,
pusher, workers, jobs) in one place. A per-service env would need a
dozen declarations to stay consistent.
- Registry entry: `rollout`, default off, owner two-lane lead,
`review_by` 2026-11-15.
- Ramp plan in the registry:
  1. Set `true` on every writer service and revision.
  2. Wait until no revision without it serves.
  3. Run the existing epoch ramp (5% → 100%).
  4. If the reader ramp is dropped, remove the writer.

## Catch-up on re-enable (lead d8fd89 / 12:48Z conditions)

Stale rows and versions never serve:

- **Versions.** A version is a random token in the list ETag scope,
which also includes the epoch. While the writer is off,
`ListVersionCheck.start` returns before reading any version, whatever
the epoch. The new test covers this for both families, with and without
an epoch.
- **Re-enable order:**
  1. Set the writer `true` on every writer service.
  2. Wait until no revision without it serves.
  3. Set a **fresh** `OMI_LIST_VERSION_EPOCH`.

A fresh epoch changes every ETag, so a validator issued before or during
the gap can never match. The first conditional request after the new
epoch reads the source and issues a new tag. Existing coverage:
`test_list_projection.py` "new-rollout-after-writer-gap" asserts 200
after a gap.
- **Rows.** `*_list_rows` are a migration substrate that no code reads,
and a partial legacy update can never mark a row ready. Any future row
reader must backfill or prove coverage after a writer gap. Re-enabling
alone does not make them complete.

## Would the epoch reader save more reads than these writes cost?

Not shown, and not measurable today:

- Read-probe origins in a Sunday hour: `/v1/conversations` 758k,
`/v1/dev/user/action-items` 602k, `/v1/action-items` 236k. That is about
38M reads/day, about $17/day at $0.461/M.
- That is the ceiling, reached only if every list GET were conditional
and unchanged. Each conditional request also adds one version read.
- No Dart client sends `If-None-Match`. With the epoch empty,
`/v1/conversations` emits no `lp0` tag for HTTP caches to revalidate.
- The writes cost about $5.5 on a Sunday and $8-10 on a weekday whether
or not any of that saving appears.
- To measure it before any ramp, this PR adds
`omi_list_conditional_requests_total{origin, validator}` (3 origins ×
present/absent). If the present share on these routes is high, the ramp
case can be made with numbers.

## Product invariants affected

- INV-DATA-1: no source data changes. The rows and versions are a
derived substrate. With the writer off they stop being maintained, and
the epoch ramp already requires full writer convergence and a fresh
epoch after any writer gap (registry note on #23394). No serving path
reads them while the epoch is empty.

## Verification

All runs used `backend/test.sh` under `bin/omi-heavy` + `nice -n 19`, at
the unit layer:
- `test_list_projection` (20), `test_memory_change_head` (50),
`test_released_memory_projection` (27),
`test_conversation_smart_merge_audit_sdk` (26), and the other files that
reference the projection collections or installer: all pass.
- Tests that assert projection writes now set
`OMI_LIST_PROJECTION_WRITER_ENABLED=true` explicitly.
- `scripts/check_feature_flag_registry.py`: OK.

Live check after deploy:
`omi_firestore_billed_writes_total{collection=~"users/(list_serving_versions|conversation_list_rows)"}`
goes to ~0, and fleet `write_count` drops by about the same amount.

## Rollback

Set `OMI_LIST_PROJECTION_WRITER_ENABLED=true` fleet-wide, or revert.

Failure-Class: none

🤖 Generated with [Claude Code](https://claude.com/claude-code)
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