Skip to content

fix(record): producer custody token lease and heartbeat (option A), default off - #25018

Merged
Git-on-my-level merged 93 commits into
mainfrom
lane/tokenlease
Nov 11, 2026
Merged

Git-on-my-level merged 93 commits into
mainfrom
lane/tokenlease

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Merge-main push 5

Head: 1ec50a75e6e8c34eca7601e768148be7ac2c9830.

Merge-main resolution under lead2 1c606e; reviewed patch behavior unchanged.

Merged main: 28b447f847fccfa960fecf17312561ab390e82a6. A final refetch added only main's v0.12.574 desktop changelog (two files, +14 lines) in a second normal merge. The sole textual conflict in the initial main merge sets flag_budget.count to the merged registry's actual 269 names. Both sides are preserved. The token-lease metrics and quiet-check, erasure guard, receipt replay, renewal retention and deterministic messaging test remain unchanged. Incoming main changes are preserved; no new workflow or UI change was authored.

Fresh qualification on this exact head: 44 seal/custody/privacy/lifecycle, pusher and messaging unit files yielded 1,517 passed and 86 existing xfails, zero failures/skips (includes all 24 flag-budget tests). Loopback emulator/lifecycle suites yielded 30 + 4 + 34 + 75 + 39 passed, with 3 existing lifecycle xfails; all emulators shut down normally. Expanded preflight passed all 75 checks. Normal full pre-push passed: 3 metadata checks, 75 shared checks, zero backend typecheck errors, 851 index-guard passes in 7 files, and 34 selected backend files yielding 2,141 passed / 86 existing xfails / 4 emulator skips / 144 integration deselections. The skipped/deselected emulator coverage passed independently above. Merge delta from the reviewed head, including incoming main: 347 files, +15,679/-952. Full PR diff against merged main: 124 files, +9,626/-159. Commands use omi-heavy run -- with inherited GCP credentials and CLOUDSDK variables removed. Local static/synthetic and loopback emulator evidence only.

Exactly one normal fast-forward push completed from 9a48272644889eae505df59221bf8ccf5da78281 to this head. Its mandatory full hook also passed with the same 75 shared checks, zero typecheck errors, 851 index-guard passes, and 2,141 passed / 86 existing xfails / 4 emulator skips / 144 integration deselections across 34 selected backend files. No rebase, force push or hook bypass.

STOP for delta-only Luna. No deploy or merge.

Historical qualifications below remain attributed to their recorded heads.

Flag count and backfill CI diagnosis

Earlier head: 9a48272644889eae505df59221bf8ccf5da78281 (parent 7d9126fd6738173a6324dadedd7b6973267fe793). The only incremental source change corrects flag_budget.count from 267 to 268, equal to the merged names count; no flag or behavior is added. Incremental diff: one file, +1/-1 (two changed non-test lines).

Shard 8's backfill assertions all passed; its failure was the unchanged 1.00s CPU guard at 1.14s for test_backfill_cleared_discard_restore_recovers_only_owed_unarmed_debt[None-still_refused0]. Current main is 4e9c70405c53f8efcaced2fea369910ade355058. Local exact-node runs pass on both main and L1; the full backfill file passes on both (101 passed, one existing emulator skip each). The flag budget file passes all 24 tests. No backfill code, test, skip, xfail or timing limit changed. Current main CI also passed this case at 0.89s (Backend Unit Tests run 42946411215, shard 7). Local CPU measurements were 0.80s main / 0.52s L1 for the isolated node and 0.41s on both full-file runs. The exercised backfill, conversation restore, summary-delivery and strict transaction fake match main. Classification: the backfill failure is not reproduced on current main or locally on L1; evidence supports a CI timing flake, with no established L1 functional regression. A main-wide failure is NOT confirmed. Backfill is left unchanged; no timing limit or marker is relaxed. Normal full pre-push passed on this head: 75 shared checks, supplied-body metadata validation, zero backend typecheck errors; seven embedded index-guard files yielded 848 passes, and 34 selected backend files yielded 2,140 passed, 86 existing xfails, four emulator skips and 144 integration-marker deselections. Both exact failing nodes passed independently (one test each); full focused L1 files yielded 125 passed and one existing emulator skip. All gates ran through omi-heavy run -- with inherited GCP credentials and CLOUDSDK variables removed, private HOME/config and disabled metadata discovery. These are local static/synthetic results, separate from remote CI. Exactly one normal fast-forward push completed from the parent to this head. Its mandatory hook also passed with the same 75 shared checks, zero typecheck errors, 848 index-guard passes and 2,140 passed / 86 existing xfails / four emulator skips / 144 integration deselections across 34 selected files. No hook bypass or timing relaxation was used.

STOP after one green push for delta-only Luna. No deploy or merge.

Previous qualification remains attributed to its recorded head.

Merge-main push 3

Earlier head: 7d9126fd6738173a6324dadedd7b6973267fe793. Merge-main resolution under lead2 1c606e; reviewed patch behavior unchanged.

Merged main: 4e9c70405c53f8efcaced2fea369910ade355058. The two textual conflicts are mechanical unions of worker labels/lease defaults and the monitoring keep-regex. Erasure, receipt replay, renewal retention, repair coordinator and messaging-test fix remain byte-identical to the reviewed parent. No workflow file changed.

Fresh credential-free local qualification through omi-heavy: 43 focused unit files, 1,493 passed and 86 existing xfails; loopback emulator suites 30 + 4 + 34 + 75 + 39 passed with 3 existing lifecycle xfails; expanded preflight 75 checks passed; normal full pre-push passed with 3 metadata checks, 75 shared checks, 848 index-guard tests, zero backend typecheck errors and 34 selected files yielding 2,140 passed / 86 existing xfails / 4 emulator skips / 144 integration deselections. Emulator coverage passed separately above. Local static/synthetic and loopback-emulator evidence only.

Merge delta: 52 files, +1,670/-49 (incoming main included). Full PR diff: 124 files, +9,626/-159. Stop after this one push for delta-only Luna and refactor-lead's custody delta. No deploy, ramp or production access.

Exactly one normal fast-forward push completed from 5bbf8212c634a5c38f151fbdf310cbb839f64e12 to this head. The mandatory push hook also passed with the same shared, typecheck, index-guard and selected-backend results.

Merge-main push 2 qualification

Earlier head: 5bbf8212c634a5c38f151fbdf310cbb839f64e12. Merged current main: aa3df45721c8714c58c66f69f81ebbc507c2f526.

Mechanical merge-main resolution under lead2 1c606e; reviewed L1 runtime behavior preserved.

The resolution keeps L1 token-lease metrics, custody maintenance, erasure admission, receipt replay and renewal retention alongside main's urgent/recent repair scheduling and quiet-check behavior. The equivalent deterministic messaging test stub is retained from main. Test-only composition reconciliations isolate priority fixtures from custody maintenance/metrics-server IO and align the emulator expectation with main's newest-first order; no runtime policy change.

Fresh local qualification on this exact head ran through omi-heavy run -- with inherited GCP credentials and CLOUDSDK variables removed, private test HOME/config, metadata discovery disabled and synthetic fixtures:

  • Seal/custody/privacy/lifecycle and pusher retention/barrier units: 43 files, 1,493 passed, 86 existing xfails, zero failures/skips; includes 11 messaging cases and 39 priority cases.
  • Loopback emulator/lifecycle: custody append 30 passed; no-job seal 4 passed; lifecycle/properties 34 passed and 3 existing xfails; held custody 75 passed; recovery custody 39 passed. Emulator shut down normally.
  • Expanded preflight: 75 checks passed, zero failures.
  • Normal full pre-push: 75 shared checks, 3 metadata prechecks, zero backend typecheck errors; 34 selected backend files, 2,108 passed, 86 existing xfails, 4 existing emulator skips, 144 integration deselections. The skipped/deselected emulator cases passed separately above.

Merge delta from reviewed head: 63 files, +2,876/-138, including imported main. Full PR diff against merged main: 124 files, +9,626/-159. The incoming workflow change is exactly main's blob; no workflow change was authored in this resolution.

Local static/synthetic and loopback-emulator evidence does not establish remote CI or deployed behavior. Stop after the single push for delta-only Luna and refactor-lead's custody delta. No deploy, ramp or production access.

Test-only messaging determinism fix

Earlier head: 4328ac0ff96324d99e35ce5ab57c7f69885085d1 (parent cd63b355ba4fefaff836908b9767c681cd353f8e). Test-only determinism fix for a main-wide messaging flake: the optional continuity-load failure regression now executes its in-memory reads directly so the mocked digest succeeds without executor startup/deadline races; product code is unchanged.

Incremental diff: one test file, +6/-1 (under 20 changed lines). Exact test_optional_load_failure_returns_plain_window[failure2]: 1 passed; full test_messaging_review_fixes.py: 11 passed, including all three continuity-failure parametrizations. Checks run via /Users/david/workspace/omi-workspace/bin/omi-heavy run -- with inherited GCP credentials and CLOUDSDK variables removed, private HOME/config, and disabled metadata discovery. Normal full pre-push passed on this head: 75 shared checks, 3 supplied-body metadata checks, zero backend typecheck errors; 34 backend files yielded 2,080 passed, 86 existing xfails, 4 emulator skips and 144 integration deselections. This is local static/synthetic evidence; no remote CI or deployed behavior is claimed. Exactly one fast-forward push completed; its mandatory hook also passed with the same shared/typecheck/backend counts. Stopped for delta-only Luna; no deploy or merge.

Historical qualifications below remain attributed to their original commits.

Refused-receipt retry fix

Earlier head: cd63b355ba4fefaff836908b9767c681cd353f8e (parent b0cee99fdeb521e32b1e7c71fc8e52ac5ab27b62). Addresses the single FIX-FIRST: finish() replays only accepted receipts, so a same-job retry after a refused 202/failed clears its newly acquired token and records the accepted revision and recovery obligation. Accepted receipt replay remains idempotent.

Incremental scope: 2 files, +45/-3; 5 changed non-test lines, under the 40-line cap. The new request-level regression first failed on the parent with the retry token still active; it verifies refusal has no revision/recovery effect, then successful retry records revision 8, schedules recovery, clears custody and replays without another write or late count.

Focused custody/token-lease/erasure/privacy qualification passed all 520 tests in 20 isolated files (custody append: 84 passed). Normal full pre-push passed: 75 shared checks, 3 supplied-body metadata checks, zero backend typecheck errors; 33 selected backend files yielded 2,069 passed, 86 existing xfails, 4 emulator skips and 144 integration deselections. This is local static/synthetic evidence; no emulator integration run or deployed behavior is claimed. Checks use /Users/david/workspace/omi-workspace/bin/omi-heavy run -- with inherited GCP credentials and CLOUDSDK variables removed, private HOME/config and disabled metadata discovery. Exactly one fast-forward push completed from the parent to this head. Its mandatory hook also passed: 75 shared checks, 3 supplied-body metadata checks, zero typecheck errors, and the same backend counts. No workflow, deployment, ramp, access or production change. Stop after one green push for delta-only Luna and refactor-lead custody delta.

Historical qualifications below remain attributed to their original commits.

Current merge-main qualification

Earlier head: 584188bf8e8af86592e8c211ed8982649aa2fc58. Merge-main resolution under lead2 1c606e; one normal push from 2afc561cdb03a95695f603d3873c1433ebceda55, merging current main 75dc53a81df78643cf74c7638350fecc9082ebfc.

Resolution preserves both adjacent flag-catalog additions verbatim. Each parent independently added one index and moved the fixed field-index counts from 23/25 to 24/26; the combined registry requires 25 requirements / 27 modes. Only those two test literals were reconciled after the initial expanded preflight exposed the automatic merge collision. The reviewed token-lease metrics, quiet-check, erasure guard, receipt replay and renewal-retention behavior remain unchanged. No workflow or action was changed by this merge resolution.

Fresh checks on this exact head ran through /Users/david/workspace/omi-workspace/bin/omi-heavy run --, with inherited GCP credentials and CLOUDSDK variables unset, private HOME/config, disabled metadata discovery and synthetic fixtures:

  • Seal/custody/privacy/lifecycle plus pusher retention/barrier units: 40 files, 1,433 passed, 86 existing xfails, no failures or skips.
  • Real loopback Firestore and lifecycle: custody append 30 passed; no-job seal 4 passed; lifecycle/properties 34 passed and 3 existing xfails; held custody 75 passed; recovery custody 39 passed. Emulator shut down normally.
  • Expanded preflight: 75 passed, zero failures.
  • Normal full pre-push and actual mandatory push hook: both passed; 75 shared checks and 3 supplied-body metadata checks; backend typecheck zero errors. Each selected 33 backend files, yielding 2,068 passed, 86 existing xfails, 4 emulator skips and 144 integration deselections. The skipped/deselected emulator suites passed independently above.
  • Merge delta from prior PR head: 60 files, +4,899/-66, including incoming main. Current PR diff against merged main: 123 files, +9,583/-159.

The 86 strict lifecycle-invariant xfails and 3 lifecycle simulator xfails are existing; no xfail or skip was added. This is local static/synthetic and loopback-emulator evidence; remote CI and deployed behavior are separate. Exactly one normal push completed. STOP for delta-only Luna and refactor-lead's custody delta. No deploy, ramp or production access.

Historical qualifications below remain attributed to their original commits.

Previous L1 renewal-budget fix

Earlier head: 2afc561cdb03a95695f603d3873c1433ebceda55 (parent 023db969b7d158ba0c518c5cb318be11b90f6aaa). Addresses the custody delta 3 FIX-FIRST: a Firestore renewal refusal no longer enters the storage upload retry ladder. The unchanged batch stays in the ready lane with its existing audio-budget reservation, without incrementing upload retries or reaching fail_recording/the exhaustion drop. Disconnect-drain renewal retries remain paced and cancellable. The receive-window path is unchanged.

Incremental scope: 2 files, +68/-2; 11 changed non-test lines (under the 60-line cap). The two router regressions inject renewal errors beyond PRIVATE_CLOUD_SYNC_MAX_RETRIES during a live socket and after disconnect, then verify exact PCM reaches the synthetic upload writer without fail_recording. Both regressions fail against the parent and pass with the fix. Focused pusher barrier/abandon, custody and token-lease qualification: 413 passed across 14 isolated files, no failures/skips.

Normal full pre-push on this head passed: 75 shared preflight checks, supplied-body metadata validation, backend typecheck with zero errors; 33 selected backend files yielded 2,068 passed, 86 existing lifecycle xfails, 4 existing emulator skips and 144 integration-marker deselections. All qualification ran through omi-heavy run -- with inherited GCP credentials and CLOUDSDK variables removed, private HOME/config, disabled metadata discovery, and synthetic fixtures. This is local static/synthetic evidence.

Stop after the single fast-forward push for delta-only Luna and refactor-lead custody delta on this exact head. No deploy, ramp or production access.

Exactly one fast-forward push completed from the parent above to this head. Its mandatory pre-push hook also passed with the same 75 shared checks, zero typecheck errors, and backend counts.

Requested by David; ship owner: refactor-lead.

What changed and why

A vanished producer can otherwise keep audio unsealed indefinitely. Part A replaces that indefinite fence with a server-observed lease inside the existing producer map. Only storage-backed custody appends and frame-bearing pusher batches establish accepted late audio; custody heartbeat renewal requires this upload's explicitly acquired session in the eligible serve cohort. Off preserves original producer behavior, shadow observes, and serve uses the fresh record-token-lease cohort. Raw audio is retained throughout.

Custody uploads acquire an exact request token before staging, finalize after durable acceptance, and clear refusals without a revision bump. The custody lease covers the production backend-sync timeout plus the named 300s margin (currently 3900s); frame leases default to 3600s. Late audio invalidates the captured upload revision and re-arms create-only partial recovery, including interior holes. Recovery of accepted serve bytes survives mode rollback.

Separate recovery jobs are parked as record_recovery_waiting while the original publication is unsettled. Old worker images cannot schedule this state. The active repair CronJob and current workers transactionally promote it to record_pending only after the original ledger/publication completes, in off, shadow or serve; privacy revocation exits to privacy_blocked. This prevents a rolled-back worker from bypassing the publication fence. Normal partial processing retains its existing partial_retired exit and inventory rearm.

Finish receipts are idempotent across lost commit responses, enroll account-erasure authority before every write, and expire through the active repair CronJob after 24h. Expiry uses the existing server recorded_at, covering prior receipt versions. It deletes metadata only, never audio or recovery jobs. Pusher metadata-renewal failures retain receive windows or requeue projection batches before durable storage, and failed registration cannot be resurrected by a same-frame renewal. Persisted append_late survives registration retries; late metrics count durable acceptance exactly once.

Landing order: #24866 remains open and is an adjacent-file integration dependency, not a runtime prerequisite. Land #25018 first after this fresh-main merge. Then merge that resulting main into #24866 and preserve both its seal-gated scheduling/callback changes and this lease/revision protocol in shared transactions; regenerate its flag registry and rerun both focused suites. Do not rebase the published #25018 branch. #24832's age-only grace is superseded/absorbed. Main's staged-input alerts and both exact token-lease split-file payloads are retained in the regenerated union.

Consolidated privacy review fixes

Custody admission now checks the canonical owner/erasure authority before any custody token or raw staging, including missing accounts and active purge. Actual custody uses the same conversation privacy checks as finish/recovery; sync opt-out retains its existing no-custody behavior while still enforcing owner erasure. A missing identified target refuses admission. Finish/recovery logic is unchanged.

Archive heartbeats now identify the exact session acquired by this upload. Custody renewal requires that session and an eligible serve cohort; unowned, shadow and non-cohort archives retain read-only late observations without extending any custody token. Ordinary frame renewal and dead-letter behavior are unchanged. No flag, ramp, workflow, access or production change is introduced.

Previous merged candidate: 023db969b7d158ba0c518c5cb318be11b90f6aaa (includes current main 85de1985f0fb4fddd05e0de4b36c1ac68108d81e). Exact-head verification is recorded below; earlier results remain attributed to their recorded commits.

Product invariants affected

  • INV-DATA-1: preserves the existing production customer identity and data plane. The changes in gcp_backend_listen_helm.yml and gcp_backend_pusher.yml only validate and bind the four shared record-token-lease rollout inputs; they do not change customer-data endpoints, Firebase/Auth/Firestore projects, UID authority, service accounts, credentials or IAM. This is not a customer-data migration.
  • INV-MEM-4: canonical admission remains the sole Long-term authority; runtime wiring does not add an admission path.

Failure class (fixes)

Failure-Class: FC-state-deadline-without-reader-exit

lease_would_expire is a shadow diagnostic, not a persisted job state. Its observation ends with the next planner evaluation: a fresh append restores liveness, exact finish clears the fence, or serve-mode retained-tail/privacy proof permits seal/partial finish.

Named exits: producer lease lapse still requires the quiet heartbeat/append predicate plus retained-tail/privacy proof; exact finish clears custody; complete seal and partial finish remain distinct; late audio reactivates the revision. Parked recovery exits through database/record_recovery_gate.py:promote after original publication, independent of the mode. Finish receipts exit through database/record_custody_receipts.py:prune or account erasure after the bounded retry window.

How it was verified

Source inspection checked the INV-DATA-1 routing guard entry in .github/checks-manifest.yaml, the production-data-plane declaration in backend/utils/cloud_tasks.py, and the two small workflow diffs. Those diffs add rollout-input validation/binding only. This is static source evidence, with no live customer-data or deployed-artifact verification. Historical runtime/custody results remain attributed to their original tested commits.

Local commands use bin/omi-heavy, credential-free private test environments and the canonical backend/test.sh, with 900s per file. The batched pre-review report records the exact focused, all-backend custody, lifecycle/emulator, alert/telemetry, real PromQL, hook typecheck and expanded preflight results. New custody, nojob and lifecycle property proofs are wired into the emulator CI lane; the checksum-pinned PromQL check runs in both local and CI manifest lanes. The 50ms race now uses event-driven expiry inside enqueue without weakening its one-write assertion.

Evidence: backend/docs/listen_pusher_pipeline/changes/2026-11-10-token-lease-batched-prereview.md (local validation report). No production access or GCP credentials used; refactor-lead performs the single push and subsequent independent review.

Rollout

Default lease mode remains off with serve percent 0. This branch and this qualification apply no deployment, traffic shift, environment-variable change, access grant or customer-data operation. The workflow additions take effect only on a separately authorized workflow execution; a branch push does not authorize or perform the production rollout.

Checked-in defaults remain off. Bind the same four RECORD_TOKEN_LEASE_* protected-environment inputs to Cloud Run and the shared producer ConfigMap; GKE pods consume explicit key references. Roll all producers through shadow for 48h before serving. Configure the separately typed repair vector to match, and enable repair serve only after producer rollout is verified. Use a fixed preview epoch in shadow, pin the first serve epoch across the whole ramp/restarts, and require lead2 approval plus P4 auto-revert at 1/10/50/100%. Retune 3600s only from the signal-gap histogram at 10%; require RECORD_GAP_FILL_PERCENT >= 10 before 100%. Mode shadow/off rolls back behavior while preserving already-acquired custody and recovery obligations. An old-image worker rollback parks separate recoveries until a current worker resumes safe promotion.

Capacity disclosure: receipt cleanup before 0, after max 10000 metadata receipts per active repair run, with 128-document query pages and a 30s maintenance budget. Recovery promotion adds one bounded waiting-state query and up to 100 transactional publication/privacy checks with a CAS write to each record-pending scan, reusing the existing due-page limit, with a new 60s recheck backoff and a fresh transactional availability CAS. The active production repair CronJob invokes the same bounded promoter (one query, up to 100 checks, 30s) without enabling the idle seal worker; promotion and receipt cleanup have separate 30s phases, at most 60s total before the unchanged audio-repair budget. No raw-audio retention, audio inventory cap (8192), worker concurrency, executor size or production capacity is increased. The receipt collection-group recorded_at index is declared in the generated manifest; normal schema readiness gates apply before shipping.

UI evidence

UI-Evidence: none -- backend custody and validation change only

Source growth declarations

Line-Count-Exception: backend/database/firestore_index_registry.py | 2343 -> 2344 | Declare the receipt-expiry collection-group index at its schema owner.
Line-Count-Exception: backend/routers/pusher.py | 2032 -> 2051 | Renew frame custody at the existing appender; retain metadata-refused batches under the audio budget without consuming storage retries.
Line-Count-Exception: backend/routers/sync.py | 3830 -> 3852 | Keep the serve-cohort guard adjacent to the existing manifest heartbeat.
Line-Count-Exception: backend/testing/listen_pusher_stack/run.py | 1980 -> 1988 | Bound numerical thread pools in every isolated lifecycle child and restart.

Recovered-head qualification

Registry completion is 41a173de1d79959c5b5ab26ba6e9a8c785db29fc; the synthetic-account fixture is 70a31d885774680bf576d97712575207ae37d64a. The earlier test-only completion is 4152755f9c4b5471e6f9841d6037c5ff5cfb8849 (+3/-2, one test file). It synchronizes the custody clock at 10000 and aligns the final expectation with the expired frame lease. No product behavior, privacy guard, query, index, lease policy or flag changed in this completion.

The final assertion was corrected because the frame token's lease lapsed at the mocked clock; product behavior unchanged.

The earlier runtime/custody, emulator/lifecycle, focused, query/index, PromQL/pre-deploy and typecheck results remain recorded at their actual tested commits; they are not represented as rerun on this merged candidate. On merged candidate 3fc6150cc191140c6ffa8e645bac4871b0cce2e5, the product-file ratchet passed across 28 changed product source files; product-invariants accepted INV-DATA-1 and INV-MEM-4; expanded preflight passed all 75 checks; normal full pre-push passed, including its backend typecheck with zero errors and 28 selected backend unit files. These are local static and synthetic qualification results; CI and deployed-artifact behavior remain separate evidence. No production access, deployment or ramp.

