Skip to content

fix(record-seal): speed repairs and prioritize urgent and recent work - #25049

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

Git-on-my-level merged 14 commits into
mainfrom
lane/sealspeed

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

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.

View guided diff Turn on auto-fix

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 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 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 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 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 was pending behind the shared firestore-schema-prod concurrency lock held by main reconciliation 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 owns the current head's unit CI result.

Git-on-my-level and others added 14 commits November 10, 2026 19:33
A recording seal takes ~89 s per row (p50) and the seal itself is ~5 s.
~88% is per-process fixed cost: a fresh `python scripts/record_seal_repair_job.py
--row` subprocess re-imports the backend, and the pod is CPU-starved.

Three changes, no worker-count change (16 -> 24 already lost 15-35% of
seals/run in prod, #24962/#24966; 48 was worse, #24729):

- Chart: pin record-seal-repair to batch-pipeline-pool (8-19% CPU) with that
  pool's taints instead of the monitoring pool at 101% CPU, and raise the CPU
  request 2 -> 4 (== the unchanged limit) so 16 row workers are not starved to
  ~2 cores. Both are values-driven, so placement rolls back from values alone.
- Image: `python -m compileall -q /app` at build, and drop
  PYTHONDONTWRITEBYTECODE=1 from the CronJob. The pod has a read-only root
  filesystem, so .pyc must be baked at build time.
- Code: utils/metrics.py and utils/sync/stage.py import fastapi inside the one
  function that needs it. fastapi/pydantic was ~60% of the row's import bill
  and a recording seal does no HTTP work. Behaviour is unchanged.

Row import on a warm Mac, image-shaped tree: 8.0 s -> 1.2 s with .pyc,
~3.9 s without.

Guarded by a new import-graph test that imports the row entrypoint in a clean
interpreter and asserts fastapi/pydantic/starlette never load, plus chart
tests for the affinity, tolerations, request and the values-only rollback.

Failure-Class: new
# Conflicts:
#	config/feature-flags.yaml
@Git-on-my-level
Git-on-my-level merged commit aa3df45 into main Nov 11, 2026
71 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/sealspeed branch November 11, 2026 01:37
Git-on-my-level added a commit that referenced this pull request Nov 11, 2026
Retained dead jobs and GPU privacy-fenced jobs can still match both
merge_pending probes. This dark phase 1 excludes the explicit terminal
union with an indexed `state not-in (...)` filter, preserving
capture/segment ordering and future nonterminal state strings. No field,
schema change, backfill, deploy or enablement is included.

Current head: `68076d006c442d81efb51570c958184beb79c06f`.

The independent test-only PR #25083 has merged, fixing the pre-existing
messaging deadline race. Current main (including #25049 and #25083) is
integrated with a merge to preserve pushed history; this PR has no
messaging-test diff against main.

## B: terminal writer audit and verdict

The table covers all job-state writers found by AST payload-builder and
constant-alias inventory plus text search in production
database/utils/router/operator sources. Quarantined projection receipts
are separate result/receipt documents, not job state transitions. The
explicit terminal union combines queue dispositions
(`is_queue_dispositioned`), lifecycle terminals, and provider supersede.
A complement test ties it to the lifecycle inventory and provider state
constant.

| Terminal job state | Every job writer and merge_pending behavior |
|---|---|
| dead | [input
expiry](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/database/batch_pipeline_quarantine_recovery.py#L613)
sets true for GPU / false for assignment; [held
expiry](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/database/batch_pipeline_quarantine_recovery.py#L645)
explicitly sets true to retain legacy redrive; [aged record-barrier
expiry](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/utils/batch_pipeline/live.py#L599)
sets false. |
| privacy_blocked | [Firestore
revoke](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/database/batch_pipeline_recovery.py#L36)
preserves true for GPU leased/retry and clears it for provider states;
[Postgres
revoke](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/database/jobstore/postgres_store.py#L421)
and [sim
revoke](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/testing/pipeline_sim/store.py#L320)
mirror that conditional. |
| quarantined |
[quarantine_job](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/utils/batch_pipeline/retry_policy.py#L23),
[provider settle
failure](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/utils/batch_pipeline/provider_stt.py#L371),
[provider terminal
failure](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/utils/batch_pipeline/provider_stt.py#L400)
and [artifact
re-upload](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/database/batch_pipeline_artifact_missing.py#L164)
all set false. |
| committed | [ordered
commit](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/utils/batch_pipeline/merge.py#L327)
sets false. [assignment projection
release](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/database/batch_pipeline_projection_release.py#L372)
preserves false: its input-expiring terminal path requires the
assignment leg, which input expiry made false. |
| partial_retired | [partial
update_run](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/database/record_partial.py#L156)
preserves false: requires record_pending, whose
[creation](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/utils/batch_pipeline/live.py#L179)
and
[requeue](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/database/batch_pipeline_record_dead_letter.py#L16)
both set false. |
| provider_superseded | [provider
supersede](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/utils/batch_pipeline/provider_stt.py#L460)
explicitly sets false (SUPERSEDED constant at line 88). |

**Verdict: not structurally zero.** Dead held/GPU input expiry and GPU
privacy fencing can leave merge_pending=true while retaining
owner_key/capture_at/fresh_capture. Those rows can match both probes.
The other writers above contribute zero absent corrupt/legacy rows. No
terminal-returned-document census was performed, so no measured nonzero
saving is claimed.

Only the existing `state` field is newly filtered. Creation writers
always stamp it: Scheduler.enqueue_in_transaction (ready), native live
registration (record_pending), and provider_stt_admission
(provider_pending). Transitions above and existing lease/recover/requeue
paths preserve or explicitly set it; none removes it. No production read
or write was used for this audit.

## C: review fixes and scope

- ON uses explicit terminal exclusion, keeping future nonterminal
strings visible. OFF preserves the old Firestore query/read sequence;
exact SQL/parameter tests cover Postgres OFF too.
- first_pending and fresh_pending fall back to their exact OFF query on
FailedPrecondition (unbuilt index) or InvalidArgument (unsupported ON
shape). OFF errors still propagate. Real Firestore planning is an enable
prerequisite; the local emulator verifies capture-first negative-filter
ordering but does not prove production index readiness.
- OrderedMerge.commit_next is tested with a terminal merge_pending=true
head and later result_ready row, then redrive/complete of the retained
earlier row and its late result-log append. `_prefer_merge_head` is
tested under both flag values for terminal and unknown predecessors.
- `held_merge_owners` always uses the OFF query in all adapters,
preserving owner resolution even when only terminal pending rows remain.
oldest, held_oldest, new_over_sla, stale-vendor watchdog and fresh-head
wait remain independent.
- The flag has an owner/review date in the ADR 0006 budget, with its
inventory count and registry test updated. CONTRACT.md now describes
authoritative merge/scheduler effects, fallback and the held-owner
exception.
- Simulator/Postgres mirror behavior for conformance, including ON
missing/null exclusion. **All saving bounds below are Firestore-only.
Postgres gets no read saving**; the predicate is evaluated after its
existing index scan. Postgres has local real-backend conformance plus
CI-runnable exact SQL/parameter tests; CI's emulator proof still does
not run a PostgreSQL server.

## Baseline and estimate

Historical supplied GMP scope, measured 2026-11-10T22:35Z; no fresh
production measurement in this PR. W1:
**2026-11-09T20:00Z–2026-11-10T20:00Z**. W2:
**2026-11-02T20:00Z–2026-11-03T20:00Z**, pre-ramp reference. W1
denominator 15,554.8 admitted audio-hours; W2 3,788.7. Fleet totals
include the unlabeled GKE worker. Dollars use the scope's **$0.47/1M
reads calibrated proxy**, not settled SKU spend.

| Caller | W1 reads/day | W1 reads/audio-h | W1 $/day | W2 reads/day |
W2 $/day |
|---|---:|---:|---:|---:|---:|
| get | 230.30M | 14,806 | 108.24 | 14.55M | 6.84 |
| fresh_pending | 75.86M | 4,877 | 35.65 | 0.10M | 0.05 |
| due | 52.08M | 3,348 | 24.48 | 1.32M | 0.62 |
| first_pending | 10.97M | 706 | 5.16 | 0.10M | 0.05 |
| oldest | 16.30M | 1,048 | 7.66 | 19.91M | 9.36 |
| projection_page | 36.64M | 2,355 | 17.22 | 6.06M | 2.85 |
| timeliness_sample | 0.14M | 9 | 0.07 | 0.10M | 0.05 |
| Seven-caller total | 422.30M | 27,149 | 198.48 | 42.13M | 19.80 |

Method: intersect each query's owner/merge_pending/fresh predicates with
the terminal writers. Normal
[commit](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/utils/batch_pipeline/merge.py#L327)
and
[quarantine](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/utils/batch_pipeline/retry_policy.py#L24)
set merge_pending=false and contribute **zero** absent corrupt/legacy
rows. However [held
expiry](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/database/batch_pipeline_quarantine_recovery.py#L645)
deliberately writes dead + merge_pending=true, [input
expiry](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/database/batch_pipeline_quarantine_recovery.py#L613)
does so for the GPU leg, and [GPU privacy
fencing](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/database/batch_pipeline_recovery.py#L36)
preserves merge_pending. They retain the existing owner/capture/fresh
fields. Thus terminal rows **can** match both probes: the zero-match
STOP condition does not apply.

The caller counter has no state label, and there is no
terminal-returned-document census. The defensible code-only terminal
fraction for either caller is **0–100% of returned documents**; code
supplies no narrower empirical estimate. A nonzero population is
possible, not measured here.

For fixed query invocations, let T be matching terminal rows, A
nonterminal rows and L the cap. Billed document reads change from
`max(1,min(L,T+A))` to `max(1,min(L,A))`; active rows can refill a page.
The [instrumented empty-query
floor](https://github.com/BasedHardware/omi/blob/68076d006c442d81efb51570c958184beb79c06f/backend/database/firestore_document_probe.py#L655)
is one read.

| Revised path | Direct saving per invocation | W1-based code-only
saving bound |
|---|---|---|
| fresh_pending (L=32) | 0–31 reads; 0 when active rows refill the page
| 0–73.49M document reads/day, $0–34.54/day |
| first_pending (L=1) | 0 billed document reads; replacing a terminal
row or returning empty still costs one | 0/day directly |
| oldest | unchanged | 0/day |

Upper bound: 75.86M × 31/32 × $0.47/1M. **Planning/booked saving is zero
pending measurement.** The upper bound assumes terminal-only full fresh
pages and unchanged probe frequency; it is a ceiling, not an expected
point estimate or a measured reduction. It excludes index-entry charges,
new index storage/build cost and any downstream scheduling/read effects.
The original combined held-skip estimate is superseded for this cut. D+2
settled SKU must establish net dollars.


The capture-first negative filter can scan terminal index entries even
when it avoids document fetches. More than one range/order field can
incur index-entry billing; large terminal partitions can offset or
exceed the document-read ceiling. Net savings remain booked at zero
until a real query plan, scan/read measurements, and settled SKU confirm
a benefit. Any OFF fallback gives zero direct savings for that
invocation.

## Enable prerequisites: census and indexes

Build all four new composites to **READY before enabling** and verify
both ON queries with the real-Firestore planning oracle. This PR
declares indexes and does not provision or deploy them. An unsupported
ON shape falls back safely and is not evidence of benefit.

**The read-only state census MUST PASS (0) before
BATCH_HELD_POLL_SKIP_ENABLED is turned on, alongside index READY and
successful real query plans.** Firestore `not-in` and Postgres `state <>
ALL(...)` exclude missing/null state; this is a known ON property, now
mirrored in the simulator. OFF remains unchanged. Future unknown state
strings remain query-visible, but the enable census conservatively
rejects them too.

From a checkout, after selecting the read-only GCP tier on this host:

```bash
source ~/.local/bin/gcp-agent-env.sh ro-prod
cd backend
.venv/bin/python -m scripts.batch_pipeline_poll_state_census --project based-hardware
```

The tool covers both `batch_pipeline_prod_jobs` and
`batch_pipeline_dev_jobs`. Per collection, at one read-only transaction
snapshot, it computes aggregate `COUNT(merge_pending == true) -
COUNT(merge_pending == true AND state in KNOWN_STATES)`. It never
fetches job documents or writes them. KNOWN_STATES is the full 14-state
batch/provider lifecycle inventory, tied to the lifecycle
declarations/provider constants by test. Counts are summed into exactly
one `PASS (0)` / `FAIL (n)` stdout line, with exit status 0/1;
API/permission/index errors propagate nonzero and cannot pass the gate.
No production census was run in this PR: the flag must remain OFF
pending that evidence. Record a fresh PASS for the target project
immediately before enabling; a nonzero result requires investigation,
never an automatic backfill.


All ASC, COLLECTION scope, for both batch_pipeline_prod_jobs and
batch_pipeline_dev_jobs:

- `{stage}_batch_fresh_pending_nonterminal`: `(owner_key, merge_pending,
fresh_capture, capture_at, segment_id, state, __name__)`.
- `{stage}_batch_pending_nonterminal`: `(owner_key, merge_pending,
capture_at, segment_id, state, __name__)`.

Firestore supplies implicit inequality ordering after the explicit
capture/segment order in the locally tested shape; verify the real
planner before enabling. Declarations are in batch_pipeline_indexes.py
with generated firestore.indexes.json. No dependency on merge_ready is
introduced by the final ON shape. The runtime query-driver matrix
exercises both flag modes and the explicit held-owner bypass.

## Gates, ramp, kill switch and rollback

Terminal loss = 0. held_oldest, new_over_sla and summary SLA flat. This
caller's reads per admitted audio-hour must decrease (target at least
30% for fresh_pending + first_pending in a matched settled 24h window,
unchanged denominator) before expansion. Validate D+2 settled Firestore
read SKU, index-entry charges and net dollars; if it cannot meet the
gate, keep OFF and retire/re-scope it.

The sole new flag is BATCH_HELD_POLL_SKIP_ENABLED, default OFF, named in
the registry and budget. It lets us delete no existing flag. Rollback:
flag OFF/false or unset restores the prior query/read sequence without
reverting code or migrating data.

Owner firestore-lead owns any separately approved ramp: synthetic/local
proof, census PASS (0), all four indexes READY and successful real query
plans, integration first, then workers/remaining callers only after
clean correctness/SLA windows and D+2 cost validation. Target
decision/expansion by 2026-11-18; unmet prerequisites or benefit keep it
OFF and are reported by that date. No deploy or enablement is authorized
by this PR.

Phase 2: held retry/get/record-pending reductions require a separate
design for optional decision fields, time-dependent holds and legacy
documents. No held exclusion or backfill is bundled here.

## Validation

All heavy commands run through bin/omi-heavy. Touched
unit/index/query/flag checks: 760 tests pass. Full conformance with
OMI_REQUIRE_STORE_BACKENDS=all passes 195 tests with 6 skips per run,
both flag OFF and ON, against simulator, local Firestore emulator and
local PostgreSQL. Four skips are existing backend-inapplicable cases;
two are the new aggregate API test's non-Firestore adapters. New cases
prove absent/null pending rows stay visible OFF and disappear ON without
writes. The emulator census test covers all known states,
missing/null/unknown pending rows and nonpending exclusions; it rejects
document-read RPCs and any write-bearing commit. CLI tests cover both
collections, exact PASS/FAIL output and exit status. The local
empty-emulator CLI prints `PASS (0)`; this is not production enable
evidence.

Read-only production planning check at 2026-11-11T00:51:27+00:00: both
ON shapes returned `FailedPrecondition: no matching index found` (not
InvalidArgument). `ExplainOptions(analyze=False)` was explicit, so the
requests did not execute over job documents. The missing indexes must be
built and a successful plan verified before enabling.

The local emulator also verifies not-in ordering with an earliest
`zz_future` head before a later `result_ready` row, for both
first_pending and fresh_pending. OFF sequence and ON fallback tests keep
the exact stream transaction binding. Query-shape/index guards passed,
and all 43 selected preflight checks passed. The final push hook also
runs the bounded unit, type-check and guard contract.

No production document reads or writes, schema change or backfill. The
only production API use was read-only planning metadata with
`ExplainOptions(analyze=False)` and a synthetic owner predicate.
Outside-tests churn: 300 lines (cap 300).

CI for this current head is tracked in the [live
checks](https://github.com/BasedHardware/omi/pull/25077/checks). #25083
is merged and included through current main; no known shard-5 exemption
remains.

## Product invariants affected

none

Failure-Class: none

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant