Skip to content

fix(batch): promote an owner's due retry merge heads instead of waiting for global recovery - #25675

Merged
kodjima33 merged 7 commits into
mainfrom
fix/merge-promote-stale-retry-heads
Nov 18, 2026
Merged

kodjima33 merged 7 commits into
mainfrom
fix/merge-promote-stale-retry-heads

Conversation

@kodjima33

@kodjima33 kodjima33 commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

What changed and why

Problem. About 80% of sealed recordings wait the full 60 s merge head wait before they commit. The owner's merge head is a retry job that is days past its available_at and never re-runs. #25673 skips the wait for allowlisted uids. This PR fixes why the head never moves, for every owner.

Root cause. A due retry job rejoins the scheduler only through Scheduler.recover. It takes the oldest-due page of 100 per pass (database/batch_pipeline_store.py:870, called from utils/batch_pipeline/serving.py:394 and the GPU pump). That single FIFO is 94 h behind:

Prod, read-only, 2026-11-18 08:40–08:50Z Value
jobs in retry / already due 1,100,972 / 1,076,409
jobs in ready / leased 58 / 43
oldest due row, overdue 93.8 h
front advance (available_at s per real s) ~1.2, about 3 rows/s
time for the front to catch up at that rate ~20 days
due rows that are held / allowance_exhausted (samples at 1, 6, 24, 48, 72, 90 h depth) ~95%

The allowance holds cycle. The prod GPU worker runs image ef42ee8 (2026-11-14), which predates allowance parking (59f1edf138). So its pump leader requeues the oldest page every 5 s without parking, workers refuse admission again, and defer puts each row back for 2 h. A 100-row page snapshot fully turned over in 32 s: 91 rows were re-deferred allowance holds, 5 ran, 4 were requeued.

Entitled retries wait behind them. Of 126 owners whose rows were committed through the head-wait bypass in the last hour, 27 of 40 strict heads and 27 of 42 fresh heads were retry. 46 had compute allowed / entitled and were due 15–91 h earlier, untouched since 2026-11-14…17. The canary account has 75 such rows, due about 79 h ago.

Fix. OrderedMerge.commit_next remembers any retry row it reads as the owner's strict head (first_pending) or fresh head (fresh_first_pending). When one is promotable and the strict and tx-fresh attempts committed nothing, it promotes that row, plus the owner's promotable rows from the existing fresh-pending page, before the probe and head wait. No new query or index. Kill switch BATCH_PIPELINE_MERGE_STALE_HEAD_PROMOTE_ENABLED, default on.

Only rows whose next attempt is bounded are promotable:

  • Worker-failure or lease-expiry retries. Latest decision allowed, unattempted, or none with no refusal streak. Another failure charges an attempt.
  • Parkable allowance holds. held / allowance_exhausted with parking on.

Non-allowance policy holds (fair use, budget) and unevaluated refusals are not promoted. Scheduler.defer refunds their attempt, so promoting them could cycle. They stay with recovery and the head-wait bypass exactly as today.

Each promotion re-reads the row in its own transaction. The row must exist, be the owner's, be merge_pending, be a due promotable retry, and have fewer than 3 promotions. Then:

  • an allowance hold parks (allowance_held, merge_pending=false) and stops blocking the owner;
  • any other row returns to ready through scheduler.requeue_due_retry, the transition recover uses;
  • a commit-boundary BatchPrivacyBlocked gets recovery's disposition, store.quarantine_fenced.

A requeued row's service class drops by capture age, the way record intake classifies (capture_age_priority: FRESH ≤ 10 min, RECENT ≤ 7 days, else DEEP), and never rises. A days-old head therefore cannot outrank a live capture in the FRESH ring. The admission value is kept as admitted_priority, and both identity checks compare against it (enqueue_in_transaction, provider admission). An idempotent re-admission still matches, and different work is still refused.

Protected-share eligibility is not consulted. Recovery's ordinary oldest-due page doesn't consult it either; it is a plain requeue, and the lease still applies admission.

Bounds.

  • 8 rows per merge call.
  • A process-wide token bucket of 2 promotions/s, burst 16, shared by every drain (at most 7,200 per process-hour).
  • 3 promotions per row, counted in stale_head_promotions.
  • Owners continued after a bound sit in an LRU of 1,024 that expires after 600 s.

Bounded exit, stated precisely. Every promotion either completes, or charges an attempt on a worker failure, or meets an admission refusal that makes the row unpromotable. After 3 promotions recovery and the head wait own the row again, as before this PR. Worker failures still quarantine at max_attempts (5), which clears merge_pending and uses the existing held-recovery presentation. Policy-held rows are not made terminal by this PR; they keep today's behavior (recovery plus the 60 s bypass). No audio, result or obligation is dropped.

Expected effect. Once an owner's stale prefix commits or parks, a new recording no longer meets an unready head. It commits on the next drain instead of after 60 s. That is about 45–55 s off the p50 merge stage for ~80% of recordings, for every owner, after a backend roll only (estimate). For a 1-unit recording, the first drain after deploy still waits up to the existing 60 s while the promoted head runs. Owners whose head is a policy hold keep today's 60 s bypass. #25673 (allowlist skip) is now on main. The two compose: promotion runs first, and #25673's skip still passes a promoted head for listed owners, since requeue keeps available_at. test_batch_pipeline_merge_stale_head.py now pins the combined sequence, plus the skip with promotion off.

Problem B (seal → intake claim tail): measured, not changed here. Grouped by seal hour (unit jobs' record_sealed_at and record_intake_claimed_at):

Sealed (UTC) < 15 s 5–15 min > 15 min
11-17 19Z–01Z (per hour) 35–43% 37–49% 11–20%
11-18 02Z–04Z 49–61% 20–23% 7–20%
11-18 05Z 77% 11% 2%
11-18 06Z–09Z 92–97% 0–1% 0–1%

In the bad window (20Z–00Z, 5,703 recordings) the gap is bimodal: 38% under 1 min, then a sharp onset at 5–7 min (1,314 recordings) that decays to 15 min, plus 12% beyond 20 min. Recording length is the same in the fast and slow groups (24% vs 23% over 10 min; 1.4% vs 1.0% over 2 h). So the 2 h prepare_native_wake window (database/record_seal_wake.py:16) and the 900 s barrier backoff for rows older than 10 min (config/record_drain.py:64) do not explain the 5-minute floor. The tail faded from 02Z without a pusher roll or an intake code change; backend-integration had only the config-only 7d7e0cc at 04:25Z. Today the record drain takes full 100-row pages (p50 16 s, p90 45 s per pass). About 1,900 record_pending rows from 1–14 days ago fail admission (retained_capture_not_durable_yet etc.) and are retried every 60 s, but a due seal is claimed within one page turn (~100 s). With nothing to verify against now, no B change ships here. The next step is to log the seal-wake outcome (prepare_native_wake refused vs applied) so the next occurrence is attributable.

Product invariants affected

none

How it was verified

  • backend/tests/unit/test_batch_pipeline_merge_stale_retry_head.py (29):
    • promote and commit in order without bypass; backoff respected; allowance park frees the owner inside the head wait;
    • parking off → not promoted;
    • fair-use, budget and unevaluated refusals → not promoted, no repeat fresh_pending reads, bypass unchanged;
    • per-row bound of 3, then recovery quarantines at attempt 5;
    • 8-per-call pages; token bucket limits repeated calls in one drain and the owner resumes; bucket refill;
    • LRU cap and TTL on continued owners;
    • demotion by age (5 min stays FRESH, 2 h and 6 d go RECENT, 8 d goes DEEP) with the queue ring and admitted_priority checked; same-work re-admission returns False, different work still raises; DEEP is never raised;
    • stale hint where the row was leased or parked after the read → store unchanged;
    • deleted job and merge_pending=False → no-op; another owner's row never promoted;
    • BatchPrivacyBlocked → quarantine_fenced, logged action=privacy_fenced, no retry loop;
    • a failed promotion leaves the row to recover;
    • kill switch false/off/0 → promotion never runs, no extra reads, the 60 s bypass commits as before.
  • New emulator proof backend/scripts/merge_stale_head_emulator_test.py, registered in run-emulator-proofs.sh and run by the Backend emulator proofs job:
    • covers promotion and in-order commit, a stale hint after another lease, the privacy fence (deleted conversation → privacy_blocked), a missing job, and demotion with identity kept;
    • uses the real FirestoreStore transactions;
    • local run on sim + Firestore emulator: 10 passed (Postgres skipped).
  • Identity checks: scheduler.enqueue_in_transaction and provider_stt_admission compare stored_identity(previous), which is the stored row with admitted_priority substituted when present.
  • config/record_drain.py: record_intake_priority now delegates to the shared capture_age_priority, with the same thresholds.
  • Kill switch registered in config/policy/kill_switches.py, config/feature-flags.yaml (ops_kill), backend/config/flag_budget.json, test_flag_budget.py, and the rendered feature-flag-registry.md. check_feature_flag_registry.py: OK. No runtime-env binding, matching the sibling BATCH_PIPELINE_MERGE_TX_FRESH_GATE_ENABLED.
  • tests/support/lifecycle_writer_inventory.py: the state='ready' site moves from Scheduler._recover.recover_page.commit to requeue_due_retry.
  • test_record_seal_latency.py: two assertions after its blocked drain (the due older head is requeued).
  • Neighbouring suites pass on the tree merged with main (59 files, including perf(merge): skip the 60 s head wait behind starved merge heads (uid-allowlist canary) #25673's test_batch_pipeline_merge_stale_head.py): merge, scheduler, allowance, serving, pump, owner chain, lifecycle writers/invariants, pipeline sims, provider admission, record drain, flag budget, deploy contract.
  • backend/scripts/typecheck.sh: 0 errors (run with NODE_OPTIONS=--max-old-space-size=8192; the default heap crashes pyright with exit 241).
  • Prod evidence came from read-only Firestore REST and read-only gcloud/kubectl. No prod writes, env or flag changes.
  • Not verified: a live run. That needs the backend roll.

Review fixes (Sonnet review of 7f25004, NO-SHIP)

  1. Privacy-fenced head: BatchPrivacyBlocked is caught separately and calls store.quarantine_fenced, like recover_page. Unit and emulator tests cover it.
  2. a) Kill switch above. b) Promoted rows are demoted by capture age, with identity-safe admitted_priority. c) Refunded-attempt holds are never promoted; the bounded-exit claim above is restated.
  3. Process token bucket (2/s, burst 16) and an LRU/TTL bound on continued owners.
  4. A deleted job returns None. Protected-share eligibility is not applied; why that is OK is stated above.
  5. Tests listed above, including the real Firestore transaction path on the emulator.

Data repair (proposal only, not run)

  1. Roll the GPU worker image to current main (allowance parking in defer and pump recover). This stops the 2 h refusal loop that keeps refilling the FIFO.
  2. Run the existing allowance-parking migration per backend/docs/runbooks/batch-allowance-parking.md (dry-run first, --concurrency 32 --max-rows-per-second 50). It parks the ~1.0M due allowance holds. At the measured 1.16 rows/s sequential baseline it takes 12.6 days; concurrency is the lever.
  3. With this PR live, owners' entitled heads clear on their next recording. No per-owner repair is needed.

UI evidence

UI-Evidence: none -- backend merge scheduling only

Failure class (fixes)

Failure-Class: FC-batch-fault-domain-head-of-line-poison

🤖 Generated with Claude Code

…ng for global recovery

Due retries rejoin the scheduler only through Scheduler.recover, oldest-due
100 per pass. In prod that FIFO is 94 h behind 1.07M due rows (95% allowance
holds cycling through the pre-parking GPU worker), so an owner's retry head
was never re-run and held every new recording for the full 60 s head wait.

OrderedMerge now promotes a due retry row it reads at the owner's strict or
fresh head, plus the owner's due fresh-page retries (8 per call), through the
transition recover already uses (shared as scheduler.requeue_due_retry):
allowance holds park and stop blocking; other rows rejoin DRR and run.

Failure-Class: FC-batch-fault-domain-head-of-line-poison
…tale rows out of it

Review of #25675 (NO-SHIP):
- BatchPrivacyBlocked during promotion now takes recovery's disposition
  (store.quarantine_fenced) instead of retrying every drain.
- Kill switch BATCH_PIPELINE_MERGE_STALE_HEAD_PROMOTE_ENABLED (ops kill,
  default on); false restores waiting for recovery.
- Requeued rows drop to their capture-age service class; the admission
  priority is kept as admitted_priority for both identity checks.
- Non-allowance policy holds and unevaluated refusals (refunded attempts)
  are never promoted; 3 promotions per row at most.
- Process token bucket (2/s, burst 16) and an LRU/TTL bound on continued
  owners; a deleted job is a no-op.
- Emulator proof scripts/merge_stale_head_emulator_test.py on real
  FirestoreStore transactions, registered in run-emulator-proofs.sh.

Failure-Class: FC-batch-fault-domain-head-of-line-poison
…le-retry-heads

# Conflicts:
#	backend/config/flag_budget.json
#	backend/docs/feature-flag-registry.md
…spatch; skip the probe read on a spent budget

A demoted row's stored priority no longer moves its speech charge to the backfill
bucket or its notes to the backfill dispatch. A spent process budget skips the
fresh-pending probe and keeps the owner marked. An unapplied privacy fence is not
counted. The change note covers mixed-version rollback and the parked-head wake.
…le-retry-heads

# Conflicts:
#	backend/docs/feature-flag-registry.md
@kodjima33
kodjima33 merged commit 6176fb3 into main Nov 18, 2026
62 of 63 checks passed
@kodjima33
kodjima33 deleted the fix/merge-promote-stale-retry-heads branch November 18, 2026 11:52
Git-on-my-level added a commit that referenced this pull request Nov 20, 2026
## What changed and why

Quarantine recovery re-reads only the mismatched retained source, once,
under the same privacy and generation fences. Both reads must disagree
with the manifest's SHA-256 of decoded PCM before recovery commits
`failed_held` with `retained_digest_changed`. The successful CAS emits
the bounded `omi_fallback_total` reason; the task receives 200 and
duplicate deliveries and automatic redrive do not retry the source. A
matching confirmation resumes ordinary recovery. Storage outages,
missing inputs, invalid manifests, and switched-off target 409s keep
their existing paths.

The SHA-256 check, custody, expiry/deletion policy, and reviewed
operator redrive are unchanged. Set
`BATCH_PIPELINE_RETAINED_DIGEST_HOLD_ENABLED=false` to restore the
legacy single-read 500 for new mismatches without altering existing held
rows. Recovery, merge, projection, expiry, and metrics readers are
listed in `backend/utils/batch_pipeline/CONTRACT.md`.

State exit: retained_digest_changed is a refusal reason on the existing
terminal failed_held state. Normal retained dead-letter expiry still
applies, and only a reviewed operator redrive can requeue the row.

### Cause evidence

An offline native-Opus probe reproduced the exact digest failure with
identical object bytes and generation. Admission's
`source_metadata=True` read used the frame table to skip a zero-sample
diagnostic packet; recovery used the plain decoder, which decoded that
packet. The asymmetric branch arrived in #25045, before #25675. A
rewrite to a different generation cannot satisfy the pinned read. This
proves a decoder path can cause the error without a rewrite; it does not
identify the affected production cohort or establish the rollout
trigger. This change does not alter decoder selection or regenerate
manifests.

## Product invariants affected

none

## How it was verified

- M1, Python 3.11: `env PYTHON=.venv/bin/python bash test-preflight.sh`
passed all 18 checks.
- M1, `BACKEND_PYTEST_WORKERS=2 bash test.sh` with 10 selected unit
files: digest, invalid/missing inputs, artifacts, serving, held
dead-letter, projection exception taxonomy, pipeline sim, flag budget,
and quarantine recovery. All selected files passed after rerunning the
three affected fixture/flag files.
- Held-custody, recovery-admission, and recovery-custody conformance:
112 simulator cases passed; 56 Firestore emulator cases skipped because
no loopback emulator was running.
- `make preflight` passed all 44 checks; the offline native-Opus decoder
probe passed.
- Not verified: the post-deploy one-hour error window. No production
reads, writes, merges, or deploys for this PR.

## Tests

`backend/tests/unit/test_batch_pipeline_retained_digest_hold.py`
exercises the real FastAPI handler, manifest materialization, and
recovery transactions with synthetic pinned reads. It covers confirmed
mismatch, delivery replay, transient mismatch, read outage, rollback,
stale intent, changed URI, privacy revocation, and automatic versus
reviewed redrive.

## UI evidence

UI-Evidence: none -- backend recovery only

## Failure class (fixes)

Failure-Class: FC-batch-fault-domain-head-of-line-poison


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/25761?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/25761?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25761&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. -->
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