The index-count assertion was updated to match this PR's own registry change (24/26); product behavior unchanged.

The ci-budget manifest now records the rationale and expected runs for the emulator-proofs trigger change already in this PR; no workflow behavior changed.

Staging input completion

Staging explicitly sets the four RECORD_TOKEN_LEASE_* inputs to off/0/3600/a fixed staging epoch, and STAGING_DIFF_ALLOWLIST now permits exactly those four names as independent staging inputs.

Previous merged-head local qualification

Earlier head: 30e3ab980a5fd9c7c509ab9410eda7943d649636. Merged main: 85de1985f0fb4fddd05e0de4b36c1ac68108d81e. The final allowlist-only commit adds five lines in one file, including exactly four explicit names; staging retains off/0/3600/1794268800.

All gates below ran fresh on this head through /Users/david/workspace/omi-workspace/bin/omi-heavy run --, with inherited GCP credentials and CLOUDSDK variables stripped, private HOME/config, disabled metadata discovery, and synthetic fixtures:

  • Staging overlay: 21 passed, zero failures.
  • Seal/custody/privacy/lifecycle units: 36 files, 1,343 passed, 86 existing strict lifecycle-invariant xfails, zero skips/failures.
  • Real loopback emulator: custody append 30 passed; no-job seal 4 passed; lifecycle/properties 34 passed and 3 existing xfails; held custody 75 passed; recovery custody 39 passed. Emulator shut down normally.
  • Expanded preflight against current main: 75 checks passed, zero failures.
  • Normal full pre-push: passed; shared preflight 75 passed, metadata precheck 3 passed, backend typecheck zero errors; 30 selected files produced 1,962 passed, 86 existing xfails, 4 emulator skips, and 144 integration cases deselected. Skipped/deselected emulator suites passed independently above.

Residual expected failures remain the existing 86 lifecycle invariants plus the 3 lifecycle simulator cases: test_sealed_no_job_registered_recovered, test_upload_failed_gets_retried, and test_server_batch_completion_ordering[closed-before-completed]. No xfail/skip marker was added. Local qualification does not establish remote CI or deployed behavior. Stop after push 2/2 for delta-only Luna; no deploy, ramp or production access.

Receipt replay completion

This change completes Luna finding (2): begin() recognizes the accepted exact-session finish receipt before adding custody, preserving idempotent finish replay without leaving a token that blocks sealing. The regression proves begin/finish/retry leaves no token, revision or metric change and no seal refusal.

Earlier head: 15fc2627f3d9d923bd88c1358232c8e3521859ae (parent 30e3ab980a5fd9c7c509ab9410eda7943d649636). Incremental diff: 2 files, 32 additions; 4 product lines and 28 test lines. Focused custody/erasure/privacy/token-lease suites: 515 passed in 20 files. Real loopback Firestore custody-append suite: 30 passed. The new regression was first observed failing on the parent before the guard was added. Normal full pre-push passed: 75 shared checks with supplied-body metadata validation, backend typecheck with zero errors; 30 selected backend files yielded 1,963 passed, 86 existing xfails, 4 emulator skips, and 144 integration cases deselected. The actual push hook also passed with the same counts. Exactly one fast-forward push completed, from the parent above to this head. All checks ran through omi-heavy with inherited cloud credentials and CLOUDSDK variables unset, private HOME/config, disabled metadata discovery, and synthetic fixtures. This is local static/synthetic and loopback-emulator evidence; remote CI and deployed behavior are separate. No deploy, ramp or production access. Stop after the single push for delta-only Luna and refactor-lead custody review on this exact commit.

L1 CI and pusher correction

Candidate: 023db969b7d158ba0c518c5cb318be11b90f6aaa, based on published 15fc2627f3d9d923bd88c1358232c8e3521859ae. Batch scope is 120 changed non-test lines (cap 150); no workflow file changes.

Finding-by-finding resolution:

  1. Deploy assertions: render production separately from the pinned staging overlay, assert its actual timeout plus custody margin, and avoid repeating mode-invariant Helm work inside the CPU-timed test.
  2. Pusher renewal P2: a failed metadata renewal returns a refusal. Receive windows keep their audio/WAL unacknowledged; projection batches requeue before storage. A pending refusal survives mode rollback until retry succeeds or ownership is retired. Regressions cover retention, retry, and cleanup.
  3. Monitoring inventory drift: regenerate the committed inventory with only the two record-token-lease alert consumers and their count adjustment.
  4. Alert serialization: restore the combined export's exact split-source bytes. Parsed alert objects, query expressions, thresholds, and notification behavior are unchanged.
  5. Composite action: replace unavailable vars reads with four explicit action inputs. Defaults remain off/0/3600/0; the same validator writes the complete vector to GITHUB_ENV only after validation. Existing stack callers omit these inputs and therefore stay at defaults. Protected-environment variable forwarding at those callers is not added in this batch; a future rollout must explicitly supply the inputs under separate authorization. Standalone workflow bindings are unchanged.
  6. Test drift: align held-state and isolated-canary inventories and remove stale real-clock allowlist entries. No new skip or xfail marker.

Fresh credential-free qualification: 994 passed across 34 isolated files, including the deploy, pusher barrier, custody/token-lease and monitoring/action contracts. The initial run hit the unchanged real-clock scanner CPU guard at 1.02s/1.00s after all assertions passed; the canonical single-file rerun passed all 11 cases with unchanged limits. Pinned formatting was applied to the updated CI test. Final normal full pre-push on 023db969b7d158ba0c518c5cb318be11b90f6aaa exited 0: 75 shared checks, supplied-body metadata validation, zero backend typecheck errors; 33 selected backend test files yielded 2,066 passed, 0 failed, 4 existing emulator skips, 86 existing lifecycle xfails and 144 integration-marker deselections. The first pre-push attempt stopped on the stale pusher growth declaration; it was corrected to 2032 → 2044 before this green rerun. No source change or check bypass was needed. All checks use /Users/david/workspace/omi-workspace/bin/omi-heavy run --, with inherited GCP credentials and CLOUDSDK variables unset, private HOME/config, metadata discovery disabled, and synthetic fixtures. Local static/synthetic evidence does not establish remote CI or deployed behavior.

The previous shard-5 collection diagnosis remains resolved: interleaved output came from the inventory assertion, not a collection/import failure. The capture-continuity failure remained unreproduced on main and L1 and is untouched. The previously observed emulator cursor-age clock-boundary issue is also untouched; this batch does not claim a new emulator run.

Exactly one normal fast-forward push completed from 15fc2627f3d9d923bd88c1358232c8e3521859ae to 023db969b7d158ba0c518c5cb318be11b90f6aaa. Its mandatory pre-push hook also passed: 75 shared checks, zero typecheck errors, and the same 2,066 passed / 86 xfailed / 4 skipped / 144 deselected across 33 selected files. Final batch diff: 12 files, +199/-52; 120 changed non-test lines. Stop here for independent delta and custody review on this exact head. No deploy, ramp, production data/config, credentials/IAM, or UI changes.

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

ℹ️ 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 +131 to +133
# A later object can fail after earlier create-only writes succeeded.
# Re-arm those durable chunks even while the phone retains its WAL.
await run_blocking(db_executor, wake_partial, store, uid, cid, gap.time.time())

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 Create recovery work for the first refused late-WAL append

For a serve-cohort recording whose full native intake has already completed, the first WAL containing previously missing interior audio can successfully retain new chunks here without ever scheduling their processing. wake_partial() only updates existing partial coordinators, so it does nothing for this recording. In registered_record_response(), _covered() still checks the original intake's immutable audio and returns audio_coverage_unproven; consequently, the custody wrapper calls finish(accepted=False), which also skips recovery creation. With no subsequent pusher frames, every retry follows the same path: the phone keeps its WAL and the newly retained speech remains unprocessed. Create a recovery obligation for successfully retained chunks even when the HTTP request conservatively refuses acknowledgment.

Useful? React with 👍 / 👎.

Comment thread backend/utils/pusher_record_barrier.py Outdated
Comment on lines +386 to +390
except Exception:
# Metadata is a side channel. Keep the old renewal clock so a
# later batch retries, and let this batch retain its audio.
logger.warning('event=record_token_lease_renewal outcome=unavailable')
return

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 shared telemetry when lease renewal fails open

When the frame-lease transaction fails, this branch deliberately continues receiving and retaining audio without a renewed producer fence, but emits only an ad hoc warning. That is a new fail-open path and therefore requires record_fallback under backend/AGENTS.md; otherwise these degraded renewals are absent from the shared fallback metrics used to observe rollout safety. Emit the shared helper with a bounded degraded outcome before continuing.

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

Useful? React with 👍 / 👎.

Git-on-my-level added a commit that referenced this pull request Nov 10, 2026
)

## What and why

Retire summary due indexes atomically when donor tombstones, manual
title/overview edits or already-enriched merges refuse repair. Preserve
`summary_first_pending_at`. Undo/manual-field removal and discard
restore recover owed debt in the same transaction using original
acceptance plus the row's policy deadline, without replacing a non-null
due or arming a refused/owned row. Internal debt metadata stays outside
reversible user-field receipts.

The guarded operator script clears legacy residue using the serving
refusal classifier. Unknown provenance is retained for provenance
repair; processing, local-only, BYOK and active finalization ownership
are explicitly retained even when another refusal has precedence. Both
completion metadata and output-present metadata retire copied legacy
due. No serving rate, feature flag, deadline, capacity, repair-service
or released-client schema changes.

## Merge order — required hold

Merge **after #25019 and #25032. This PR must not merge before #25032.**
Both dependency PRs were OPEN when this batch began. After #25019 lands,
rebase onto current `origin/main`, regenerate inventories and retain
both sides' tests; never resolve a shared-file conflict by taking one
side wholesale. Repeat exact inventory guards after any overlapping PR
lands. #25032 owns its upstream registry/flag-budget train conflicts;
this batch does not edit them.

## Operator run plan — cl2-deploy only

1. Deploy the merged code first, then identify the exact serving
revision. Old writer sites keep re-arming due during the sweep, so a
pre-deploy sweep or dry-run is insufficient.
2. Re-run a fresh dry-run **after deployment on that serving revision**.
Verify the deployed `summary_due_at` collection-group index and inspect
class/retained/eligible/conflict counts before any apply.
3. Run a bounded **5,000 scanned-row canary**, using an apply cursor
separate from the dry-run cursor. Production `--apply` additionally
requires `--confirm-production-project based-hardware` matching the
actual client's project. Review canary counts.
4. Run the full sweep **only on lead2's go**. Re-run the
serving-revision dry-run after any intervening code deployment; restart
without a cursor to reconsider conflicts as needed.

The sweep runs **two disjoint passes** at one cutoff instant: a numeric
`summary_due_at <= now` pass, then a Timestamp `summary_due_at <=
datetime(now, UTC)` pass. Each uses `(summary_due_at, __name__)`
pagination, classifier-only projection and batches of at most 400
writes. Every clear retains the original snapshot `update_time`
precondition, including individual retries after atomic batch failure.
Concurrent re-arm/delete is skipped. `--limit` bounds the combined
scanned rows across both passes, including retained rows. Aggregate
counts remain available, with scanned/eligible/classes/written/conflicts
also reported separately under `passes.numeric` and `passes.timestamp`.
Output is counts-only; private cursor files are written to unique
same-directory `mkstemp` files, explicitly set to mode `0600`, flushed
and fsynced before atomic replacement; any failed attempt removes its
temporary file and preserves the previous checkpoint. They include a
`pass` marker plus a numeric or tagged RFC3339 due and document path,
with no IDs printed. Cursors are separate for each pass: completing
numeric scanning checkpoints `{pass: "timestamp", due: null, __name__:
null}` before the first timestamp query. Resuming a timestamp checkpoint
skips the completed numeric pass. Older unmarked cursors infer their
pass from the due type. Keep apply/dry-run cursor files separate. This
operator-only metadata cleanup is exempt from content-generation batch
privacy admission: it never reads transcripts/generated summaries or
changes protection levels or content. No production access or operator
run was performed in this lane.

## Follow-up: private atomic checkpoints

