Skip to content

perf(batch): dark terminal-only merge poll skip - #25077

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

Git-on-my-level merged 3 commits into
mainfrom
lane/heldpollskip

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

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 sets true for GPU / false for assignment; held expiry explicitly sets true to retain legacy redrive; aged record-barrier expiry sets false.
privacy_blocked Firestore revoke preserves true for GPU leased/retry and clears it for provider states; Postgres revoke and sim revoke mirror that conditional.
quarantined quarantine_job, provider settle failure, provider terminal failure and artifact re-upload all set false.
committed ordered commit sets false. assignment projection release preserves false: its input-expiring terminal path requires the assignment leg, which input expiry made false.
partial_retired partial update_run preserves false: requires record_pending, whose creation and requeue both set false.
provider_superseded provider supersede 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 and quarantine set merge_pending=false and contribute zero absent corrupt/legacy rows. However held expiry deliberately writes dead + merge_pending=true, input expiry does so for the GPU leg, and GPU privacy fencing 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 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:

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. #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

Preserve held heads and fresh wait while filtering queue-dispositioned jobs from merge discovery. Keep oldest and SLA/watchdog scans unchanged.

Failure-Class: none
…l indexes

Exclude the explicit terminal union instead of maintaining a positive
nonterminal list. Keep capture order and unknown state strings visible.
Unavailable ON query/index shapes use the exact OFF query; OFF errors keep
propagating. Keep held-merge marker owner resolution on the OFF query.

Retained GPU dead letters and privacy fences can keep merge_pending=true;
ordinary commit/quarantine, provider supersede and retired records do not.
The possible saving is Firestore fresh_pending document reads only; the
limit-one first_pending floor and Postgres yield no direct read saving.

Declare capture-first negative-filter indexes for both probes and stages,
register the flag budget entry, and document authoritative merge/scheduler
behavior and the index/planning enable gates. Add ordered commit/redrive,
head-priority, unknown-state, terminal-complement, exact-SQL and fallback
coverage across the real store conformance implementations.

Failure-Class: none
Git-on-my-level added a commit that referenced this pull request Nov 11, 2026
… CI load (#25083)

The optional-load failure test can count two degraded fallbacks under CI
load: its intended summary-load exception plus a digest timeout. Both
reads are in-memory fakes, but the test still dispatches them through
real workers while `PREPARE_SECONDS=0.15` bounds both tasks. This
test-only change executes the fakes through a test-local async helper
and retains the assertion that exactly one degraded fallback is
produced. Production code, deadlines, and the separate timeout /
real-executor regressions are unchanged.

Current head: `7efee81725d9cfa31a72d7f663a0a21a5fe77800`.

The trigger is the deterministic LPT shard reshuffle when files are
added to the suite. Every test file runs in a separate pytest process,
so this is a pre-existing scheduling race rather than cross-file state
leakage. The CI trace contains `summary_load ValueError` followed by
`digest TimeoutError`, matching the `assert 2 == 1` failure. An isolated
diagnostic that delays only the digest worker by 200ms reproduces the
same failure before the change and passes afterward.

This independent fix unblocks #25077 and #25079. It adds no flags and
has no deploy or index prerequisite. Rollback is a normal revert of this
test-only commit.

Validation through `bin/omi-heavy`:

- The CI `backend/test.sh` runner, four workers and per-file process
isolation, passed 54 tests across `test_messaging_review_fixes.py`,
`test_shaped_context_prefetch_safety.py`, and
`test_shaped_chat_context.py`.
- All 11 messaging review tests pass with the diagnostic digest-worker
delay still injected.
- `OMI_PR_BODY_FILE=<body> make preflight` passed all 35 selected
checks.
- The same helper previously passed the exact 347-file shard-5 plan from
#25077's merge tree, with runner exit 0; that replay did not naturally
reproduce the messaging race on this host.

Commands from `backend/`:

```sh
~/workspace/omi-workspace/bin/omi-heavy run -- env BACKEND_UNIT_TEST_FILE_LIST=/tmp/firestore-lead-m1/msgflake-test-files.txt BACKEND_PYTEST_WORKERS=4 bash test.sh
~/workspace/omi-workspace/bin/omi-heavy run -- env PYTHONPATH=/tmp/firestore-lead-m1 .venv/bin/python -m pytest -p heldpoll_delayed_digest tests/unit/test_messaging_review_fixes.py -q
```

Only `backend/tests/unit/test_messaging_review_fixes.py` changes: 8
additions and 2 removals. The async helper and patches are scoped to
each parametrized invocation and restore automatically.

## Product invariants affected

none

Failure-Class: none

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/25083?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/25083?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25083&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. -->
Require aggregate-only PASS (0) before enabling either merge probe. Match missing/null state filtering in the simulator and cover all stores plus CLI and aggregate-only behavior. Integrate current main without rewriting published history.

Failure-Class: none
@Git-on-my-level
Git-on-my-level merged commit ea4ccbc into main Nov 11, 2026
76 of 78 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/heldpollskip branch November 11, 2026 02:21
MichaelC001 pushed a commit to MichaelC001/omi that referenced this pull request Nov 11, 2026
… CI load

Both mocked reads still used real workers under the shared 150ms prepare
budget. A delayed digest worker emits a second degraded fallback alongside
the intended summary-load exception, making len(notices) == 1 race CI load.

Use a test-local async helper to execute the in-memory reads directly and
retain the single-fallback assertion. Separate deadline and real-executor
regressions keep their existing behavior. Production code is unchanged.

Backend files run in separate processes. New files reshuffle the LPT shard
schedule and expose this pre-existing timing race; they do not leak state.
This independent test-only fix unblocks BasedHardware#25077 and BasedHardware#25079.

Failure-Class: none
Git-on-my-level added a commit that referenced this pull request Nov 11, 2026
…ons (#25089)

Reconcile `backend/config/flag_budget.json` count from 267 to 268 after
a semantic merge race between #25077 and the `lane/fabledebtstamp` merge
(#25032). Both lanes added a distinct flag on their own bases, leaving
both names present with a stale count.

Verified 268 unique names and no duplicate JSON keys.
`BATCH_HELD_POLL_SKIP_ENABLED` is read through
`config.batch_pipeline.held_poll_skip_enabled()` by the store adapters;
`SUMMARY_PROJECTION_DEBT_ENABLED` is read through
`projection_debt_enabled()` in
`utils/conversations/summary_delivery.py`. Both have owned registry
entries. Only `count` changes. ADR 0006's seeded/replacement budget
remains 161; owned exceptions are validated separately.

Validation: `/Users/david/workspace/omi-workspace/bin/omi-heavy run --
backend/.venv/bin/python -m pytest
backend/tests/unit/test_flag_budget.py -q`

```text
........................                                                 [100%]
24 passed in 0.62s
```

Current head: `1e8ad1fb9b0c2a801a93407fdbcbdc9ce9659aa1`

Product invariants affected: none (inventory metadata only).
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