Repository navigation
perf(memory): reuse atomically versioned released query projections - #23402
Conversation
Maintain owner change tokens in the same Firestore commit as canonical, historical and suppression mutations, including deletes. Reuse exact raw query snapshots at internal readers while retaining policy and lineage checks, existing levers, and fleet-coverage gates.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Git-on-my-level
left a comment
There was a problem hiding this comment.
SHIP — Sol / P88, round 1, exact head c41357eb71d171e48bfd74f6419004de4beb97fe.
No P0/P1 findings. Raw snapshots are keyed by exact query/database/client/owner/coverage epoch and a fresh atomic change head; policy, lineage, suppression, device visibility and decryption remain in the original callers. Failed commits cannot advance the head; non-atomic bulk writes block reuse before their source RPC. Account erasure explicitly removes the recreated head after source deletion, including a missing parent.
Reviewed source and the 100→2 counted-read proof; sync/async commit/delete/retry and bulk-barrier contracts; device-policy rerun on warm canonical pages; deletion/fill races; bounded retention; query/field-mask/epoch identity; source-error and partial-prefix budget behavior. No local test rerun in this review.
Fleet writer coverage and epoch activation remain lead-owned gates. MCP card reuse additionally requires P1's writer/epoch contract. The 50M/day target is conditional; added head reads/writes and process-local hit share must be included before claiming savings.
Code-review verdict only; exact-head CI and lead-owned merge/deploy gates remain separate. No merge performed.
Git-on-my-level
left a comment
There was a problem hiding this comment.
SHIP — Sol/P88 round 2, delta only from c41357e to bf6f72c. No P0/P1 findings in the two-file delta. The last-document bypass preserves the existing MCP partial source prefix on cold and warm paths instead of spending it on an incomplete version-head pair; corresponding regression tests cover both states. Moving DocumentSnapshot to the hydration function preserves behavior while avoiding import-time SDK stub breakage. No changes to authority, invalidation or deletion fences. Reviewed source/test source; no own test rerun, CI/rollout/savings claim or merge.
…23440) Main's backend typecheck has failed since #23408 (1c64780): seven `reportUnnecessaryIsInstance` errors (edit_tools.py 47/99/127/160, turn_refs.py 20/32/52) stop every unit shard before tests run, which blocks CI on all backend PRs (e.g. #23402, run 39993556902). Fix: keep #23408's runtime guards exactly. Widen the `configurable` parameter of the three turn_refs helpers to `Any`, and route edit_tools' four call sites through `_configurable(config: Any)`. No behavior change. Verification (m1, omi-heavy, nice 19): - `backend/scripts/typecheck.sh` (pyright 1.1.403): **0 errors** - `pytest tests/unit/test_chat_edit_tools.py`: 23 passed Failure-Class: none 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/23440?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/23440?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F23440&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. -->
Import-isolated archive consumers evict the projection and origin modules while Prometheus retains their collectors. Reuse the registered counters and prove collector identity and accumulated counts survive re-imports. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep P1 SDK list projections and P2 atomic memory change heads installed, retain both late-head erasure cleanups and flag contracts, and verify mixed sync/async source batches preserve atomicity and public result counts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Retain P2 projection flags alongside fs-p5's operation snapshot kill switch. Both lanes share the identical production origin-counter reimport repair. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6ac131f9f5
ℹ️ 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".
| def sync_commit(client: Any, request: Any = None, **kwargs: Any) -> Any: | ||
| prepared, count = prepare(request, kwargs) | ||
| return response(original(client, request=prepared, **kwargs), count) |
There was a problem hiding this comment.
Version the head by successful commit rather than request UUID
With projection reuse enabled, a retried nontransactional commit can restore an earlier token and make stale cached rows authoritative again. The UUID is generated once before calling the GAPIC method, but the pinned SDK retries Commit on ServiceUnavailable using the same request. For example, commit A succeeds but loses its response; a reader caches the page under A's token; commit B deletes a different memory; then A's transport retry succeeds and restores A's token without undoing B's deletion. Both reader head checks now match the cached token, so the deleted row can reappear until cache expiry. Use a server-assigned commit revision, such as the head snapshot's update_time, in the cache identity so each successful application invalidates previous projections, and cover an ambiguous-success retry interleaved with another document's mutation.
Useful? React with 👍 / 👎.
Include #23402 released memory projections and retain its declarations beside the monthly epoch and sync snapshot contracts. Regenerate the registry at its existing date. The reviewed non-fatal usage publication fix is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
## What changed and why Monthly allowance refreshes repeatedly scan `hourly_usage` (caller #6, about 42M reads/day in the sprint's latest-hour snapshot). Maintain five monthly counters and daily subtotals in the same transaction as hourly usage and its existing once/partial receipt. Warm full-month and since-day lookups read one document. Absolute history overwrite, admin reset and historical deletion atomically invalidate the total; first use rebuilds from hourly source rows. Legacy anomalies retain the existing query. Every new aggregate creator binds erasure authority to publication: ordinary, once-key, absolute, admin and migration writers use the existing `external_write_fence` and require a user root inside their transaction. Authority reads precede all receipt/source/total writes. Rejected publication leaves receipts untouched. Existing batch projection completion/partial transactions reuse their deletion/root/privacy checks. Lead approved this strengthening in ANX `event:ev_5e7c48e900024551f307ab9c3e254fd7`. Usage publication refusals are non-fatal to user-facing pipelines. The shared `utils.analytics.record_usage` composition boundary catches the refusal outside the transaction: conversation/transcript/audio processing completes while hourly/monthly counters and the once receipt remain uncommitted. A typed missing-root refusal is distinct from a deletion/destructive-operation refusal in `omi_fallback_total` and matching fixed-field logs (`component=usage_publication`, `from_mode=publish`, `to_mode=skip`, `outcome=degraded`, reason `usage_root_missing` or `usage_fence_blocked`); no UID, content or exception text enters labels/logs. All user-facing source writes use this helper. Direct admin/migration operations keep their refusal semantics. Cold reader rebuild already returns to the hourly query on root absence; no other production user path gains a root dependency in this PR. Hermetic regressions cover a root absent before sync admission, root removal immediately before publication, pending/completed deletion and ordinary live-account once replay. They require completed sync, the persisted conversation/transcript, no aggregate/usage receipt on refusal and an incremented bounded counter. Deletion still returns 403 for HTTP polling. The Firestore fake now preserves subcollections during root deletion, matching Firestore; a harness self-test checks repeated deletion without recreating the root. ## Rollout and rollback Writer maintenance ships ON. Reader `usage_month_total` remains 0 because mixed-version writers can undercount paid/Free allowance. Lead owns merge, deploy and ramp. Target writer train: **2026-10-24 08:00Z**, cutoff **07:30Z**. Deploy every writer (listen → pusher → Cloud Run → desktop-backend, plus operator/migration tooling); verify actual serving identities/traffic and drain old jobs. Choose a common `FSR_USAGE_MONTH_TOTAL_EPOCH`, then 5% for two hours with zero synthetic parity mismatches, no p95/5xx regression and no contention errors. Lead/reads loop expands to 100%. The original 08:00Z full-ramp deadline conflicts with an 08:00Z writer train plus the required hold. **Proposed replacement: 2026-10-24 12:00Z, pending lead acceptance.** Report any writer/parity blocker. Details: `backend/docs/monthly-usage-totals.md`. Kill switch: `usage_month_total:0`, preserving other levers. Writers continue maintenance. After rollback to any old writer, change the epoch on all readers before re-enabling. Epoch wiring uses existing manifests/renderers; no new workflow. ## Attribution and net economics Origins: `job:usage_month_total_read`, `job:usage_month_total_rebuild`, `job:usage_month_total_fallback`. Grade all three alongside original monthly and writer caller origins. **Up to 40M/day gross reader reduction is modeled, not measured.** Previously unfenced writer/replay attempts now add **three point reads** (deletion marker, destructive gate, root) per commit attempt. If their daily count is W, subtract 3W plus cold-seed scans/point reads and fallbacks from gross reduction; account separately for one added total write per accounting commit. Retries and existing outer fences may add further reads. Example: W=1M/day implies at most 37M/day before those other costs. W and realized net saving remain unmeasured. Funded `read_month` and plan/shadow readers retain their existing paths. ## Product invariants affected INV-MEM-4: `backend/deploy/runtime_env.yaml` wires the epoch; canonical memory intake/promotion keeps its authority. Existing deletion fences are strengthened by transaction-bound reuse under the lead's explicit ruling. Free-plan allowance policy, authorization, transcripts and speaker labels retain their behavior. ## Validation - Latest integration head **`9efacbc5723b866a598c061986d8718d960071d6`** includes main **`0d302a99fe`** (#23402) and **`251892e223`** (#23393). Only adjacent feature declarations conflicted. All monthly/snapshot/released-memory declarations and query proof registry entries are preserved; the feature registry keeps its existing 2026-10-22 date. The reviewed safety code and regressions are unchanged from safety commit `162181c8d8`. - Normal integrated-head commit/push hooks passed; evidence `nonfatal-main2-push.log`. No workflow, timing budget, test selection, skip hatch or force-push change. [Live exact-head checks](https://github.com/BasedHardware/omi/pull/23397/checks) are authoritative: require every expected backend check, all six unit shards and aggregate gate, full Hermetic E2E and merge gate, emulator proofs, guardrails, source closure, static contracts, metadata, hygiene and formatting to be present and successful before merge. The final gate certificate belongs to the lane handoff; no stale-head or check-presence-only certification. - Safety delta local evidence: **165 focused unit passes** (47 sync-two-lane, 24 monthly total, 60 usage units, 34 user usage), **24 targeted hermetic passes**, and **56 loopback monthly Firestore emulator passes**. Eight ordinary/once refusal cases prove zero writes/committed usage receipt, exact bounded reason counter/log, and unrelated errors still propagate. Real finalize cases include a root absent before admission, root removed immediately before accounting, pending/completed deletion and live once replay; the job and persisted decoded conversation/transcript complete. Evidence: `nonfatal-unit2.log`, `nonfatal-unit3.log`, `nonfatal-hermetic2.log`, `nonfatal-emulator2.log`. - Full Hermetic E2E on predecessor `f05a38addd`: **135 passed, 3 skipped, 2 xfailed**, 110.56s ([job](https://github.com/BasedHardware/omi/actions/runs/40028805287/job/120671936148)); emulator, other five shards and stack checks also passed. That head was not green: its first shard-3 attempt passed all 66 runtime-image assertions but failed a **1.17s / 1.00s CPU guard**; one bounded same-head retry passed all test files and the CPU guard but failed the unchanged **723s / 720s wall gate**. Earlier safety head `162181c8d8` failed wall **733s / 720s**. No further identical reruns are queued. Main #23402 then advanced and caused a real merge conflict; the latest head integrates that changed source/test input. Timing evidence: `nonfatal-final-unit3-failure.log`, `nonfatal-final-unit3-retry-failure.log`, `card:fs-p3-ci-unit-wall-budget`. - One requested safety delta Luna review: **SHIP, no P0/P1**, execution `exec-express-mask-gap-tennis-atom-bundle`; static production/caller review, `nonfatal-luna-review.md`. Later changes only corrected test setup/fake deletion semantics and integrated already-reviewed main. No review loop. - Earlier writer proof remains: fake **744 source reads to 1 warm read**, identical five-field/day-cutoff results, three writer authority reads and one added total write. Monthly emulator proofs include all original creator erasure cases, receipt rollback/retry/replay and racing root/deletion inventories. Four historical broader projection failures also reproduced on then-main `4d236fd94e`, tracked on `card:fs-p3-projection-emulator-baseline`; the broader suite was not rerun after the latest upstream integration. All local checks use `omi-heavy` at nice 19 with targeted FILE_LIST or hermetic `-k`. No full local backend unit suite, production data, GCP or deploy action. Reader remains off until lead-owned writer/epoch gates; realized net savings are unmeasured. ## UI evidence UI-Evidence: none -- backend accounting/read-path change. ## Failure class (fixes) Failure-Class: none The erasure defect was found within this unmerged feature; no shipped incident is classified. ANX owner/evidence: `card:fs-p3`, `card:p88-monthly-usage-cold-seed-erasure`. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Summary
Repeated released-memory reads reload identical canonical, historical and metadata windows. This change atomically maintains a content-free owner change head with source commits, including deletes, and reuses exact raw-query projections at internal canonical, historical, list-window, status-pair and MCP-card callers. Existing authorization, policy, lineage, privacy, decryption and lever paths remain authoritative.
Warm 100-document pages use two head reads instead of 100 source-document reads. Cold pages add head checks; queries smaller than three rows bypass reuse. The sprint's 50M/day target is conditional and unmeasured. Grade avoided source reads minus marker reads and added writes before booking savings.
This branch merges main through
251892e223fca3bf5c90f060d3b9673683e258fa, including P1 list projections (#23394), fs-p5 operation snapshots (#23393), the typecheck repair (#23440), merge-copy fixture repairs (#23447), and apt CI repair (#23446). Conflict resolution retains BOTH writer installers, BOTH account-erasure cleanup families, and all flag contracts. New real-SDK sync/async mixed-batch checks verify one atomic commit, both projection families, and unchanged source result counts. Erasure checks cover late head recreation with both present and missing user roots. The final fs-p5 refresh resolved only an adjacent flag insertion; its origin-counter repair is byte-identical to P2's.The archive-filter CI regression is fixed in production registration:
firestore_read_originandreleased_memory_projectionrecover their existing process-wide Prometheus counters after import-isolation teardown evicts modules. Two re-import cycles prove collector identity and counts survive. No test catches the error or weakens archive behavior. The earlier shard-5 rerun passed all four archive cases in 514s against its unchanged 720s budget.Lane / contract
fs-p2 owns
released_memory_changes_v1,MEMORY_RELEASED_PROJECTION,MEMORY_RELEASED_WRITERS_COVERED, andomi_memory_released_projection_total; original design bus 9012d9. MCP consumes P1'slist_serving_versions/conversations.version, writer kill switch and coverage epoch (original bus dd3ecb). Missing P1 metadata retains source reads. No additional conversation writer is introduced.Product invariants affected
Verification
Final focused conflict-resolution run on m1: 433 tests across 21 files passed through
/Users/david/workspace/omi-workspace/bin/omi-heavy run -- nice -n 19 env BACKEND_UNIT_TEST_FILE_LIST=/Volumes/scratch/m1-lanes/fs-p2/fs5-merge-files.txt BACKEND_PYTEST_WORKERS=4 bash backend/test.sh. Covers P1/P2 projections, mixed sync/async writes, erasure/privacy, archive filtering, origin attribution/wiring, MCP consumers, memory policy, all three shared-main merge-copy stub files, and fs-p5 snapshot/metric/tombstone/unlock contracts. Log:/Volumes/scratch/m1-lanes/fs-p2/fs5-merge-focused.log. The prior P1/P2 refresh passed 353 tests across 17 files.Full backend typecheck passed with zero errors (existing warnings remain), via
omi-heavy run --cache-default backend-typecheck -- nice -n 19 bash backend/scripts/typecheck.sh; log/Volumes/scratch/m1-lanes/fs-p2/merge-typecheck.log. One read-only Luna conflict delta review completed with no P0/P1 findings:exec-curve-yellow-plunge-fancy-pill-obtain, result/Volumes/scratch/m1-lanes/fs-p2/luna-merge-result.txt. Historical metric delta review:exec-rhythm-sort-chapter-traffic-comic-vendor; its P1 typing finding was corrected and verified.Published final merge head:
6ac131f9f566b0eb2d35447329c685d76c951ed1. Exact-head CI is green: Backend Unit Tests, attempt 2, Firestore emulator proofs, and hermetic backend gates pass. All visible checks are terminal: 37 successful, 30 intentionally skipped, no failures. Final-head shard 5 passes all four archive cases with wall 673s/720s. The single permitted failed-job rerun passed shard 4 (all 66 runtime-contract assertions, GPU closure CPU 0.88s/1.00s, shard wall 615s/720s). No threshold, allowlist or source changes and no further reruns.Attempt 1's sole failure was the unchanged GPU closure CPU guard at 1.01s against 1.00s, with all 66 assertions passing. Exact main also fails the same guard at 1.16s in run 40026957577; test and closure tool blobs match. ANX
card:fs-p2-runtime-durationretains the shared-main timing follow-up for the lead.Normal pre-push exited 0: all 37 manifest checks, full backend typecheck with zero errors, runtime source closure and bounded selected unit checks passed; log
/Volumes/scratch/m1-lanes/fs-p2/fs5-merge-push.log. The prior main refresh also passed all normal pre-push gates; log/Volumes/scratch/m1-lanes/fs-p2/merge-push.log.Prior-head CI passed five unit shards, guardrails, Firestore emulator proofs and hermetic gates. Shard 5 passed all four archive cases in 635s against its unchanged 720s wall budget. Shard 4 passed all 66 assertions in unchanged
test_runtime_image_contracts.pybut failed its CPU guard on the GPU import-closure test at 1.05s versus 1.00s. A focused same-runner local reproduction passed all 66 tests, that case at 0.31s; log/Volumes/scratch/m1-lanes/fs-p2/runtime-focused.log. No threshold/allowlist changes and no CI rerun used. Tracking: ANXcard:fs-p2-runtime-duration. Main advanced with fs-p5 during this CI run, so the final merge gets fresh CI rather than rerunning the superseded head.Earlier synthetic P2 Firestore emulator proof passed failed-batch atomicity, SDK transaction retry, result cardinality, sync/async deletes, bulk exclusion and raw-read parity at recovered head bf6f72c. Emulator project
demo-fs-p2, local127.0.0.1:18585; log/Volumes/scratch/m1-lanes/fs-p2/emulator.log. This historical emulator run is not claimed as fresh conflict-resolution evidence. New-head registered CI emulator proofs must pass before merge.Rollout / rollback
Writer maintenance is on. Reader preference defaults on with
MEMORY_RELEASED_PROJECTION=offas kill switch. Reuse requiresMEMORY_RELEASED_WRITERS_COVERED=v1:<unique-epoch>, initially absent until complete writer-fleet attestation. MCP additionally requires P1 writer coverage and its fresh epoch. Bulk-blocked or missing-head owners retain source reads; no user-data backfill.Owner: rollout lead. Target T2 2026-10-24 08:00Z, cutoff 07:30Z, only after exact-head CI is green. By cutoff, verify every backend/sync/backfill/integration/listen/pusher/desktop/job writer release and synthetic create/update/delete parity, including standalone/non-Python/raw-RPC writers. If proof is missing, record the blocker and keep reuse disabled. Once proved, enable all eligible owners with a fresh epoch.
Metrics: bounded
surface/outcome/originonomi_memory_released_projection_total; marker reads useorigin=job:released_memory_projection, and source reads retain their existing caller/origin. Compare output/order/access parity and p95. Any mismatch or regression disables readers. Grade net reads in equal full-day windows and mature billing before recording savings.Clear coverage before ANY writer rollback or gap; rotate the epoch after restoration. Reader-only rollback keeps head writers installed. Details:
backend/docs/released-memory-change-projection.md.Failure-Class: none
Line-Count-Exception: backend/database/memories.py | 1968 -> 1971 | three raw query calls adopt the shared projection transport; query and policy ownership remain in place
Tracking: ANX
card:fs-p2-released-memory-projection, owner fs-p2; lead owns merge/deploy and full writer-fleet audit/activation by 2026-10-24 07:30Z. Handoff:/Volumes/scratch/m1-lanes/fs-p2/HANDOFF.md.🤖 Generated with Claude Code