Review-desk FIX-FIRST at `f940cf9dd489` found that the predictable
`.tmp` path could expose private cursor document paths through a
pre-existing permissive file or symlink. Checkpoint publication now uses
a unique file in the checkpoint directory, explicit `0600`, flush/fsync
before `os.replace`, and unconditional temporary-file cleanup on
failure. Atomic replacement also replaces a final-path symlink without
following its target.

- Backfill suite through omi-heavy: **101 passed / 1 existing
loopback-only skip**, 1.33s, completed approximately 2026-11-10 17:51Z.
All eight new filesystem/security cases passed. This follow-up changes
only the backfill script and its test file; no operator --apply or
production access.
- Checkpoint follow-up head: `8159c89608d86c4c67a9bfc5d077e57c7df2f48f`.
`make preflight`: **39 checks passed in 64.42s**, completed
approximately 2026-11-10 17:55Z. Full PR non-test scope: **397 changed
lines**, within the original 500-line cap. The single authorized
checkpoint follow-up push succeeded as a fast-forward, approximately
2026-11-10 17:55:43–17:57:17Z. Its normal hook passed **39 shared checks
(67.26s), typecheck with zero errors, 250 passing changed-file tests
plus 23 explicit loopback-only skips**, and pinned formatting.
Exact-head CI is being monitored with a 90-minute deadline.

## Follow-up: two-pass sweep

Review-desk FIX-FIRST at `50f47f8058fc` found that a numeric cutoff
never selects Timestamp-valued due. The backfill now queries both types
and keeps the same classifier, fences, dry-run default and counts-only
output in each pass. Checkpoints explicitly mark the active pass and
survive interruption at the pass boundary.

Read-only inspection also confirms the serving query/repair blind spot:
`database/summary_debt_queries.py:13,24` uses a numeric cutoff/cursor;
`services/summary_debt_repair.py:50` rejects nonnumeric due and its
overdue-age arithmetic assumes a number. Those files are **unchanged**,
as requested; cl2-fixnow should route that finding to #25019's owner.

- Focused selection re-run through omi-heavy, 2026-11-10 approximately
17:12Z: **2,209 passed / 23 skipped / 86 xfailed**. Adjacent **117
passed**; extra chat/tool/strict transaction selection **55 passed**.
Per-file commands, exact timestamps and results:
`focused-results-followup-m1.json` in the supplied task directory.
- Backfill tests against synthetic loopback Firestore: **94 passed**,
receipt completed 2026-11-10T17:12:06.668829+00:00. Includes actual
mixed-type inequality behavior, refused clears, owed/future retention,
shared limits, both cursor types, interruption at the pass boundary and
bounded/fenced writes. Emulator shut down normally.
- Follow-up at earlier head `f940cf9dd4898798c72e854c0dd5226554b76866`.
`make preflight`: **39 checks passed in 46.50s**, 2026-11-10
approximately 17:15–17:16Z. Full PR scope: **388 non-test changed
lines**, within the 500-line cap.
- Only the backfill script and its test file changed in this follow-up.
Serving query and repair files remain untouched. The single follow-up
fast-forward push succeeded on 2026-11-10 approximately
17:16:32–17:17:52Z. Its normal hook passed 39 shared checks (57.04s),
typecheck with zero errors, 242 passing changed-file tests plus 23
explicit loopback-only skips, and pinned formatting. CI is being
monitored on this exact head with a 90-minute deadline.


## Verification of the preceding batch

Verification is hermetic code and synthetic loopback Firestore evidence,
not deployed-runtime evidence. Commands use
`/Users/david/workspace/omi-workspace/bin/omi-heavy run --` and the
worktree's Python 3.11, with GCP credential environment scrubbed. Pytest
files run in isolated processes under the backend unit contract.

- Requested focused selection on this batch: **2,170 passed, 22 skipped
(loopback tests run separately), 86 xfailed**, 2026-11-10
16:14:30–16:15:06Z. The old ae48104 selection measured 2,087/4/86; new
guards add passing cases and the new emulator cases increase the
explicit loopback-only skips.
- Adjacent selection: **117 passed**, 16:15:06–16:15:13Z; additional
chat/tool/strict People transaction selection: **55 passed**,
16:15:13–16:15:18Z. Exact per-file commands, timestamps and logs:
`/Volumes/scratch/cl2-fixnow-move25020/focused-results-m1.json`.
- Synthetic loopback Firestore: **22 chat edit/undo tests passed** and
**31 People-generation emulator checks passed**, 2026-11-10
approximately 16:13–16:14Z. Emulator stopped. Used the installed Java 21
in the process environment only.
- `make preflight` on commit `50f47f8058fcb904bb5bd185184c1473284783cc`:
**39 checks passed in 55.79s**, 2026-11-10 approximately 16:17–16:18Z.
The full PR has **354 non-test changed lines** (342 additions / 12
deletions), below 500.
- Regenerated the lifecycle payload inventory for changed owners and all
People fingerprints (only the four already-audited chat scopes differ);
People generator check reports no delta. Exact lifecycle
inventory/state-table guard is included above; serving lifecycle write
guard passed in preflight. Normal pre-push on
`50f47f8058fcb904bb5bd185184c1473284783cc` passed all 39 shared checks,
typecheck with zero errors, 203 passing changed-file tests plus 22
explicit loopback-only skips, and pinned formatting for all 15 PR Python
files (2026-11-10 16:18:28–16:19:46Z). The single fast-forward push
succeeded with no bypass.


UI-Evidence: none — backend metadata and an operator script only.

## Finding dispositions

| Finding (review sources) | Disposition in this batch |
|---|---|
| Predictable checkpoint temp path can follow a symlink or reuse
permissive permissions (review-desk 72a878, FIX-FIRST) | Use exclusive
unique same-directory `tempfile.mkstemp`, enforce `0600` via `fchmod`,
write/flush/fsync, then `os.replace`. Cleanup runs on failure, leaving
the previous checkpoint intact. Regressions cover the old predictable
symlink/permissive file, permissive umask, write/fsync/replace/fchmod
failures, descriptor closure and safe replacement of a final-path
symlink. |
| Numeric-only cutoff misses timestamp-valued due (review-desk e7b7dc,
FIX-FIRST) | Replaced with numeric and Timestamp passes, distinct
pass-aware checkpoints and per-pass counts. Tests cover
refused/owed/future rows in both types, shared limits, resumable pass
boundary, update-time conflicts and 400-write caps. A loopback Firestore
regression verifies actual mixed-type query behavior. |
| Unknown provenance retired as durable; #25032 late projection stranded
(pd correctness/custody/tests/merge/Kimi) | Removed from
`DURABLE_REFUSALS` and durable test cases. Regression retains the legacy
due and first-pending anchor. Missing provenance still needs its owning
repair; this batch never clears it. |
| Manual undo loses owed debt (all correctness/custody/test reviews, old
merge/CI) | Chat restore and explicit null/DELETE_FIELD removals re-arm
atomically from preserved first pending plus the stored
`first_summary_policy` deadline, falling back to `deadline_seconds()`.
Refused rows and already-armed rows never acquire a replacement due.
Real codec, strict transaction and loopback emulator coverage. |
| Every other manual removal path needs coverage (sdclear-fix1) | Title
UI and offline empty titles remain non-null manual values, covered by
retirement tests. Chat tools reject blank title/overview edits before
IO. Sync restore and generated persistence preserve manual fields. All
actual removal writers are declared in the lifecycle inventory. |
| Summary BYOK reason not excluded; terminal BYOK semantics untested (pd
correctness/custody/tests) | Explicitly retain
`summary_blocked_reason=blocked_byok`, including a competing deleted
flag and no active job. Existing finalization BYOK exclusion remains. No
terminal-BYOK policy expansion. |
| Detached queued/leased finalization rows (pd correctness) | Explicitly
retain both statuses even without a job ID, including competing
manual/discard flags. Re-arm also respects these owners. |
| Output-present enriched row can retain copied due (pd custody) | Both
completion metadata and `summary_output_present=True` take the enriched
return and retire due. Empty reprocessing preserves banked structured
content without requiring a completion stamp. |
| Discarded rows recoverable after sweep (pd correctness/tests) | The
existing restore transaction re-arms only currently owed, unarmed rows
from original acceptance and policy. Tests cover cleared legacy rows
without receipts, manual/enriched/locked refusal, existing due and
writer ownership. |
| Refusal classes can later reopen (pd correctness/custody) | Manual and
discard inverses now recover debt. Empty-output revision re-arm stays
intact and is covered by the adjacent recovery suite.
Privacy/content-floor decisions remain governed by their existing
policy; this metadata cleanup does not introduce a new privacy/content
transition. `DURABLE_REFUSALS` now documents current-obligation
retirement rather than permanent lifecycle finality. |
| Backfill bypasses batch privacy fence (pd custody) | Documented
metadata-only operator exemption: no transcript or generated summary is
read or written; only the due index is cleared with a snapshot
update-time fence. Serving content-generation fences remain unchanged. |
| Non-JSON due checkpoint (pd custody) | Timestamp cursors use private
tagged RFC3339 values and decode on resume, preserving Firestore
timestamp type and nanoseconds. Numeric cursor format remains supported.
|
| No explicit prod apply guard (pd custody) | `--apply` on
`based-hardware` requires matching `--confirm-production-project
based-hardware`; an unknown project fails closed. Synthetic unit
coverage only; no operator apply was run. |
| CLI failure path / deleted cursor not tested (pd tests) | Added
counts-only CLI error regression and resume after a deleted numeric
cursor; timestamp cursor also resumes after a missing cursor document. |
| Unchanged-title path lacks assertion (pd tests nit) | Added
no-write/no-due-move assertion for an unchanged offline title. |
| Legacy exact title assertion fails CI (old CI/merge) | Already
corrected at ae48104; retained and re-run the full revision-contract
file. |
| Update-time fence, dry-run, bounded cursor, counts-only output (all
reviews) | Preserved; original race, atomic-batch, tie/resume,
scanned-row limit, batch-size and privacy tests remain intact. |
| Deploy must precede sweep (old merge, sdclear-fix1) | Run plan below
requires code serving first and a fresh post-deploy dry-run on that
exact serving revision before the 5k canary. Old writers would keep
re-arming due during a sweep. |
| Code revert cannot restore cleared rows (pd merge, old custody) |
Rollback explicitly requires a separately authorized re-stamp keyed on
preserved `summary_first_pending_at`, current owed rows only. |
| #25019 / #25032 ordering and same-file inventories (pd merge, old
merge, sdclear-fix1) | Must merge after both, never before #25032. Both
were OPEN at intake; no premature rebase. After #25019 lands, rebase and
regenerate inventories, preserving both sides and tests rather than
taking a side wholesale. |
| Upstream #25032 registry / #25034 flag-budget conflicts (pd merge) |
Dependency-owner work outside this batch. The merge train must resolve
those before #25020; no workflow/flag-budget edits here. |
| #25018 / #24866 / #24801 / #24897 / stale #24607 overlaps (old and pd
merge) | Re-fetch before integration; if these land first, rebase and
re-run exact inventories and both branches' tests. No unrelated PR
changes or merges performed here. |
| Operator query excluded from serving-query inventory (pd merge) |
Preserve script scope. Uses the existing `summary_due_at`
COLLECTION_GROUP single-field index; cl2-deploy must verify the deployed
index with the serving-revision dry-run before canary. No production
query in this lane. |
| People audit and lifecycle inventories after shared-scope changes (all
test reviews) | Regenerated reviewed entries and four existing People
fingerprints after strict transaction and loopback emulator proof;
exact-match guards re-run. |

## Rollback

A code revert **does not restore rows whose due indexes the backfill
already cleared**. Preserve the operator receipts/cursors and stop the
sweep. A separately authorized repair must enumerate/re-stamp keyed on
the preserved `summary_first_pending_at`; only rows the current
classifier calls owed, with no competing owner and a null/missing due,
may receive `summary_first_pending_at + stored first_summary_policy
deadline` (or `deadline_seconds()` without a snapshot). Never reset the
anchor, move a non-null due, or blindly re-arm refused rows. Do not use
the due index itself to find already-cleared rows.

