Repository navigation
fix(batch): strict-VAD no-speech operator with disabled undo (L6b) - #25063
Conversation
Failure-Class: FC-irreversible-terminal-hide
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: c2bf9d8acb
ℹ️ 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".
| owner = user.get(transaction=transaction).to_dict() or {} | ||
| if owner.get('private_cloud_sync_enabled', True) is False: | ||
| raise NoSpeechConflict('privacy_changed') | ||
| transaction.update( |
There was a problem hiding this comment.
Fence terminal closes against an active recording lease
For a capture older than two hours with no current upload token, candidate_refusal() permits closure even when its recording session has a live lease. Neither planning nor this transaction reads that lease. database/recording_sessions.py renews leases on the separate session document, so the conversation revision fence does not detect a reconnect or heartbeat. An active, temporarily silent capture can consequently become completed and discarded before more speech arrives. Read and reject an active recording lease in the close transaction, as the existing oversized-terminal and empty-cleanup paths do.
Useful? React with 👍 / 👎.
| entry['disposition'] = 'proof_refused' | ||
| except Exception: | ||
| entry['disposition'] = 'read_error' | ||
| entry['exit'] = EXITS[entry['disposition']] |
There was a problem hiding this comment.
Handle every disposition returned by candidate_refusal
When a discovered stale row has record_upload_sessions, the imported candidate_refusal() returns upload_pending, but EXITS has no such key. This lookup is outside the exception handler, so one pending producer aborts the entire page instead of reporting a skipped row; the CLI emits only its generic error and cannot produce an approval digest. Add an exit for this refusal and audit the other helper results, including privacy_skipped.
Useful? React with 👍 / 👎.
| outcomes = undo_no_speech(store, entries, ledger=ledger, pace=args.pace_seconds) | ||
| else: | ||
| outcomes = {'would_restore': len(entries)} |
There was a problem hiding this comment.
Recover prepared ledger entries whose close already committed
If the process exits after the Firestore close commits but before ledger.committed() is durably appended, the write-ahead ledger contains only a prepared entry. Undo silently filters that entry out here, leaving the conversation hidden with no recovery through the documented command. Reconcile prepared entries against the matching terminal marker and establish a safe revision-fenced restore path rather than treating the missing local receipt as evidence that nothing committed.
Useful? React with 👍 / 👎.
| def update(self, ref, patch): | ||
| self.has_written = True | ||
| row = self.client.rows[ref.path] | ||
| for key, value in patch.items(): | ||
| if value is firestore.DELETE_FIELD: |
There was a problem hiding this comment.
Use the mandated strict Firestore transaction fixture
These storage-boundary tests introduce a separate transaction fake with document-reference reads and update/set, despite backend/AGENTS.md explicitly requiring tests.unit.fixtures.strict_firestore_transaction.StrictFirestore for that surface. The custom implementation bypasses the shared fixture's constraint checks and supplies its own no-op commit behavior, so these tests do not inherit the repository's established transaction guard coverage. Use the mandated fixture; cover any additional commit-result behavior with the emulator before extending the shared seam.
AGENTS.md reference: backend/AGENTS.md:L232-L232
Useful? React with 👍 / 👎.
| return ( | ||
| _classify(speech_seconds=speech, raw_objects=len(refs), legacy_objects=0), | ||
| speech, | ||
| audio, | ||
| len(refs), | ||
| 0, |
There was a problem hiding this comment.
Prove raw coverage before ignoring retained legacy audio
If a conversation contains raw-live packs for only part of its capture and retained chunks/ audio for another part, this branch measures only the raw packs and never inventories the legacy chunks. A silent raw tail therefore produces an actionable no_speech plan even when an earlier legacy-only span contains substantial speech; apply repeats the same incomplete measurement and hides the conversation. The existing list_audio_chunks() and retained_record_units() paths support mixed retained sources, so raw-object presence alone is not proof of complete coverage. Verify that raw packs cover all retained spans, or leave uncovered legacy audio as retained_audio_unmeasured.
Useful? React with 👍 / 👎.
| revision = lifecycle.close_no_speech_capture( | ||
| uid, | ||
| cid, | ||
| expected_revision=entry['revision'], | ||
| run_id=plan['run_id'], |
There was a problem hiding this comment.
Carry the approved privacy generation into the close transaction
If the owner starts a protection migration after _reprove() reads privacy authority, including while it re-measures audio, users.set_migration_status() changes the user document and advances the batch privacy generation without changing the conversation revision. This close call passes no expected privacy generation, and the storage transaction checks only private_cloud_sync_enabled, so it still hides the row despite the migration/purge fence that assert_batch_write_allowed() would reject. Pass the approved generation through the lifecycle boundary and validate canonical privacy authority inside the same transaction as the close.
Useful? React with 👍 / 👎.
Failure-Class: FC-irreversible-terminal-hide
Failure-Class: FC-irreversible-terminal-hide
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2fc15c2e65
ℹ️ 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".
| for line in self.file: | ||
| body = json.loads(line) |
There was a problem hiding this comment.
Recover durable ledger entries after a torn trailing append
If a crash or disk-full error leaves a partially written final ledger record, this unconditional JSON parse aborts the entire undo before any durable prepared entries can be recovered. In particular, a torn committed receipt after a successful Firestore close defeats the prepared-only recovery path and leaves that conversation, plus all earlier entries on the page, unrestorable through the CLI. Preserve validation of complete records, but handle an incomplete trailing append so the durable prepared entries can still be reconciled against their terminal markers.
Useful? React with 👍 / 👎.
| if disposition in ACTIONABLE: | ||
| entry.update( | ||
| row_sha256=row_state(row), | ||
| privacy_generation=generation, | ||
| revision=revision, |
There was a problem hiding this comment.
Exclude photo-bearing captures from the audio-only terminal
For a stale batch-live capture containing photos but no retained audio, the planner produces an actionable no_retained_audio entry and apply hides the conversation without checking its photo content. This is a supported capture shape: store_conversation_photos() persists has_photos=True, and test_photo_only_capture_keeps_ordinary_photo_finalization verifies that the existing finalizer preserves photo-only captures for ordinary processing rather than empty cleanup. Neither candidate_refusal() nor the close transaction rejects that marker, so the row revision fence does not protect photos already present when planning starts. Exclude photo-bearing captures, including legacy photo children without the marker, before authorizing this terminal.
Useful? React with 👍 / 👎.
…#25060) ## What / why Supersedes #25042 (split per custody review). L6a provides the lifecycle-owned reversible no_speech storage transition, exact restore, existing Home hiding and writer inventory. L6b #25063 supplies the operator. No decoder, automatic caller or production operation is included here. ## Product invariants Preserve all row/audio/content bytes. Snapshot lifecycle field presence and values; close requires expected update_time and canonical row/user privacy. Restore refuses foreign runs, changed generations and invalid closed shapes. Quiet checks remain untouched by close/restore. Existing Home discarded filtering hides closed rows; compliance/export retains access. ## Pre-review dispositions - A P1-1 fixed: close mirrors batch_pipeline_privacy's three-way batch-live fence (uses_custom_stt, absent/false row private_cloud_sync_enabled, false user flag), in the write transaction. Row-level regression cases cover all three row shapes. - A P1-2 fixed: close_no_speech and restore_no_speech are lifecycle-only methods. Added direct-call rejection and atomic-hidden-close exemption guard tests. The restore lifecycle submodule is secret-free; its narrow tripwire exception permits only restore_no_speech, and lifecycle.py re-exports that intent. - A P2-1 / B P1-2 storage half fixed: missing/empty/None SDK write results return committed_revision_unknown, never raise after the hide. L6b records and resolves that outcome through the private marker and a current-revision fence. - A P2-5 resolved deliberately: restore remains unblocked by privacy admission. It restores the owner's existing row without audio reads or new cloud work; an opt-out after close must not strand that row hidden. Run/revision/shape fences still apply, with a regression test. - A P2-8 partially improved: Home visibility uses actual close output; merged-row refusal is covered; the post-commit test blocks actual client reads/transactions; the no-delete test checks retained audio and the fake delete list. Follow-ups (non-blocking review P2s): A P2-2 storage-level kill switch; P2-3 full recovery-admission/protected-content/account-deletion parity; P2-4 deterministic orphan-finalization-job fence; P2-6 prior-marker value validation; P2-7 bounded uid/cid validation; remaining P2-8 malformed snapshot, wrapper, repeated-restore and RFC3339 fidelity cases. These are not implemented by this batch. ## Tests Repository backend/test.sh via omi-heavy, offline with credential overrides removed: test_no_speech_terminal.py, test_check_conversation_lifecycle_writes.py, test_lifecycle_state_table_writers.py, test_batch_privacy_conversation_fence.py and test_conversation_quiet_finalization.py. Final result: 1,920 passed across five files, including 28 storage cases and 18 lifecycle guard cases. Full preflight and full pre-push hook passed; exactly one normal push for this fix batch, without force or skipped hooks. ## UI-Evidence none — no UI code change; actual closed-row visibility is covered locally. Failure-Class: new FC-irreversible-terminal-hide is introduced by the overall PR and guarded by the storage and lifecycle suites. ## Rollback Stop new callers; restore unchanged closed rows with their matching run/revision (L6b can resolve missing receipts from the private ledger), then revert code. Never delete rows/audio. Restore stays available after privacy opt-out and does not initiate cloud work.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f13bab4b98
ℹ️ 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".
| # Enroll the authority in this transaction's conflict set. Checking only | ||
| # consent would miss a revoke/re-enable after the operator's reproof. | ||
| # Keep this import off the secret-free restore path. | ||
| from database.batch_pipeline_privacy import PRIVACY_COLLECTION, privacy_owner_key |
There was a problem hiding this comment.
Keep the privacy authority import at module scope
This new function-local import violates the explicit import rule in backend/AGENTS.md: all imports must be at module scope, never inside functions. Keeping audio and secret dependencies off the undo path is necessary, but should be achieved by extracting the privacy collection identifier and owner-key helper into an import-safe module rather than introducing another function-local dependency.
AGENTS.md reference: backend/AGENTS.md:L168-L168
Useful? React with 👍 / 👎.
…#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.
What / why
Supersedes #25042 (split per custody review). Depends on L6a #25060, now merged into main. Current origin/main (85de198) was merged normally before this coverage fix (both independently added feature flags retained in the merge conflict); no rebase or force-push.
Strict local VAD, bounded newest-first discovery and digest-approved plan/apply/undo close stale batch-live captures reversibly. The operator requires complete versioned audio coverage before silence classification, isolates row refusals and recovers receipt loss while keeping undo independent of audio secrets/clients. No automatic caller or production operation is authorized.
Product invariants
Preserve row/audio/content bytes, prior-field presence snapshots, exact revision/run/shape fences, row/user privacy and the approved privacy generation inside the close transaction, counts-only CLI output, bounded newest-first pages and content-free dispositions. Known committed revisions keep their original exact fence. Complete sample coverage and byte-identical overlap deduplication precede VAD. Only missing/unknown receipts resolve the current matching marker before a current-revision-fenced restore. An edit between that read and restore refuses the write. Undo never starts audio, transcription or new cloud work.
Pre-review dispositions
Second Luna FIX-FIRST at f13bab4 / DeepSeek P2-4 fixed: generation/metageneration-fenced raw listing snapshots must prove the entire timezone-aware row started_at/finished_at interval from versioned capture_start/capture_end, explicit gap_count=0 and decoded mono 16 kHz PCM frame counts. Canonical filename timing is the fallback for capture_start. The retained sample-range union helper limits total missing coverage (boundaries plus interior holes) to 20 ms / 320 frames. Identical overlap samples are included once; conflicting overlaps, unknown timing, gaps and unexpected out-of-range objects return coverage_incomplete with operator_review exit and aggregate counts. VAD only runs on the proven timeline. Apply reproof repeats the proof on its fresh listing, including added objects, before ledger preparation. Empty raw/legacy listings also refuse; historical no_retained_audio plans are non-actionable. Missing listing size/metageneration and failed download preconditions also refuse coverage. The first local Luna delta found the metadata race; it is fixed by passing the listing snapshot to canonical read_reference, with tests using the actual reader to assert both generation preconditions. Tests exercise gaps with no write, complete coverage, identical and conflicting/contained overlaps, numeric-string/filename timing, missing timing/internal gaps, cumulative tolerance and added/missing objects between plan and apply.
Luna FIX-FIRST at 2fc15c2 fixed: the operator passes the approved privacy generation through the lifecycle intent into close_no_speech/_close_txn. The transaction reads the canonical hashed privacy authority before writing and refuses privacy_changed on mismatch, including consent revoke/re-enable after reproof. Optional None preserves L6a direct-caller behavior. Regression runs actual reproof, changes generation at ledger preparation, and proves no conversation write/receipt. Matching, absent-generation-zero and omitted-generation contracts are also tested.
B P1-1 fixed: upload_pending and privacy_skipped have exits. Disposition/exit validation is inside the row failure boundary; unknown labels normalize to proof_refused. Mixed-page tests preserve later actionable rows and counts-only reporting.
B P1-2 / custody P2#1 / A P2-1 fixed: storage returns committed_revision_unknown when the SDK omits its result, and the ledger records it distinctly. Undo includes prepared-only entries, re-reads the row, proves marker.run_id plus completed/discarded/terminal_no_derived_effects, and fences restore on the current revision. Known receipts remain exact-revision fenced. Tests cover actual empty write_results, prepared-only crash recovery, foreign/changed shapes and a concurrent edit after resolution.
Custody P2#2 / B P2-6 fixed: undo requires neither ENCRYPTION_SECRET nor a storage client. The CLI loads planning/audio dependencies only after choosing the non-undo path. Restore uses the lightweight lifecycle-owned intent. Fresh-process tests remove the secret and block all network/audio dependency loading.
B P2-7 fixed by an explicit one-ledger-per-page contract: exclusive creation remains, reuse cannot overwrite a partial ledger, and recovery uses the old page's ledger before replanning with a new path. No append/resume behavior is added.
B P2-14 fixed: table tests cover wrong tiers, emulator refusal, page/pace bounds, missing apply approval/ledger, forbidden undo cursors, identical cursor files, undo dry-run, ledger mode/symlink/existing-path refusals.
A P1-1/P1-2 and P2-5 are included through L6a: canonical close privacy, lifecycle tripwire, and deliberately privacy-unblocked owner restore. A's improved no-delete assertions also resolve B P2-12's ineffective mock.
Follow-ups (non-blocking review P2s): B P2-1 absent-owner-document defense; P2-2 discovery age cutoff; P2-3 last-scanned cursor progress; P2-5 pre-extend memory budget; P2-8 undo offsets if ledger bounds ever change; P2-9 restored-event receipts; P2-10 finished_at convention; P2-11 server close timestamp; P2-13 end-to-end raised-privacy fidelity; remaining P2-15 broad unexpected/receipt-fsync error classification (prepared recovery is now available); P2-16 re-decode duration/cost disclosure. L6a's remaining P2-2/3/4/6/7/8 are listed in #25060. These are not implemented by this batch.
Tests
This coverage batch runs backend/test.sh through omi-heavy with credential overrides removed and offline providers: test_no_speech_coverage.py, test_no_speech_operator.py, test_no_speech_terminal.py, test_record_partial.py, test_source_audio_listing.py and test_record_orphan_repair.py. Result: 270 passed (19 coverage, 57 operator, 32 storage, 67 partial-retained, 8 source listing, 87 orphan repair). Both fresh-process secret-free undo modes remain covered. Full local preflight passed all 43 checks. Luna delta on 93ac677: SHIP, no concrete remaining findings; read-only source review, no tests run by the reviewer and no merge approval. Full pre-push hook passed, including all 108 storage/operator/coverage tests. Exactly one normal push in this coverage batch; no force or hook skips.
UI-Evidence
none — no UI code change; existing Home filtering is covered with actual closed rows.
Failure-Class: FC-irreversible-terminal-hide
FC-irreversible-terminal-hide is defined by merged L6a and guarded by both no-speech suites, including the transaction privacy-generation race regression.
Rollback
Disable new closes with NO_SPEECH_TERMINAL_ENABLED=false. Keep it false while using --undo --apply with each private page ledger. Prepared-only/unknown receipts resolve the matching marker; known revision conflicts require separately reviewed manual recovery, preserving unrelated edits and all audio/content. Revert code only after restoring rows. No production apply is authorized here.
Capacity numbers and state exits
Operator bounds carried from #25042: MAX_AUDIO_SECONDS initial 7200; MAX_RAW_OBJECTS initial 4096; discovery limit initial 128 (range 1..128); GCS page_size initial 200; pace initial 0.5 seconds (range 0.1..60). Speech threshold remains strictly below 10 seconds. New fixed coverage policy: TOLERANCE_FRAMES initial 320 (20 ms at 16 kHz), cumulative across boundaries and interior gaps; zero prior coverage checks are replaced by mandatory complete-coverage proof. No runtime tuning flag is added. No serving capacity change.
State no_speech exits through restore_no_speech. Outcome committed_revision_unknown exits through private-ledger marker resolution and fenced restore. coverage_incomplete exits by operator review and only a fresh coverage-proven plan can become actionable; empty-list no_retained_audio plans no longer close rows. Upload-pending rows stay untouched for operator review; privacy-skipped rows exit by operator rerun after consent.