Repository navigation
Measure duplicate projection follow-up discovery without extra reads - #25596
Conversation
Codex Review Summary: ✅ CompletedThis 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d0186011d4
ℹ️ 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 observer_for_store(store): | ||
| """Observe direct Firestore or its known mirror-only wrapper; exclude index/PG discovery.""" | ||
| from database.batch_pipeline_store import FirestoreStore |
There was a problem hiding this comment.
Move store-class imports to module scope
observer_for_store introduces function-local imports for both FirestoreStore and DualStore, contrary to the explicit backend import convention in backend/AGENTS.md: all imports must be at module top level, never inside functions. Move both imports to the module import section so the new instrumentation follows the repository's required dependency structure.
AGENTS.md reference: backend/AGENTS.md:L166-L168
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Accepted and fixed in published head 69e6434866f4d046bff3ad86472f3cc91d31108a: FirestoreStore and DualStore imports now live at module scope; no function-local imports remain in observer_for_store. Related panel fixes also add the diagnostic off switch with its ownership record, strict malformed-sketch rejection, and a bounded constant debug signal for callback failures. 123 affected tests passed; the ownership update passed 47 affected tests. Normal pre-push hooks passed without bypass or timing-limit changes; remote head independently matched. New-head CI remains pending its existing watch.
## Change Ordered merge and source-alias fallback now stamp an idempotent projection obligation on the committed result in the same transaction. The segment key and owner log sequence identify the revision. Serving offers an immediate, bounded post-commit hint, and one strict lease holder per namespace scans lost wakes in kind, due time, and document ID order. A delivery claims the revision, runs the existing fenced projector, then settles from the canonical result state. Predecessor, sibling, timeout and error deferrals retain the obligation with a bounded clock and a disposition. Multipart receipts, content ledger completion, hourly usage, retained audio and privacy checks use the existing authority. This removes downstream job/policy probes and projection attempts for covered rows from legacy assignment, finish and follow-up sweeps while the backstop has recently succeeded and is keeping up. Legacy pages retain their raw Firestore reads, cursor and overlap measurements. The existing finish classifier (#25314), follow-up due-clock marker, overlap measurement (#25596), refused-head recovery (#25623), and raw keyset conformance (#25555) retain their separate responsibilities. ## Mixed versions and rollback Older writers, including GPU image `ef42ee8`, leave unstamped rows eligible for every legacy path. Older readers may consume a stamped result through the existing receipt and accounting fences. Current GPU-side commits rely on the elected due scan because the GPU process has no projector. No cross-process wake transport or historical backfill is needed for coverage. Fenced held release and privacy resume rearm a result and invalidate its prior token. New writers with the switch off mark a reactivated row for legacy discovery while keeping its previous scheduling metadata. An expired or stalled backstop restores compatibility attempts, even for stamped rows. Set `BATCH_PROJECTION_OUTBOX=false` on the participating readers and writers to restore the full legacy discovery paths and stop new obligations and claims. Existing result and receipt data stay available. Set it to true to resume after both stage-specific indexes are READY and the due query is confirmed. Release qualification compares matched completion, partial latency, oldest obligation, failures and read/write telemetry across the actual serving roster. The outbox supervisor starts on projection-serving roles when its switch is on. A batch-serving process continues outbox discovery when the dedicated pump and legacy projection sweep are both off. The due-page loop has a 5-second interval, a MAX_PENDING initial 200-key bound, and a MAX_SCAN_LAG initial 60-second coverage limit. Both follow-up queues share the existing per-process slot budget. Its claim expires after 180 seconds. Existing serving and projection-pump cadence and page configuration are preserved. A missed wake, process loss or leader change returns unclaimed debt to discovery. A canonical hold parks it until an existing release or privacy resume. Persisted and ready receipts honor a future `projection_followup_due_at`. Unsuccessful finish then uses the configured follow-up backoff on the outbox clock, with a 60-second fallback if the setting is zero. Outbox delivery skips the legacy durable deferral write. ## Expected saving **Inferred, unmeasured in serving.** The design baseline measured overlapping 339.56M follow-up-origin and 222.08M serving-origin reads in the 24 hours ending 2026-11-18 13:16Z. Those totals include useful work. The avoided share is the expensive downstream attempts of covered rows, and the two baselines cannot be added. Embedding the metadata adds zero document writes at merge. One claim plus one settlement at the recorded 1.516M daily commits implies about 3.03M scheduling writes/day if every commit follows that path, before retries and lease writes. Index cost and net read savings need a matched serving measurement. ## Panel and verification Scope panel `scope-20261118t145338-00de` returned three answers. Accepted its writer audit, per-row revision witness, strict lease and post-page token check, due deferral, existing receipt/privacy fences, three-store parity, existing age gauge, rollback and cost measurement. Chose embedded result fields because they avoid a new merge write and preserve the existing purge and retention lifecycle. Deferred a physical Firestore legacy page cut, fleet backfill, additional election switch, and cross-process wake transport. A successful per-row witness keeps old and mixed-mode writers eligible without a fleet cutover. The scope command emitted a dossier without F-numbered findings, so its review-only triage CLI had no calls to record. - `cd backend && .venv/bin/python -m pytest -q tests/unit/test_firestore_query_shapes.py --tb=short` — 611 passed. - `bash backend/scripts/check_runtime_env_compose.sh`, `python3 scripts/check_feature_flag_registry.py`, and `cd backend && .venv/bin/python scripts/generate_firestore_indexes.py` — passed. - Focused backend pytest files for the outbox, serving, leader, discovery and follow-up desync — 201 passed. - `OMI_REQUIRE_STORE_BACKENDS=all .venv/bin/python -m pytest -q tests/integration/test_store_conformance.py -k projection_outbox` (loopback Firestore and an owned PostgreSQL 16 container) — 3 passed, one per store. The fixture pins scheduler elapsed time alongside its synthetic timestamps so local load cannot expire the setup claim. - `.venv/bin/python -m pytest -q tests/integration/test_batch_pipeline_projection_followup_firestore.py` (loopback Firestore) — 13 passed, including lost wake/ack, duplicate delivery, privacy, predecessor, and multipart restart. - `.venv/bin/python -m pytest -q tests/unit/test_flag_budget.py` — 26 passed. `.venv/bin/python -m testing.pipeline_sim projection-drain --rows 300 --owners 12` — all three projection modes preserved ordering and completed assignment. - Dev and prod `backend/scripts/validate-backend-runtime-env.py` and deployment-setting classification — passed. - The normal pre-push PR preflight passed all 52 selected static, metadata and Firestore guard checks. The local hook used the approved 900-second per-file wall budget after a host-load timeout. - Whole-backend Pyright passed with zero errors in the normal push hook. The loopback Store conformance and 13 Firestore tests were repeated after the typed Store interface correction. - The outbox unit and background-task ratchet rerun passed 12 tests, including graceful worker shutdown. The runtime manifest validator passed 295 tests, and the async blocker gate reported zero selected findings. - `cd backend && .venv/bin/python -m pytest -q tests/unit/test_batch_pipeline_projection_outbox.py` — 6 passed after adding the mixed-switch reactivation assertion. The three-store conformance and 13-test Firestore replay rerun also passed with the fixed scheduler test clock. ### Round 2 review and CI repairs Review panel `review-20261118t202810-030a` (FIX-FIRST), CLI triage `F1=accept F2=accept F3=accept`. - F1 starts elected outbox discovery independently of the dedicated pump and legacy sweep on a batch-serving process. Projection and first-summary policy stamping stay on owning roles. The outbox hands off predecessor work and index flushes after the delivery claim scope. - F2 proves a stale oldest due row clears the coverage witness, successful scans renew it near expiry, and scans leave a fresh witness alone. - F3 enforces the follow-up due time and configured backoff on outbox delivery. The outbox is the sole durable retry-clock writer for those deliveries. - CI on `d1195ac4cc7` found a stale ghost-hold assertion, a stale pump fixture and Store protocol expectations, and scheduler-only fields leaking into the characterization and provider-STT behavior goldens. The integration assertion now pins the ghost-hold outbox clock. The simulator trace excludes the internal kind and retry reason, with the outbox details checked directly by replay and conformance tests. - Hosted unit shard 7 on `0be3b03fd7e` caught the shadow-store guard pointing at the public wrapper. It now asserts that the cached constructor wraps the only Firestore store. All 23 cases in `test_jobstore_shadow_seams.py` passed locally. - Hosted Sync Cloud Tasks `batch-happy` on `0be3b03fd7e` exposed an admission process stamping projection policy when neither serving role was enabled. The startup gate now preserves projection-serving role ownership even while the outbox remains independent of legacy sweeps. - Round 5 incorporates [#25778](#25778), which removed the paused jobstore retirement carrier. The migration runner requires contiguous numbers, so the unchanged outbox index SQL occupies `0010_projection_outbox_due.sql`. Production Postgres target bindings remain absent and outbox projection stays on Firestore during the pause. The main branch’s staging isolation fence stays in place. - `08352903c14` also fences the delivery claim at canonical transaction read and before fair-use dispatch, preserves mixed-store discovery parity, and reserves queue space for lost wakes. - Ran each of nine focused unit files in its own pytest process from `backend` using `.venv/bin/python -m pytest -q tests/unit/<file>.py --tb=short`. All 559 cases passed across outbox, serving, pump, follow-up clock, job-store parity and migrations, provider STT, characterization, and the background-task ratchet. - The role-bound startup change passed the 178 focused serving, pump, and outbox cases. The local `batch-happy` gauntlet passed against Firestore and Redis with its original owning-role and effect assertions. The first local full-batch attempt stopped before scenarios at the serving startup deadline under host load. The focused rerun increased only the local startup wait. - Discovery, overlap, and dual-store focused unit files added 150 passes. The final typed parity adapter was exercised again with 156 protocol-parity and 78 dual-store passes. - `make preflight` passed all 52 selected manifest checks, including the index and collection guards, feature flags, and runtime composition. The normal push hook also passed whole-backend Pyright with zero errors and all 40 selected unit files. - Loopback Firestore pytest proofs passed 16 in `test_batch_pipeline_projection_followup_firestore.py` and 37 in `test_batch_projection_ghost_holds_firestore.py`. One ghost-hold throughput assertion was intentionally skipped because emulator speed depends on host load. - `OMI_REQUIRE_STORE_BACKENDS=all .venv/bin/python -m pytest -q tests/integration/test_store_conformance.py -k projection_outbox` passed all three backends. `test_jobstore_migrations_postgres.py` added three native PostgreSQL 16 passes. A supplemental full run was interrupted at 193 passes and two skips after a Docker connection stall reproduced by a standalone PostgreSQL connection. The targeted rerun used the native test fixture. - `.venv/bin/python -m testing.pipeline_sim projection-drain --rows 300 --owners 12` preserved projection and chain ordering in all three modes. ### Hosted verification at `6d2551733d9` The full Sync Cloud Tasks and Listen Pusher gauntlets, Backend Emulator Proofs, and unit shard 7 all passed. The backend unit suite remains red solely on two CPU-duration guard violations. Pytest reported 39 and 297 passing tests in the two files, respectively. [Hermetic E2E](https://github.com/BasedHardware/omi/actions/runs/44468718109), [emulator proofs](https://github.com/BasedHardware/omi/actions/runs/44468718162), [backend unit suite](https://github.com/BasedHardware/omi/actions/runs/44468718334). - `test_monitoring_adapter_hpa_contract.py::test_hpa_and_adapter_changes_select_this_contract` used 1.02 s of CPU against the 1.00 s limit. It used 0.65 s in the preceding hosted run and 0.59 s in the local rerun with the same guard. [Hosted shard 2](https://github.com/BasedHardware/omi/actions/runs/44468718334/job/135372906740). - `test_backend_runtime_env_validator.py::test_control_sync_routing_validates_deployed_values_without_changing_manifest[all]` used 1.04 s against the same limit. It used 0.92 s in the preceding hosted run and 0.62 s in the local rerun. [Hosted shard 5](https://github.com/BasedHardware/omi/actions/runs/44468718334/job/135372906741). - The two cases, their test selector, runtime manifest and validator are identical to the preceding PR head, which passed both hosted shards. The intervening diff restores projection-serving ownership and updates the store-construction guard. [Previous unit run](https://github.com/BasedHardware/omi/actions/runs/44461717687). ## Product invariants affected - INV-MEM-4. The runtime manifest declares a projection scheduling switch. Canonical memory admission and the projection receipt, ledger and accounting authority stay on their existing paths. Failure-Class: FC-unresolved-head-blocks-projection Line-Count-Exception: backend/utils/batch_pipeline/projection.py | 1871 -> 1914 | Projection owns coverage-aware discovery and dispatches outbox snapshots through its existing fenced receipt methods. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/25724?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/25724?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25724&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. --> Implemented by a delegated agent for the batch owner-state program.
Periodic projection follow-ups can repeatedly discover the same rows on several serving instances. This adds bounded, identifier-free sketches and row-visit counters at the existing discovery boundary so we can measure overlap before choosing a fleet leader. It performs no extra database queries or writes and changes no cursor, ownership, privacy, receipt or scheduling decision.
Only direct Firestore and its mirror-only wrapper are observed. Postgres/index/simulation adapters and targeted/owed repair are excluded. Fixed two-slot HLL64 windows export ranks, never identifiers or hashes; mixed epochs are rejected. The runbook states the 13% nominal per-estimate error, ratio/coverage limitations, cardinality/sample budget and the actual-serving/export proof required before a full24h readout. No leader or production rollout is included.
Validation: the canonical backend selected-suite runner passed151 tests:12 new overlap tests,67 discovery tests,21 due-clock tests and51 follow-up/desync tests. Synthetic overlapping/disjoint fleets, local repeats, empty/partial/mixed epochs, multiprocess-max decoding, bounded labels/memory, clock regression, adapter selection and observer failure are covered. Tests exercise the existing discovery API and prove no added query or cursor change. Source scope panel considered HLL/epoch/coverage risks; this PR gets its own exact-head panel review.
No production deployment, new scrape service, paid capacity or realized savings is claimed. Existing Release owns carrier/export/headroom qualification. Full coverage of actual serving targets and a complete24h window are required before sizing the separate elected-sweeper change.
Product invariants affected
None — diagnostic instrumentation only; projection eligibility, privacy/custody, receipt and scheduling semantics are unchanged.
Failure class
Failure-Class: none
New diagnostic instrumentation; the fix commits are pre-merge review corrections to this new feature, rather than an instance of an existing production failure class.
UI evidence
UI-Evidence: none — backend discovery instrumentation and synthetic tests only.
Panel triage: F1 rejected with the explicit parity timeline: epoch0 spans[0,600), completes at600, and slot0 is reused at1200. Capture deadline is600s after completion, as the completed-epoch runbook says. F2/F3/F4 accepted and corrected: default-on env off switch before drain construction; uniform ValueError for missing/non-numeric samples; bounded debug signal for custom observer failures without exception or row payloads. The original panel returned Luna SHIP and GLM FIX; all actionable findings were corrected by root. DeepSeek supplied no valid answer before its bounded collector timed out; no replacement reviewer was started. Exact operational reconciliation is retained in the dated run record.
Automated-review import finding accepted: FirestoreStore and DualStore imports now live at module scope as required by backend/AGENTS.md. Store selection and discovery behavior are unchanged. The focused canonical isolated-file delta suite passes123tests (21 overlap,51 discovery,51 follow-up), including disabled observer, malformed samples and payload-free failure logging. No production mutation or realized savings claim.