Failure-Class: FC-obligation-outlives-terminal-owner

Line-Count-Exception: backend/database/conversations.py | 4960 -> 4969 |
Keep atomic due retirement and guarded discard-restore re-arm at their
owning writes.

Line-Count-Exception: backend/utils/sync/assignment.py | 1538 -> 1539 |
Keep atomic summary-debt retirement at the donor redirect write.
Git-on-my-level added a commit that referenced this pull request Nov 11, 2026
…#25049)

# seal-speed: cut the per-row startup bill and give the repair pod real
CPU

## Why

A recording seal takes ~89 s per row (p50) and the seal itself is ~5 s
of it.
Measured 2026-11-10 on `origin/main` = `9c051da5be4b` (evidence:

`omi-workspace/data/run-2026-11-08-pipeline-refactor/findings-fable-seal-time.md`):

| stage | p50 | share |
| --- | ---: | ---: |
| `startup` (fork/exec + module imports) | 45.1 s | 51% |
| `clients` (lazy imports + Firestore/GCS construction) | 32.7 s | 37% |
| `proof` + `list` + `walk` + `apply` (the actual seal) | 5.3 s | 6% |

Two compounding causes, both fixed here:

1. **The row process imports the web framework.**
`record_seal_cluster_repair`
reaches `utils.observability.fallback` -> `utils.metrics` -> `from
fastapi
import Response`, and `database.batch_pipeline_store` ->
`utils.sync.stage`
-> `from fastapi import HTTPException`. fastapi/pydantic is ~60% of the
   import bill. A recording seal does no HTTP work.
2. **The pod is CPU-starved.** The CronJob's `nodeAffinity` deliberately
excluded `batch-pipeline-pool`, so repair landed on the monitoring pool
at
101% CPU and received ~2 of its 4-core limit. The batch-pipeline pool
sits at
   8-19% CPU. The image also shipped no `.pyc` and the CronJob set
`PYTHONDONTWRITEBYTECODE=1`, so every one of ~250 row processes per run
   re-parsed source.

**No worker-count change.** 16 -> 24 was already measured in prod and
lost
15-35% of seals per run (#24962, reverted by #24966); 48 was worse
(#24729).
More workers only split the same starved CPU.

## What changed

**1. Placement and CPU request (chart only).**

`backend/charts/batch-pipeline-worker/templates/record-seal-repair.yaml`
now
pins the repair pod to `batch-pipeline-pool` and carries that pool's two
taints
(`omi.ai/batch-pipeline=true`, `nvidia.com/gpu=present`). CPU request 2
-> 4,
which equals the unchanged CPU limit. Memory remains request 4 GiB /
limit
8 GiB, so the pod stays Burstable; the scheduler now reserves four CPU
cores. Both are values-driven
(`recordSealRepair.nodePool`, `recordSealRepair.tolerations`,
`recordSealRepair.cpuRequest`); setting `nodePool=` and `tolerations=[]`
restores the old exclusion from values alone.

**2. Precompiled bytecode.**
`backend/diarizer/Dockerfile.batch-pipeline` gains `RUN python -m
compileall -q
/app` after the last `COPY`, and the CronJob no longer sets
`PYTHONDONTWRITEBYTECODE=1`. The repair pod runs with
`readOnlyRootFilesystem: true`, so the `.pyc` must be baked at build
time.
`.dockerignore` now excludes `**/__pycache__` so host bytecode cannot
shadow
the build-time compile.

**3. No web framework in the row path.**
`utils/metrics.py` and `utils/sync/stage.py` import fastapi inside the
one
function that needs it (`metrics_response`, `require_http_stage`) and
annotate
with `TYPE_CHECKING`. Behaviour is unchanged: `/metrics` still returns
the same
`Response`, and the sync-stage HTTP dependency still raises
`HTTPException(503)`.

## Follow-up: Plan v3 L2 ordering

The bundle omitted the newest-first / near-dead-letter-first part of L2
(David ruling reference `6db8f2`). The follow-up adds:

- Urgent pending jobs first, ordered by their stored dead-letter
deadline and
document name. **Implementation choice: near = final 24 hours** before
the
stored 14-day barrier deadline; already overdue pending jobs are
included.
  Age never invents a deadline, and terminal jobs are excluded.
- Newest enqueue/name order for ordinary jobs and newest finish/name
order for
conversations. The existing half-worker reservation for conversations
stays.
- An independent encrypted urgent cursor and new recency cursor names,
keeping
old ascending frontiers out of the descending scans. Frozen recency
horizons,
wrap, minimum-age eligibility, exact numeric cursor clocks, and
checkpoints
  before proofs / after attempts remain covered.
- Five additive indexes in the batch registry and generated manifest:
job
recency/deadline for both stages, and completed-conversation recency.
The
deployment readiness gate must confirm them before an image ships. No
live
  index apply or deploy was run.
- Default-on behavior through the existing
`RECORD_SEAL_REPAIR_AGE_ORDER` kill
switch. Off skips urgency and restores the original hash jobs scan. The
ordinary missing-index fallback survives; a missing urgent index skips
only
that leg, emits content-free degraded telemetry, and continues ordinary
and
  conversation discovery.

The extra urgent page uses 128 rows **inside** the existing 10,000-row
aggregate
scan cap; candidate cap 1,024, worker count 16, row budget 270 seconds
and run
budget 1,500 seconds are unchanged. Roll back the follow-up commit to
restore
prior ordering; old frontier documents are untouched. No seal-proof or
custody
rules change. Also corrected the chart test's QoS wording and added
Starlette
to the coordinator-module import assertion.

## Tuning disclosure

| | before | expected after |
| --- | --- | --- |
| per-row p50 | 89 s | ~40-55 s |
| workers | 16 (unchanged) | 16 (unchanged) |
| CPU actually available | ~2 cores (node at 101%) | 4 cores
requested/reserved |
| seals/run | ~200 | ~330-450 (estimate) |
| throughput | ~390 seals/h | ~700-900 seals/h (estimate) |

The "after" numbers are estimates, not measurements: they extrapolate
the
measured import share and the 2 -> 4 core change. They must be confirmed
from
the CronJob's own `record_seal_repair_row` stage events over a full run
before
any further tuning. **This PR does not change worker count,
`rowSeconds`, the
run budget, or the seal rules.**

Local import measurement (warm Mac, image-shaped tree, 2,811 `.py`
files):

| | row import |
| --- | ---: |
| before, with `.pyc` | 8.0 s |
| after, with `.pyc` | 1.2 s |
| after, without `.pyc` | ~3.9 s |

So the fastapi removal is the larger lever (~6.7x) and `compileall` is
the
second (~2x on the remaining import). The absolute seconds are
indicative; the
*share* is the load-bearing part.

### Scheduling note the reviewer should weigh

`g2-standard-8` allocatable is ~7.8 vCPU and the GPU worker requests 4,
so a
4-CPU repair pod does **not** co-schedule with a worker: the pool
autoscaler
adds a node (pool max 16, currently 4 workers). That is the cost of a
four reserved CPU cores. If the lead prefers no extra node, set
`recordSealRepair.cpuRequest: "3"` — 4 + 3 = 7 fits beside a worker, and
the pod
still gets 3 guaranteed cores instead of today's ~2. This is a
values-only
change; the template does not need to move.

## Rollback

- **Placement only:** `--set recordSealRepair.nodePool= --set-json
  'recordSealRepair.tolerations=[]'` restores the old monitoring-pool
exclusion. `--set recordSealRepair.cpuRequest=2` restores the old
request.
- **Whole job:** `recordSealRepair.suspend: true` (already the
documented
  rollback in `prod_omi_batch_pipeline_worker_values.yaml`).
- **Code:** revert this commit. The lazy imports are
behaviour-preserving, so a
revert needs no data migration and no image rollback beyond the normal
digest
  pin.

## m1 verification (2026-11-10)

Merged `origin/main` through `986386ba0e48` without rebasing. Through
`bin/omi-heavy`
and `backend/test.sh` (file-isolated runner): import graph **4 passed**,
chart
render contracts **13 passed**. Worker count remains 16 in the
production render.

The completed follow-up also ran this explicit 12-file selection through
`bin/omi-heavy run -- env -u GOOGLE_APPLICATION_CREDENTIALS -u
CLOUDSDK_CONFIG
-u CLOUDSDK_CORE_ACCOUNT BACKEND_UNIT_TEST_FILE_LIST=<selection>
BACKEND_UNIT_FILE_BUDGET_SECONDS=3600 bash backend/test.sh`:

- `test_record_seal_row_import_graph.py`: 4 passed
- `test_record_seal_cluster_repair_deploy.py`: 13 passed
- `test_record_seal_cluster_repair.py`: 136 passed
- `test_record_pending_repair.py`: 60 passed
- `test_record_seal_priority.py`: 13 passed
- Seven selector-owned Firestore guard files: 842 passed, 1 deselected

**Total: 1,068 passed, 1 deselected.** These are hermetic checks; no
live cluster
or full CUDA image build was exercised. The actual push passed the full
repository pre-push hook with no skip
switches: 47 shared preflight checks, whole-backend type checking (0
errors),
and the selected backend test files and formatting checks.

## Original lane verification

New `backend/tests/unit/test_record_seal_row_import_graph.py` (4 tests):

- imports `scripts.record_seal_repair_job` in a clean interpreter and
asserts
  `fastapi`, `pydantic` and `starlette` are absent from `sys.modules`;
- the same for `utils.batch_pipeline.record_seal_cluster_repair`;
- `metrics_response()` still returns a `starlette.responses` object with
the
  Prometheus content type and `omi_*` samples;
- `require_http_stage()` still raises `HTTPException` 503 on an unknown
stage.

New chart tests in
`backend/tests/unit/test_record_seal_cluster_repair_deploy.py`:

- the repair pod's `nodeAffinity` requires `batch-pipeline-pool` and its
  tolerations match that pool's taints;
- request == limit == 4 CPU, and no GPU in the limits;
- `PYTHONDONTWRITEBYTECODE` is absent from the CronJob env;
- `nodePool=` + `tolerations=[]` renders the old exclusion exactly.

Commands run through `bin/omi-heavy` (the host was at load 150-350 from
other
lanes, so every run waited for a slot). Each file below was run in its
own
pytest process, as the backend contract requires:

```
backend/.venv/bin/python -m pytest -q tests/unit/test_record_seal_row_import_graph.py
  4 passed
backend/.venv/bin/python -m pytest -q tests/unit/test_record_seal_cluster_repair_deploy.py
  13 passed
backend/.venv/bin/python -m pytest -q tests/unit/test_record_seal_cluster_repair.py
  136 passed
backend/.venv/bin/python -m pytest -q tests/unit/test_record_partial.py
  67 passed
backend/.venv/bin/python -m pytest -q tests/unit/test_sync_stage_isolation.py
  6 passed
backend/.venv/bin/python -m pytest -q tests/unit/test_omi_flags.py
  84 passed
backend/.venv/bin/python -m pytest -q tests/unit/test_external_list_cache.py
  38 passed
backend/.venv/bin/python -m pytest -q tests/unit/test_episodes_metrics_export.py
  2 passed
backend/.venv/bin/python -m pytest -q tests/unit/test_llm_gateway_routers_metrics.py
  4 passed
backend/.venv/bin/python -m pytest -q tests/unit/test_metrics_sidecar_server.py
  2 passed
backend/.venv/bin/python -m pytest -q tests/unit/test_metrics_cardinality_contract.py
  4 passed
```

A single combined run of the record-seal and metrics files (604 passed)
also
covered `test_record_seal_sweeper_deploy`,
`test_record_seal_worker_deploy`,
`test_record_seal_worker_guards`, `test_record_seal_rules`,
`test_record_seal_fast`, `test_record_seal_nojob`,
`test_record_seal_sweep_budget`, `test_record_seal_sweeper` and
`test_record_seal_worker`. That combined run reported two failures in
`test_sync_stage_isolation.py` from cross-file `caplog` contamination,
which is
exactly why the contract isolates files; the file passes 6/6 on its own
(above).

Static checks:

```
backend/.venv/bin/python scripts/scan_import_time_side_effects.py
  Checked 2530 backend production file(s); 0 violation(s).
backend/.venv/bin/python scripts/check_module_stub_pollution.py
  Checked 2919 backend test file(s); 0 violation(s).
make runtime-image-source-closure
  Runtime-image contracts passed for 19 registered images.
python3 .github/scripts/check_failure_class_guard_ratchet.py
  OK: every class at or above the threshold names a guard artifact.
scripts/failure-class validate --pr-body-file .agent-brief/pr-body.md
  ok: true
helm template ... -f prod_omi_batch-pipeline-worker_values.yaml
  renders; rollback render verified
```

Not run: a full `docker build` of `Dockerfile.batch-pipeline`
(torch/CUDA
wheels) and any live cluster apply. The `compileall` step is verified by
inspection and by the local `.pyc` measurement above, not by a built
image.

## Product invariants affected

- INV-DATA-1 — preserves the existing customer data-plane authority. The
selected source SHA and `vars.RUNTIME_GCP_PROJECT_ID` bind the read-only
index gate to the release’s existing Firestore authority; this is not a
customer data-plane migration.

Failure-Class: new

Line-Count-Exception: backend/utils/metrics.py | 1722 -> 1730 | Keep the
HTTP Response import at its sole call boundary with a TYPE_CHECKING
annotation; splitting the shared metrics registry is outside this
startup fix.

Line-Count-Exception:
backend/utils/batch_pipeline/record_seal_cluster_repair.py | 791 -> 887
| Keep the bounded priority query and its cursor checkpoints with the
existing coordinator; the follow-up adds no separate seal or mutation
authority.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/25049?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/25049?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25049&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. -->

## Pre-review dispositions

Consolidated fix batch after merging current `origin/main` (no rebase).

- **Production safety P1-1 — fixed:** the existing `gcp_diarizer.yml`
stages immutable Firestore gate controls and invokes the same readiness
action/inputs as `gcp_backend.yml`, unconditional with its sparse
control checkout, registered in `_LANE_SOURCE_BINDINGS`, and bound to
`${{ steps.vars.outputs.source_sha }}` before build, digest promotion or
Helm. No new workflow.
- **Production safety P1-2 / correctness P2-3 — fixed:** catch
`FailedPrecondition` around urgent discovery only, emit content-free
`index_unavailable` and shared degraded fallback telemetry, then run
ordinary and conversation discovery. Regression covers plan/apply and
the real CronJob entrypoint returning 0; provider exception contents
never enter events.
- **Correctness P2-1 / Luna malformed-prefix FIX-FIRST at earlier head
`7c214814` — fixed:** urgent discovery uses
`record_dead_letter_deadline_at > 0` and the existing final-day upper
bound. Every examined row advances the encrypted query position before
eligibility checks. The urgent codec accepts raw scalar scan positions
while ordinary enqueue cursors keep numeric validation, so malformed
metadata cannot create an unreadable frontier. Examined invalid
deadlines add to the existing content-free `invalid_clock_rows` metric
and are not selected for urgent processing. A persistent full malformed
prefix cannot pin valid jobs; the existing saturated-page regression is
retained and now checks readable advancing progress.
- **Production safety P2-7 / correctness P2-2 — fixed:** runbook names
the v2 conversation/recency cursors and v1 urgent cursor, newest-first
ordering, gate and degraded behavior.
- **Correctness P2-4 — fixed:** direction-aware conversation query fake
verifies descending finish/name ties, encrypted resume, frozen horizon
and wrap.
- **Production safety P2-1 / Luna FIX-FIRST at earlier head `0711777f` —
fixed:** ordinary discovery runs every enabled run within the shared
discovery budget. For allocation `A = max(1, workers // 2)`, reserve `R
= max(1, A // 4)` ordinary places; urgent discovery gets at most `A -
min(R, ordinary candidates)`. With 16 workers, ordinary retains 2 of 8
job places under sustained urgency; with no ordinary candidates, urgent
can use all 8. Unused urgent capacity returns to ordinary candidates.
Urgent attempts remain deadline-first. Held ordinary candidates stay
ahead of their encrypted checkpoint. The hard bound is one run between
ordinary scans, with no finite settlement-time guarantee. The change doc
and runbook now state the bound.
- **Production safety P2-2 — follow-up:** review urgent cursor
wrap/fairness for newly urgent work behind the frontier.
- **Production safety P2-3 — follow-up:** measure newest-first candidate
yield against the unchanged 30-minute minimum age and append-proof
refusals.
- **Production safety P2-4 — follow-up:** validate GPU-pool scheduling,
4-CPU reservation, autoscaler headroom and cost before deployment.
- **Production safety P2-5 — follow-up:** verify compiled
bytecode/readability in the built batch worker image; full CUDA image
build was not performed locally.
- **Production safety P2-6 — follow-up:** old v1 frontiers remain stale
on code rollback; clarify the urgent numeric payload naming in a later
cursor change.
- **Production safety P2-8 — follow-up:**
`typing.get_type_hints(metrics_response)` needs a runtime `Response`
resolution if a caller is introduced.

## CI regression dispositions after earlier head `783ec7ff`

The complete logs for [run
42879396660](https://github.com/BasedHardware/omi/actions/runs/42879396660)
reveal regressions triggered by this PR. The earlier classification as
unrelated was incorrect.

- **Workflow policy — fixed:** removed both unsupported service
predicates from `gcp_diarizer.yml`. The sparse immutable-controls
checkout and readiness gate are unconditional. Registered the workflow's
real `${{ steps.vars.outputs.source_sha }}` expression in
`_LANE_SOURCE_BINDINGS`. The existing policy and all its enforcement
remain intact. Baseline: 2 workflow tests failed; corrected suite: 98
passed.
- **Lazy HTTP import / shard 3 — fixed:** `require_http_stage()` imports
`HTTPException` only inside `except InvalidSyncStage`; valid stage
checks remain free of FastAPI. The import trace for the slow test was
`database.conversations` → `utils.other.storage` → `utils.cloud_tasks` →
FastAPI, during a test-body import. Removing earlier framework warming
exposed that call-phase cost. The test now loads the real visibility
dependency in module-fixture setup, as required by the CPU guard's
setup/call boundary. The 1.00-second limit and all rollback/visibility
assertions remain unchanged. Local call CPU: 0.575309 s before, 0.000652
s after (2026-11-10, m1; repo guard measurements). Fixture/setup still
pays the dependency import.
- **Multipart / shard 8 — fixed:** the isolated
`test_sync_transcription_prefs.py` fixture itself replaced
`python_multipart` with a plain `ModuleType`, hiding
`python_multipart.exceptions`. Removed that unnecessary package shadow
and retained the installed lightweight parser. Existing `stub_modules`
teardown continues to restore its other fakes. Baseline isolated run: 59
setup errors; corrected file: 59 passed. CI launches one Python process
per file, so another file's module state cannot leak into this failure.
`test_action_items_conversation_list_malformed.py` already removes its
conditional fallback stub in `finally` and skips installing it when the
real package is present.
- **Gacrux desktop — no voice defect found:** the old shard log's
adjacent `FAILED [87%]` belongs to concurrent workflow-contract output.
The voice file's own terminal summary is **119 passed**, with no
failed-file status. Both baseline and corrected isolated local runs also
pass all 119 tests, including Gacrux desktop; voice code is untouched.
- **Row import graph — preserved:** 5 subprocess contracts pass,
including the new valid-stage path assertion that
FastAPI/Pydantic/Starlette stay absent and the existing invalid-stage
HTTP 503 behavior.

Local reproduction on the merged tree (2026-11-10, m1):

- Focused regression selection: **344 passed** across workflow
contracts, merge jobs, sync preferences, voices, row import graph, stage
isolation, deploy and priority tests, via `backend/test.sh`.
- Original shard 3: 345 original CI files, all passed locally (exit 0).
- Original shard 8: 345 original CI files, all passed locally (exit 0).
- Both original shard file sets contain 345 files, exactly matching the
complete old CI logs. Launch order is reconstructed with the unchanged
runner's LPT weights and shard-1 typecheck reservation over the original
2,741-file selection (including workflow-contract extras). Both use
`BACKEND_PYTEST_WORKERS=4`, file isolation, 0.1-second warning /
1.0-second failure CPU guards and
`BACKEND_UNIT_FILE_BUDGET_SECONDS=3600` through `backend/test.sh`, with
the three ambient GCP credential variables unset. No policy, budget,
allowlist or hook bypass.

The former prod P2 follow-ups above remain as listed. No deployment or
PR merge. CI correction at earlier head
`0711777f1cbc2fc2c92eb833497a8a94b6affb4f`.

Full local shard evidence recorded 2026-11-10T19:28:30+00:00 in
`backend/docs/listen_pusher_pipeline/changes/2026-11-10-record-seal-priority.md`,
including manifest hashes and the exact runner settings.


Full push-hook receipt (2026-11-10T19:37:43+00:00): **passed** at
earlier head `0711777f1cbc2fc2c92eb833497a8a94b6affb4f`. All 56 selected
preflight checks and the bounded unit selection passed with the required
credential-unset/body-file/3600-second recipe. GitHub received one
update from earlier head `783ec7ff49` to that earlier head; no
force-push or hook bypass. The `sealfix2` worktree was removed via lane
finish. [Backend Unit Tests run
42886859875](https://github.com/BasedHardware/omi/actions/runs/42886859875)
owns that earlier head's CI result.


## Luna FIX-FIRST: ordinary-job reserve

The urgent leg previously filled the entire job allocation before
ordinary discovery was considered. A sustained urgent backlog could
suppress the ordinary query forever. Ordinary discovery now runs first
with one bounded page, urgent discovery is capped by the ordinary
reserve, and attempt order remains urgent deadline-first, then ordinary,
then conversations. Both legs retain their existing encrypted frontiers
and combined worker reservation; held ordinary candidates cannot be
checkpointed past. No extra query or scan budget is added.

Regression coverage uses real bounded job queries and encrypted cursors
at 2, 4 and 16 workers: repeated runs under sustained urgency retain the
ordinary reserve, an empty ordinary pass allows full urgent capacity,
and a partially used ordinary reserve returns unused places to urgency.
The one-place allocation edge, pre-attempt checkpoints, urgent index
degradation and conversation capacity are covered. L1 #25018 was open at
the main merge; no L1 conflict was present.

Local reserve verification (2026-11-10T20:21:16+00:00, m1): all 15
record-seal unit files through `backend/test.sh` under `omi-heavy`:
**436 passed, 3 skipped** (Firestore emulator unavailable), including 35
priority, 136 coordinator and 5 import-graph tests. Credential variables
unset; file isolation, four file workers, 3600-second file budget and
unchanged 0.1/1.0-second CPU guards. Main merged through
`85de1985f0fb4fddd05e0de4b36c1ac68108d81e`, without rebasing. `git diff
--check` and required invariant metadata validation pass.

Ordinary-reserve fix at earlier head
`d991957cab4ed220198e859660af33dec156510a`.

Full push-hook receipt (2026-11-10T20:25:33+00:00): **passed** at
earlier head `d991957cab4ed220198e859660af33dec156510a`. All **56
selected preflight checks** and the bounded unit selection passed with
the credential-unset/body-file/3600-second recipe. Exactly one non-force
push updated earlier head `0711777f1c` to that earlier head; no hook
bypass. [Backend Unit Tests run
42895041539](https://github.com/BasedHardware/omi/actions/runs/42895041539)
owns that earlier head's CI result.


## Sibling merge refresh after #25020 and #25063

Earlier head `7c214814536c30c5fb6b9d3f97ab5453571933a4` merged main;
main parent: `75dc53a81df78643cf74c7638350fecc9082ebfc`. Fetched and
merged main with `git merge --no-ff origin/main`, without rebasing or
new feature scope, under lead2 ruling `1c606e`.

The only textual conflict was `config/feature-flags.yaml`: retained this
PR's current `RECORD_SEAL_REPAIR_AGE_ORDER` declaration and main's new
`PIPELINE_LEDGER` declaration. Main's `NO_SPEECH_TERMINAL_ENABLED` entry
also remains. The index sources merged automatically, retaining #25063's
`record_no_speech_newest` and all five seal-repair indexes (prod/dev
newest, prod/dev deadline, newest completed conversation).

Regenerated `firestore.indexes.json` with `backend/.venv/bin/python
backend/scripts/generate_firestore_indexes.py --write` and
`backend/docs/feature-flag-registry.md` with `backend/.venv/bin/python
scripts/render_feature_flag_registry.py`. Neither generated output was
hand-merged. Semantic verification confirms every composite and field
override from both parents remains in the manifest, all six required
declarations are generated, and both parent flag registries are
preserved with the current seal-order description taking precedence over
main's older text. The Firestore generator's check mode also passes.

Verification recorded 2026-11-10T23:22:56+00:00 on m1: **1470 passed, 3
skipped, 1 deselected** across 28 files through `backend/test.sh` under
`omi-heavy`. Includes all 15 record-seal files (including import graph),
Firestore index tests and the canonical seven query guards, plus
`test_flag_budget.py` (24 passed). Emulator tests skip without an
emulator; the standard runner deselects the slow-marked case. Credential
variables unset, file isolation, four file workers, unchanged CPU guards
and 3600-second file budget. `git diff --check` passes.

`MERGE-OK 0175e5` applied to earlier head `d991957c`; it is not carried
forward as approval for any later head. The merge desk re-verifies at
the current PR head. PR remains unmerged.

Sibling merge push receipt (2026-11-10T23:26:21+00:00): **passed** at
earlier head `7c214814536c30c5fb6b9d3f97ab5453571933a4`. All **56
selected preflight checks** and the bounded unit selection passed with
the required credential-unset/body-file/3600-second recipe. Exactly one
non-force push updated earlier head `d991957cab` to that earlier head,
with no hook bypass. [Backend Unit Tests run
42923202562](https://github.com/BasedHardware/omi/actions/runs/42923202562)
owns that earlier head's unit CI result.

Firestore CI queue observed 2026-11-10T23:36:37+00:00: earlier head
`7c214814`'s [index workflow
42923203481](https://github.com/BasedHardware/omi/actions/runs/42923203481)
was pending behind the shared `firestore-schema-prod` concurrency lock
held by [main reconciliation
42920647780](https://github.com/BasedHardware/omi/actions/runs/42920647780)
from #25063. The main run was executing, with no pending environment
approval at that observation. These owning run links carry the current
state; no index apply, cancellation, approval or lock change was
performed as part of this conflict refresh.




## Luna FIX-FIRST: persistent malformed urgent prefix

Disposition: fixed. The urgent query now has a positive lower bound and
its existing final-day upper bound on the same deadline field; the
current `(state ASC, record_dead_letter_deadline_at ASC, __name__ ASC)`
index serves this range without a new declaration. Cursor advancement
happens for every examined row before local eligibility validation. Raw
scalar urgent scan positions round-trip through the encrypted
maintenance codec; ordinary enqueue cursor validation is unchanged.
Examined invalid deadlines contribute to the existing
`invalid_clock_rows` summary, without identifiers or payloads and
without urgent processing. Query-excluded rows are not enumerated or
counted.

The persistent-prefix regression leaves 128 malformed rows in place and
proves the real query floor discovers valid urgent jobs in one run. A
separate adversarial projected-page case bypasses the floor and proves
encrypted cursor advancement discovers valid urgent jobs in two runs
while counting all 128 examined malformed rows. The earlier
saturated-page test remains, including null, boolean, string,
non-positive and non-finite cases; it now asserts a readable advancing
cursor. Coordinator coverage verifies discovery invalid-clock counts are
combined with the existing aggregate. No worker, scan, query-count or
proof budgets change.

Fetched main before work; main remains the already merged parent, so no
additional main merge or rebase was needed. Prior approvals apply to
their earlier heads; the merge desk must re-verify the new published
head.

Local malformed-prefix verification (2026-11-11T00:26:25+00:00, m1):
**1,310 passed, 3 skipped, 1 deselected** through the repo runner across
23 files. Includes all 15 record-seal files, the canonical seven
Firestore guards and `test_flag_budget.py`; all 39 priority cases and
all five row-import contracts pass. The earlier ordinary-reserve batch's
priority-file subtotal is corrected from 38 to 35; its recorded total
remains 436. The Firestore generator check passes with no new registry
or manifest change. Credential variables unset, file isolation, four
file workers, unchanged CPU guard and 3600-second per-file budget.

Current head: `e47911c994d6fb0fd7b30ec5cb45da1b8761dff1`. All historical
receipts above refer to earlier heads.

Malformed-prefix push receipt (2026-11-11T00:31:41+00:00): **passed** at
current head `e47911c994d6fb0fd7b30ec5cb45da1b8761dff1`. All **56
selected preflight checks** and the bounded unit selection passed with
the required credential-unset/body-file/3600-second recipe. Exactly one
non-force push updated earlier head `7c21481453` to the current head,
with no hook bypass. [Backend Unit Tests run
42931834561](https://github.com/BasedHardware/omi/actions/runs/42931834561)
owns the current head's unit CI result.

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

ℹ️ 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 +308 to +311
if reactivated:
revision = int(row.get('record_upload_revision') or 0) + 1
patch['record_upload_revision'] = revision
if source == 'frames' and serving and changed:

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 Keep shadow frame renewals from invalidating partial barriers

In shadow mode or outside the serve cohort, a frame renewal on a partial recording still sets reactivated and increments record_upload_revision, but the serving-only branch below skips updating the partial marker. After the producer drains and clears its token, record_audio_partial.upload_revision therefore remains stale, so require_record_audio_barrier() rejects the existing continuation until a separate repair refreshes it. This makes the observational rollout interrupt real partial processing. Gate revision-changing reactivation on serving eligibility while allowing shadow renewals to update diagnostic lease clocks.

Useful? React with 👍 / 👎.

Comment on lines +123 to +124
# A custody uploader can outlive its pusher. Actual server
# signals re-fence an abandoned/gone identity. A computed stock

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 Honor newer abandonment evidence before vetoing lease release

For a serve-cohort frame token abandoned after its latest heartbeat, this unconditional live-lease veto prevents the later abandonment check from running. abandon_record_upload_session() explicitly attests that the producer stopped after settling executor I/O, so this is fresh stoppage evidence, not the stale evidence that renewal should supersede. A heartbeat followed by abandonment currently returns False from producer_tokens_dead() until lease expiry, delaying otherwise eligible full or partial repair by up to an hour with the default lease. Preserve the veto for stale proofs, but allow a valid abandonment at or after the last signal to release the frame token.

Useful? React with 👍 / 👎.

Comment on lines +134 to +137
RECORD_TOKEN_LEASE_MODE: ${{ inputs.record_token_lease_mode }}
RECORD_TOKEN_LEASE_MODE_SERVE_PERCENT: ${{ inputs.record_token_lease_mode_serve_percent }}
RECORD_TOKEN_LEASE_SECONDS: ${{ inputs.record_token_lease_seconds }}
RECORD_TOKEN_LEASE_DEPLOYED_AT: ${{ inputs.record_token_lease_deployed_at }}

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 Pass the lease rollout settings through both stack-deploy callers

When the repository variables enable shadow or serve, the manual and automatic stack deployments still bind off, 0, 3600, and 0 here: neither .github/workflows/gcp_backend.yml nor .github/workflows/gcp_backend_auto_dev.yml supplies any of the new action inputs. Unlike the updated pusher and listen workflows, these callers therefore ignore the configured rollout. The action persists those defaults through GITHUB_ENV into the Cloud Run renderer and, on full deployments, the shared backend ConfigMap, silently disabling the rollout and leaving it inconsistent with separately configured repair workers. Wire all four rollout variables into both callers.

Useful? React with 👍 / 👎.

Git-on-my-level added a commit that referenced this pull request Nov 11, 2026
…25079)

Current head `e339859141015a9ab6ba247529eef7d678dbd4fd`: a merge of
`main` (including #25083) into the earlier head
`3521802cb0e40e12e05232c9676c8355423c92eb`; the reviewed code is
unchanged. CI at the current head: 37 passed, 21 skipped, 0 failed
(shard 8 passed on rerun attempt 2).

Restore Firestore tier-counter export on Cloud Run sync and attach
bounded service identity to GKE read metrics. The measured QUERY
coverage residual remains unresolved.

Head: `lane/fsattrib` (`3521802cb0e40e12e05232c9676c8355423c92eb`).

Failure-Class: FC-metric-dropped-by-scrape-allowlist

Product invariants affected: none (telemetry only).

Root causes and investigation:

- (a) QUERY undercount remains unresolved.
`backend/database/firestore_document_probe.py:878` wraps the SDK stream
and `:890` records each consumed snapshot once. Real SDK conversion
tests cover stream/get, transaction.get(query), collection
streams/groups, limit, limit_to_last, offset, async queries and batched
gets with duplicate requested references. They pass against the main SDK
and the batch-worker-pinned SDK. Class installation covers raw clients
created later in an instrumented process (`:1115`,
`backend/database/_client.py:104`); caller overflow folds labels rather
than dropping amounts. Projections are counted, no product caller uses
list_documents, and SDK get_all uses one batch RPC. The strongest
remaining hypothesis is early termination / partial stream consumption:
the server can bill results never consumed by the SDK caller. Concrete
early breaks include `backend/database/client_telemetry.py:66` and
`backend/database/conversations.py:3340`. This is a coverage boundary,
not a proven explanation of the fleet gap. The partial-stream test
preserves laziness; no streams are drained. Aggregation index-entry
costs remain estimates, and processes that never install the probe plus
non-Python readers remain separate boundaries. No Explain RPC or
read-behavior change.
- (b) `_record()` increments tier and caller counters by the same amount
(`backend/database/firestore_document_probe.py:600`, `:608`). Tier
resolution catches errors and falls back to bounded `unattributed`
(`backend/database/firestore_tier_context.py:127`). The confirmed loss
is downstream: the sync keep regex at
`backend/deploy/cloud_run_gmp_sync.yaml:53` previously retained only
caller/origin variants and dropped `omi_firestore_billed_reads_total`.
Keep the base and both attribution variants. Also retain
`omi_read_cache_shadow_total`: usage_month shadow samples execute on
backend-sync/backend-integration. Raise the sync sample cap to 15000,
matching the sidecar profile and its whole-scrape-drop rationale; the
extra tier family needs headroom. Tests pin both caps and pass real
exposition through both keep regexes, including shadow samples and
missing/invalid tiers.
- (c) `DD_SERVICE` names the JSON ledger
(`backend/database/firestore_document_probe.py:185`), not Prometheus
samples. Static service_name pod labels and GMP PodMonitoring
targetLabels.fromPod now cover backend-listen, pusher,
batch-pipeline-worker and record-seal-worker; existing in-cluster
Prometheus jobs copy the same label. Dev/prod values retain their
existing pattern. The sync-backfill-worker pilot also carries the label
and GMP mapping for when it deploys (its chart has shared values, no
stage overlays). The production seal worker is intentionally idle
(`backend/charts/batch-pipeline-worker/prod_omi_batch-pipeline-worker_values.yaml:136`);
its reader is constructed only when enabled
(`backend/utils/batch_pipeline/record_seal_worker.py:228`). Both probe
collectors are already registered in the private registry (`:25`). This
explains absent lazy read series for the checked-in configuration; no
serving deployment was inspected.

Review fixes and operational implications:

- Keep the seal-repair and seal-sweeper CronJob pod service_name labels
**for logs only**. These pods are not scraped and gain no metric export
from this change. Alloy retains service_name
(`backend/charts/monitoring/alloy/prod_omi_k8s_monitoring_values.yml:29`).
- Guard optional batch-pipeline-worker podLabels with Helm `with`;
renders accept null and empty-map overrides. Wire the attribution chart
tests into the monitoring area of select_backend_unit_tests.py, with
regression coverage, and skip Helm-dependent tests when
shutil.which('helm') is absent.
- Known conflict with open #25018: both edit the sync keep-regex line
and the batch-pipeline-worker base-values anchor after enabled.
Whichever lands second must resolve/rebase while retaining **both** the
Firestore `firestore_billed_reads(_by_(caller|origin))?_total`
alternation and #25018's
`record_token_late_append_total|record_token_lease_.*`, as well as
`read_cache_shadow_total`. This branch is not rebased onto unmerged
#25018.
- Dashboard legend change: the existing label_replace expressions at
`backend/charts/monitoring/dashboards/general/omi-core-features.json:2573`
and `backend/charts/monitoring/gmp-query-migration-inventory.json:2677`
synthesize in-cluster only for an empty service_name. Once labels
arrive, those legends become backend-listen / pusher. GKE read series
are backend-listen / pusher / batch-pipeline-worker (and
record-seal-worker when active), **not backend**; service_name="backend"
selectors continue to cover only the Cloud Run service.
- The batch-pipeline-worker Deployment uses Recreate. Changing its pod
labels restarts all its pods together at the next chart rollout;
**cl2-deploy should schedule it**. This PR does not deploy anything.

Expected effect: restore tier/caller export parity, expose existing sync
cache-shadow samples and name GKE read series. No numerical reduction in
the native-minus-by_caller unattributed share is claimed: QUERY coverage
remains unresolved. No reads are added, removed or drained. Metric
names, bounded tiers and caller limits remain; no uid label, runtime
flag, credentials, .github change or deployment.

Validation through omi-heavy, offline (each file in its own pytest
process):

- `cd backend && .venv/bin/python -m pytest <file> -q`:
test_firestore_attribution_export.py **42 passed**,
test_firestore_attribution_charts.py **11 passed**,
test_backend_unit_selector_output.py **4 passed**,
test_batch_pipeline_chart.py **101 passed**, test_sync_worker_runtime.py
**13 passed** — **171 passed** total.
- With `PATH=/usr/bin:/bin`, the attribution chart suite reports **2
passed, 9 skipped**, exercising the missing-Helm guard.
- Prior probe/worker/repair-focused validation passed **467 tests**; the
probe plus SDK/export suites also passed **169 tests** against the batch
worker's pinned SDK. No dependencies changed.

`make preflight` and `scripts/pr-preflight --pr-body-file
/tmp/firestore-lead-m1/fsattrib-pr-body.md`: **48 checks passed each**
on this head. The single prescribed push passed its bounded gate: **171
tests** across all five changed test files, backend typecheck (**0
errors**, existing warnings), formatting and the shared PR contracts
(**48 passed**). Current-head CI finished: all other applicable checks
passed, including seven unit shards, slow guardrails, both gauntlets,
hermetic backend E2E, static contracts, formatting, hygiene and
metadata. The only red checks are [unit shard
5](https://github.com/BasedHardware/omi/actions/runs/42939082926/job/130256298497)
and its dependent [unit-suite
aggregate](https://github.com/BasedHardware/omi/actions/runs/42939082926/job/130260735732).
The shard log confirms the known
`tests/unit/test_messaging_review_fixes.py:34` race:
`test_optional_load_failure_returns_plain_window[failure2]` expects one
fallback notice and receives two. #25083 has now merged separately; this
branch does not contain that fix. No retry, unrelated messaging edit,
history rewrite or second push was made. The complete PR changes **102
lines outside tests**, below the 400-line cap. The known shard-5
messaging race is fixed separately by #25083; no unrelated messaging
changes are included here. Rollback: revert this PR's commits to restore
the prior scrape and pod-label configuration.

<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/25079?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/25079?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25079&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. -->

🤖 Generated with [Claude Code](https://claude.com/claude-code)
@Git-on-my-level
Git-on-my-level merged commit 8659de6 into main Nov 11, 2026
73 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/tokenlease branch November 11, 2026 07:47
Git-on-my-level added a commit that referenced this pull request Nov 11, 2026
…25055) (#25070)

## What changed and why

Head: `672d873b5aa2322b1e47a112e5e57fe412e5d1e4`

Replacement for #25055 (which replaced #25028) on current `origin/main`
`7ebd8450b6e023474cfe3275cf3446b28f3a710f`, carrying the reviewed
attention-expiry patch plus the independent-review FIX-FIRST corrections
at `Earlier head:` `e1c309b3e047cbfb15933fb0d2246af8829cd459`.

Supersedes #25055 because that PR is at its two-push limit and its exact
head carries two independent-review FIX-FIRST findings. This replacement
starts a fresh branch from current main, carries the same reviewed
commits, and fixes both findings:

- **Scan bound (finding `77a43d`).** `list_items` no longer streams a
user's whole active attention collection. Each query is bounded to
`SCAN_LIMIT = 500` documents, and an optional `start_after` cursor lets
a caller start from a known document. Expiry transactions therefore run
only inside a bounded scan.
- **Zero limit (finding `34c935`).** `list_items(limit=0)` (and any
non-positive limit) returns an empty list before iterating or appending,
instead of returning one item.
- **Scan cursor (finding `3d2d9d`).** A full read now pages internally
on the last **scanned** document, not the last returned one, so
filtering (resolved or expired rows) cannot repeat a window or omit
later items. The 500-row query bound and the non-positive-limit early
return are unchanged.

Carried non-merge commits from the reviewed head:

- `329a8b8fa5d` — expiry predicate and initial tests.
- `3e0e6f98de1` — transaction fencing, tests, config, registry and
documentation.
- `7d75d6a5980` — pusher literal config snapshot.

The carried patch is otherwise behavior-identical: attention expiry,
banked/completed/live-debt guards, and the flag registry. No new product
behavior beyond the two fixes. No `.github/`, UI, credentials/IAM,
production data/config, or model changes.

### Test-only follow-up (push 3)

`1252bca525de` is a test-only assertion under the driver's third-push
allowance. The 620-item pagination regression previously ended its first
500-row page on an item that was returned, so a cursor based on the last
*returned* item would have passed it too. The test now resolves the last
document of the first page and asserts the second page's `start_after`
is that document, protecting the last-scanned cursor in
`processing_attention._scan_pages`. No product code changed.

### Firestore client seam (Codex P1 `4529060103`, lead2 `f66b9e`)

`672d873b5aa2` fixes the review finding that the new expiry path used
the legacy module-level `db` proxy, contrary to `backend/AGENTS.md`.
`items_ref`, `_scan_pages`, and `list_items` now resolve
`get_firestore_client()` at call time and expose an optional
keyword-only `firestore_client` parameter; the bounded scan, the
conversation/claim reads, and the expiry transaction use that single
resolved client. The new expiry tests inject `firestore_client` instead
of monkeypatching `store.db` (the module fixture now supplies the same
fake client through `get_firestore_client` so the unconverted
claim/finish helpers and HTTP route keep working). `db` remains only in
the unconverted claim/finish helpers and `pending_conversations`.
Pagination, cursor, and expiry-predicate behavior are unchanged; the
delta is 15 non-test changed lines in one file plus the test seam.
Merge-main resolutions under `1c606e` are unchanged from
`71aff3e888f4e`.

### Merge-main resolutions (lead2 `1c606e`)

This head is a merge-main resolution under lead2 `1c606e`.

`71aff3e888f4e` merges current `origin/main` (`a73632ce0ec9`, which
carries C2's operator-ledger census read from #25084) into the branch.
Six files conflicted, all additive on both sides and resolved by keeping
both: `config/feature-flags.yaml`,
`backend/tests/unit/test_verify_pusher_config_references.py`, and all
four `backend/charts` listen/pusher values (this PR's
`PROCESSING_ATTENTION_NON_RETRYABLE_EXPIRY_ENABLED` and main's
`SYNC_RECORD_COVERAGE_WAIT_MEMO`), plus
`backend/config/flag_budget.json`, where `count` is reconciled to
**271**, equal to the 271 names on the merged head.
`backend/tests/support/firestore_query_driver_registry.py` auto-merged
and was then checked against both parents: this PR's attention cursor
entries (`list_items` with `start_after`, `_scan_pages` covered-by) and
C2's census entries (`pipeline_ledger.iter_global_window`,
`pipeline_ledger.retention_start`,
`pipeline_ledger_census._capture_creates`,
`pipeline_ledger_census.census`) are both preserved, and the delta
against `origin/main` is exactly this PR's patch (19 files). No product
behavior changed; the reviewed patch is unchanged.

`Earlier head:` `5ad54d2f0d8f2` merged `origin/main` (`8fa2cbd36487b`,
the main-wide notes prompt-pin fix from #25108); that merge was clean
and `flag_budget.count` was 270 there.

`Earlier head:` `bf6efab1c7bf6` merged `origin/main` (`8659de6ee98d9`,
which carries the main-wide messaging flake fix from #25018) into the
branch, so the previously red messaging check ran against the fix. Five
files conflicted: `config/feature-flags.yaml` and both
`backend/charts/backend-listen` listen values (additive env/flag entries
on each side, kept both), `backend/config/flag_budget.json` (`count`
reconciled to 270, equal to the 270 names on the merged head), and
`backend/docs/pending-work.md` (narrative paragraphs from both sides
merged, keeping the `HOME_STEP_PROJECTION` text and the
bounded-attention text). No product behavior changed; the reviewed patch
is unchanged.

`Earlier head:` `047de1b18fb7` merged the prior `origin/main`
(`75dc53a81df7`) under the same ruling; its only conflict was
`config/feature-flags.yaml`.

## Product invariants affected

- INV-MEM-4: the runtime change only adds attention expiry
configuration; canonical memory consolidation and promotion authority
retain their existing configuration. Attention expiry is distinct from
Short-term memory disposition.

## Tuning and rollback

- `PROCESSING_ATTENTION_NON_RETRYABLE_EXPIRY_ENABLED`: default on.
Setting the declared value to `false` and recomposing runtime
configuration disables new expiry writes. All backend services and
matching listen/pusher charts carry the binding.
- `NON_RETRYABLE_ITEM_TTL`: seven days from `created_at`, exclusively
for `recovery_structure_unavailable` after retry reconciliation.
- `SCAN_LIMIT`: 500 active attention documents examined per query; a
full read pages internally on the last scanned document.
- Bundle kill switch: `HOME_STEP_PROJECTION` (existing, default on).
Turning it off is the L4 rollback.
- Rollback is the flag off; no data migration. Expiry is terminal:
already-expired documents remain inactive after disabling the switch,
and no automatic data restoration is claimed.
- L4 success metric: **no processing rows on past days**.

## Verification

Fresh checks of head `672d873b5aa2` on m5 through
`/Users/dazheng/workspace/omi/bin/omi-heavy run -- ...`, with GCP
credential environment variables unset and worktree-local Python 3.11
dependencies:

- Attention/pending-work set (13 files, including
`test_batch_pipeline_scheduler.py`): **360 passed** across the 13 files
run; `test_pending_work.py` alone: **76 passed**, including the
strengthened 620-item pagination regression and all expiry tests, now
with `firestore_client` injection.
- Full query-shape battery `test_firestore_query_shapes.py` (now
covering both driver sets): **572 passed**.
- Flag budget: **24 passed** (`flag_budget.count` 271 equals the 271
names on the merged head). `test_verify_pusher_config_references.py`:
**31 passed**. Runtime-env validator: **206 passed**. Notes
prompt-version node `test_llm_input_prompt_version.py`: **6 passed**
(including `test_prompt_sources_match_the_pinned_digest[notes]`).
Combined five-file run: **839 passed**.
- Normal full pre-push hook: **PASS**, 0 failures.
- The new cursor assertion was confirmed load-bearing: mutating
`_scan_pages` to advance on the second-to-last page item fails it with
`[None, 'item-0498'] != [None, 'item-0499']`.

Evidence is hermetic; real Firestore contention/SDK retries and deployed
behavior are not claimed.

## UI evidence

UI-Evidence: none -- backend-only expiry on existing API reads; no
client or UI change.

## Failure class

Failure-Class: FC-stale-selection-used-as-write-authority
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