Skip to content

perf(merge): skip the 60 s head wait behind starved merge heads (uid-allowlist canary) - #25673

Merged
kodjima33 merged 5 commits into
mainfrom
perf/merge-stale-head-skip
Nov 18, 2026
Merged

kodjima33 merged 5 commits into
mainfrom
perf/merge-stale-head-skip

Conversation

@kodjima33

@kodjima33 kodjima33 commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

What changed and why

Problem. A pendant recording should show its transcript and summary on Home within 60 s of the seal. In prod it takes minutes. The largest p50 stage after the seal is not the GPU. It is the ordered merge: 80% of recordings wait the full 60 s BATCH_PIPELINE_MERGE_HEAD_WAIT_SECONDS behind a starved head. That head is a days-old retry job, and the existing bypass then commits the same row 60 s late.

Change. Owners listed in the new BATCH_PIPELINE_MERGE_STALE_HEAD_UID_ALLOWLIST (default empty) skip the head wait when it is waiting only on starved rows. A starved row was admitted at least 1,800 s ago and has waited that long for a lease: ready/retry with available_at at least 1,800 s in the past, or leased with lease_until at least 1,800 s in the past. Every lease-ending path (_defer, admission hold, missing-input repair, held requeue, redrive, quarantine) resets lease_until to 0 and stamps available_at, so a row that failed seconds ago, or is due again in seconds, is not starved. The skip commits exactly the row the expired wait would commit (the owner's earliest ready pending row) through the same transaction body. Inside that transaction it also requires:

  • the row is a native record unit whose earlier binding units are settled;
  • every pending row captured before it is starved. A new bounded pending_page read (129 rows, first_pending's filters, order and index, on every store backend) checks this; a longer backlog refuses.

A refused skip returns before the catch-up hold and the backlog-release fallback. Without the early return, a provider-route record candidate could set held['backlog'] and the tx-fresh fallback would run before 60 s; with it, that fallback is unreachable from a skip. A skip logs event=batch_merge outcome=stale_head_skip (head state + wait bucket) and does not write head_wait_bypass, so the bypass field and log stay real expiries only. Unchanged:

  • unlisted owners
  • head wait off
  • non-record rows
  • any unready row ahead that is in flight, recently leased, younger than 30 min, or in another state (record_pending, held)

Stage budget, seal to Home summary (prod, read-only)

Sample: 600 random batch_live_v1 rows with record_sealed_at, sealed 45 min to 8 h before 2026-11-18 07:50Z, out of 6,730 eligible. 432 had every unit committed. Per recording, the critical path is the last unit to commit. Units per recording: p50 1, p75 2, p90 5.

Stage p50 s p75 s p90 s Note
seal -> intake claimed 8 396 732 bimodal: 56% < 15 s, 36% wait 5-15+ min
claimed -> staged/admitted 6 9 19
admitted -> GPU result (queue + compute) 9 21 62 GPU is not the bottleneck
GPU result -> committed (ordered merge) 62 137 372 346/432 via head-wait bypass: p50 67 s single-unit, 98 s multi-unit. Without bypass: 0.1 s
committed -> persisted (projection discovery) 21 33 43
persisted -> ledger transcribed (follow-up/completion) 37 62 99 33 s single-unit (eager wake), 46 s multi-unit
transcribed -> summary_completed_at (notes) 38 58 93 Luna conv_structure
seal -> summary_completed_at, end to end (n=235) 452 708 1,496

Sum of p50 stages on the fast-claim path: about 181 s.

Root cause of the merge stage. For 20 of 20 sampled bypassed owners, the earliest pending fresh-class row is a native record job in retry, captured 36-215 h ago and due long ago (available_at in the past). fresh_capture is fixed at admission. The tx-fresh gate and _fresh_pick therefore treat these rows as fresh heads, and every new recording waits out the full 60 s. The canary account (viUv7G...) has this shape: a 78.6 h-old catch-up retry head, with fresh-class retry stock from 84 h ago behind it.

Ranked cuts (expected p50 seconds saved for the seal -> summary path)

  1. Stale-head skip (this PR). Saves 45-55 s on ~80% of recordings. All 75 of the canary owner's rows ahead are starved under this rule: retry, due 10.3-90.3 h, unleased (53 at attempt 1, 22 at attempt 0, so an attempt == 0 rule would exclude most of them). They fit inside the 129-row page. Sampled owners had 8-134. Low risk: same rows and outcome as today's bypass, 60 s sooner, allowlist-scoped. After a CPU roll the commit lands on the next serving tick (10 s on prod backend-integration). After a GPU worker roll it lands at publication, saving about 60 s.
  2. Persisted -> transcribed completion. Saves 20-35 s. Low-medium risk, small to medium effort. RECORD_FOLLOWUP_WAKE_ENABLED covers only single-unit records (projection.py:1627), and even single-unit takes 33 s. Extending the eager wake to multipart, and finding the single-unit delay, comes next.
  3. Post-commit projection wake (committed -> persisted). Saves 15-20 s. Medium effort. The GPU pump commits directly with no on_committed hook, so this needs a GPU image roll.
  4. Intake-claim tail. p50 unchanged, p75 about -380 s. Medium risk and effort. 36% of seals wait 5-15+ min for the record_pending claim. Needs diagnosis: record-drain capacity (10 rows per pass) vs ~1,200 seals/h, or barrier refusals.
  5. Starved fresh-class retry heads themselves. Same seconds as cut 1, for every owner. Medium effort. This is a scheduler question: why due FRESH retry rows go unleased for days. Fixing it removes the need for cut 1's allowlist.
  6. Notes model time. At most 5-15 s, with quality risk. Luna one-shot; the fleet notes histogram is ~25 s model time. Needs a quality eval before any model or prompt change. Not recommended now.
  7. Staged cuts, no gain now.
    • RECORD_FRESH_MERGE_ENABLED (cut 4): its blocker is unresolved. The prod GPU worker image tag is ef42ee8 (2026-11-14), which predates the sibling guard a0a8816. It would also not help here, because the stale heads are already fresh-class.
    • RECORD_NOTES_EAGER_ENABLED (cut 2): superseded by fix(notes): first summary as soon as a sealed recording's transcript lands #25635, which already moves the notes obligation to due-now at completion. The lease-off producer revision blocker is still open.
  8. Pre-seal admission of completed units. Saves at most ~25 s (admission + GPU = 15 + 9 s p50). Very high custody risk: the seal barrier is the admission contract (require_record_audio_barrier). Not recommended.

What remains to reach 60 s p50. After cut 1 (with a GPU roll), the fast path is about 8 + 6 + 9 + ~1 + 21 + 37 + 38 ≈ 120 s. Cuts 2 and 3 bring it to about 65-75 s. The rest has to come from notes (cut 6) or claim/staging. The intake-claim tail (cut 4) dominates p75 and must be fixed for a p75 target.

Related. #25633 (120 s speech-quiet seal) and #25635 (first summary when the sealed transcript lands) are live. #25601 and #25623 (David) work on stuck projection chains/heads; they touch no file here. The staged cuts and the 60 s head wait are documented in 2026-11-14-record-post-seal-latency.md.

How to canary and roll back

  • Canary for one account. Set on prod Cloud Run backend-integration (the serving loop host, BATCH_PIPELINE_SERVING_ENABLED=true): BATCH_PIPELINE_MERGE_STALE_HEAD_UID_ALLOWLIST=viUv7GtdoHXbK1UBCDlPuTDuPgJ2. This PR deliberately adds no runtime-env overlay entry: put it in the backend-integration section of backend/deploy/runtime_env/prod.overlay.yaml as part of the canary change, so the next deploy keeps it. The backend image must contain this PR. config/deployment-setting-classification.json classifies the variable as config. The GPU worker needs nothing; adding the same env there after its next image roll moves the commit to publication time.
  • Readback. A skip leaves no durable marker, so readback relies on the event=batch_merge outcome=stale_head_skip log line. On the canary account's next recordings, committed_at - ready_at of the last unit should drop from ~60-100 s to ≤ ~10 s, with no late_capture within a recording.
  • Rollback. Remove the uid or unset the env. No migration; committed rows keep their order.

Product invariants affected

none

How it was verified

  • Prod measurement used read-only Firestore (collection-group conversations query on record_lane_owner/status/finished_at, joined to batch_pipeline_prod_jobs and _results and to pipeline_ledger) and read-only kubectl/gcloud describes. No prod writes, env or flag changes.
  • pytest tests/unit/test_batch_pipeline_merge_stale_head.py: 32 passed. Jobstore SQL safety plus protocol parity: 210 passed.
  • 94 directly affected test files pass locally: merge, jobstore, parity, scheduler, transaction-attempt, pipeline sims, all Firestore query/index guards, test_flag_budget.py and test_record_seal_latency.py. CI runs the full 1,260-file selection.
  • Existing merge suites unchanged and passing:
    • test_batch_pipeline_merge_head_wait.py (177)
    • test_batch_pipeline_merge_fresh_first.py (59)
    • test_batch_pipeline_merge_tx_fresh_gate.py (24)
    • test_record_seal_latency.py (58)
    • test_batch_provider_merge_membership.py (46)
    • test_batch_terminal_poll_skip.py (42)
    • test_batch_backlog_release.py (57)
    • the recovered-release suites and the head-wait sims
  • All 24 changed-file-selected unit test files pass, including test_flag_budget.py, test_pipeline_sim*, test_lifecycle_invariants.py and test_cross_service_deploy_contract.py.
  • backend/scripts/typecheck.sh: 0 errors. make preflight: 43 checks passed. scripts/check_feature_flag_registry.py: OK.
  • Not verified: a live canary. That requires the backend roll and env change, which belong to the parent.

Tests

backend/tests/unit/test_batch_pipeline_merge_stale_head.py (32 cases) covers:

  • a listed owner commits at once behind a starved head, with its own log and no head_wait_bypass; an expired wait keeps the bypass marker
  • realistic heads that are not starved keep the wait: in flight; the reviewer's lease-expired retry due again in 10 s (lease_until=0, attempt=1); a retry that failed 10 min ago; a row redriven a minute ago; record_pending; held
  • a prod-shaped retry due for 10 h without a lease is starved and skips
  • a head deferred between the probe and the transaction keeps the wait
  • a young, leased recording captured earlier blocks the skip; both then commit in capture order
  • a refused skip of a backlog-held (provider) unit commits nothing, adds no held owner and runs no early fallback transaction before 60 s
  • the 129-row page bound: 128 starved rows ahead skip, 129 refuse
  • unset, empty or other-uid allowlists keep the 60 s wait
  • head wait off keeps strict order
  • an unready earlier unit of the same recording waits
  • non-record rows keep the wait
  • the prod shape (catch-up head plus fresh-class stock), with the tx fresh gate on and off
  • exact allowlist parsing

Mutation check: restoring the old lease_until-only rule fails 4 of these tests, and removing the early return fails the backlog test.

test_jobstore_sql_safety.py adds pending_page_in binding and limit-cap coverage. test_jobstore_protocol_parity.py checks that every backend serves pending_page, and the Firestore query-shape registry drives the new query.

UI evidence

UI-Evidence: none -- backend merge scheduling only

Failure class (fixes)

Failure-Class: none

🤖 Generated with Claude Code

…listed owners

Prod 2026-11-18: 80% of sealed batch_live_v1 recordings committed their last
unit through the 60 s head-wait bypass, behind days-old fresh-class retry heads.
For owners in BATCH_PIPELINE_MERGE_STALE_HEAD_UID_ALLOWLIST (default empty), a
head unready 30+ minutes after admission no longer gates a ready native record
unit whose earlier units are settled. Same commit body and outcome as the
expired wait; everyone else is unchanged.
Review fixes for the stale-head skip. The transaction now reads a bounded
page (129) of the owner's pending rows, with first_pending's shape on every
store backend, and refuses unless every row captured before the committing
row is waiting for a lease, admitted 30+ minutes ago and unleased for 30+
minutes. A refused skip returns before any hold or backlog fallback. A skip
logs outcome=stale_head_skip and no longer writes head_wait_bypass. The
allowlist is classified as deployment config; docs deduplicated.
Every lease-ending path resets lease_until to 0, so a head that failed
seconds ago looked starved. ready/retry rows now count as starved only
when available_at is 30+ minutes past (due that long without a lease);
leased rows keep the expired-lease check. Tests use realistic retry rows
and cover a refused skip of a backlog-held unit. The change note says the
skip leaves no durable marker.
@kodjima33
kodjima33 merged commit ac9f48f into main Nov 18, 2026
77 of 79 checks passed
@kodjima33
kodjima33 deleted the perf/merge-stale-head-skip branch November 18, 2026 09:55
kodjima33 added a commit that referenced this pull request Nov 18, 2026
…25679)

## What changed and why

Canary config for the stale-head merge skip from #25673 (merged as
`ac9f48fb2f`). `BATCH_PIPELINE_MERGE_STALE_HEAD_UID_ALLOWLIST` is bound
to one canary uid on every prod process that runs the ordered merge, so
the skip does not depend on which writer wins a commit.

| Prod process | Runs `OrderedMerge.commit_next`? | Env |
|---|---|---|
| Cloud Run `backend-integration` | Yes: the only host with
`BATCH_PIPELINE_SERVING_ENABLED=true` (10 s serving loop), the
quarantine-recovery task audience, and the provider-STT settle handler
URL | **set** (`prod.overlay.yaml`, composed `runtime_env.yaml`) |
| GKE `prod-omi-batch-pipeline-worker` + `-t4` (GPU pump) | Yes: commits
directly after each publication | **set**
(`prod_omi_batch-pipeline-worker_values.yaml`, rendered via a
`hasKey`-gated template line). Inert until the worker image rolls: the
live image `ef42ee8` predates the reader |
| Cloud Run `backend-sync` | No: serving off; the GPU worker only calls
`/v2/batch-pipeline/authorize-compute` here (admission, no merge) | not
set |
| Cloud Run `backend`, `backend-sync-backfill` | No: serving off, no
recovery or provider-STT callbacks | not set |
| GKE `backend-listen` | No: serving off | not set |
| GKE `record-seal-worker` | No merge path | not set (renders nothing) |

Live readback (2026-11-18, `gcloud run services describe`, `kubectl get
deploy`): `BATCH_PIPELINE_SERVING_ENABLED` is `true` only on
backend-integration, and `PROVIDER_STT_TASKS_HANDLER_URL` and
`BATCH_PIPELINE_RECOVERY_TASK_AUDIENCE` both point to
backend-integration. All four Cloud Run services run release
`c868729e55`, which predates `ac9f48fb2f`. The canary takes effect only
once backend-integration runs a release that contains #25673; before
that the env is ignored.

Both uid literals are recorded in
`backend/deploy/cross_service_known_gaps.json` as reviewed
`no-uid-literals` exceptions, following the existing referral-preview
exception. Each has a delete condition: remove the keys when the skip
ramps fleet-wide or at its 2026-12-18 review. Binding the GPU worker
also resolves the `reader-split` violation the cross-service contract
raised for a worker that reads the flag but leaves it unset.

Also adds the reviewer-suggested regression case: a `ready` row ahead of
the unit with an old `enqueued_at` but a recent `available_at` (requeued
a minute ago) refuses the skip. The head-position version of this case
already existed (`redriven`).

## Canary and rollback

- **Enable:** merge this PR, then run the normal backend deploy of a
release containing `ac9f48fb2f` and this PR. That rolls
backend-integration; the GPU worker picks the value up on its next chart
and image roll.
- **Readback:** `event=batch_merge outcome=stale_head_skip` log lines.
For the canary uid's next recordings, the last unit's `committed_at -
ready_at` drops from ~60-100 s to about one serving tick.
- **Rollback:** set the value to `''` (or delete both lines and both
known-gap keys) and redeploy. No migration.

## Product invariants affected

- INV-MEM-4: path-glob match only (`backend/deploy/runtime_env.yaml`).
No memory-promotion, consolidation or intake setting changes; the
composed file gains one merge-scheduling line for backend-integration.

## How it was verified

- `python3 backend/deploy/compose_runtime_env.py` then `--check`: up to
date. The composed value appears only at
`environments/prod/cloud_run/services/backend-integration/env`.
- `helm template` (prod and dev, deploy namespace): prod renders the env
on `prod-omi-batch-pipeline-worker` and
`prod-omi-batch-pipeline-worker-t4` only; `record-seal-worker` and dev
render nothing.
- `backend/scripts/cross_service_contract.py`: 0 new violations, 35
known gaps, 0 stale.
- `backend/scripts/pre-deploy-check.sh`: passed. Runtime env validation
passed for dev and prod; 632 contract tests passed.
- All 56 changed-file-selected unit test files pass, including
`test_cross_service_deploy_contract.py`, the runtime-env and flag-budget
suites, and the stale-head suite (33 passed). Mutation check: judging
`ready` rows by `lease_until` fails the new case.
- `make preflight`: feature-flag registry regenerated (the row now
renders the prod binding). `product-invariants` passes with this body.

## Tests


`backend/tests/unit/test_batch_pipeline_merge_stale_head.py::test_a_requeued_ready_row_ahead_of_the_unit_blocks_the_skip`.

## UI evidence

UI-Evidence: none -- deploy configuration only

## Failure class (fixes)

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/25679?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/25679?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25679&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. -->
kodjima33 added a commit that referenced this pull request Nov 18, 2026
…ng for global recovery (#25675)

## 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 #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](https://claude.com/claude-code)
Git-on-my-level added a commit that referenced this pull request Nov 18, 2026
…st (#25696)

* fix(deploy): omit the stale-head canary uid from the Cloud Run manifest

#25679 bound BATCH_PIPELINE_MERGE_STALE_HEAD_UID_ALLOWLIST as a literal in the
prod backend-integration overlay. test_rollout_cohort_deploy's contract is
that the Cloud Run manifest omits private uid bindings so deploys keep the
live value (gcloud preserves undeclared env), so main's backend unit suite
went red. Remove the literal and its known-gaps exception; the uid is bound
on the service at deploy time.

Unchanged: the test, #25673's skip code, #25679's regression case, and the
GPU worker Helm value. Helm is declarative, so omitting it there would drop
the canary on the next upgrade instead of preserving it; that literal keeps
its reviewed no-uid-literals exception.

Failure-Class: none
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(deploy): treat the stale-head canary uid as live-managed on backend-integration

Panel review-20261118t134925-d977: add the key to the drift report's
live-managed allowlist like the sibling canary uid allowlists (F4), and give
the surviving Helm exception its own removal condition now that the Cloud Run
key it pointed at is gone (F2).

Failure-Class: none
Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Nov 18, 2026
…parity and exact undo (#25686)

* feat(conversations-v3): per-owner backfill and repair runs with live parity and exact undo

Turn the v3 backfill into a reusable per-owner repair tool:

- Operator plans one owner + window (default 2 days) from an owners file;
  partitions cut at five-minute silences; run ledger with counts, code SHA
  and outcome; the sweep starts planned runs only when
  CONVERSATIONS_V3_BACKFILL=on; one step at a time on a dedicated
  conversations-v3-backfill queue.
- Derive passes hold their own backfill-builder lease and notes marker, so
  they never make the live builder busy or ride the live queue/sweep.
- Backfilled notes take the live CAPTURE_END path (relevance, speaker
  resolution, meeting context, live floors); process_conversation withholds
  only derived effects for v3 backfilled rows.
- Non-destructive conversion: legacy notes kept, prior field values recorded,
  undo restores donors exactly and removes derived rows; deleting a
  backfilled copy never arms the donor audio purge.
- Resume and re-derive reuse ids by adoption; legacy manual stops map to the
  v3 manual end; discarded/imported/private/unreadable rows stay legacy.

Failure-Class: FC-irreversible-terminal-hide

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(conversations-v3): backfill settle/resume edge cases from self-review

Count live-writer terminal failures as failed, keep a start-marker read error
from failing the live sweep, resume a run whose start marker was lost, and
rename the live backoff local that shadowed the window bound.

Failure-Class: FC-irreversible-terminal-hide

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* chore(conversations-v3): classify and register CONVERSATIONS_V3_BACKFILL_QUEUE

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(conversations-v3): narrow the backfill start run for the type checker

Failure-Class: FC-irreversible-terminal-hide

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* chore(conversations-v3): drop an unused loop index in the backfill operator

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(conversations-v3): keep StrictFirestore DELETE_FIELD semantics; bind historical in the hook harness

Revert the fixture change (other suites assert the stored sentinel) and compare
the restored donor as Firestore would store it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(conversations-v3): answer the backfill panel review

- A legacy row no derived window claims stays a visible legacy conversation
  (counted as sources_unclaimed) instead of being hidden with no replacement.
- Start markers move under users/{uid} so account deletion purges them; the
  sweep reads them with a bounded collection-group list.
- The operator refuses a new run while one is blocked; undo/resume exit 1
  when no listed owner has the run.
- A redelivered committed partition re-dispatches a lost successor (named
  task, so a duplicate is a no-op).
- Re-derive blocks (rederive_mixed_runs) rather than merge rows from two
  runs, keeping undo run-scoped.
- A refused undo records its reason; a drain stopped mid-way reports stopped.
- classify_window reports legacy_candidates; the cost model has a test;
  the runbook documents the row-level partition-gap caveat.

Failure-Class: FC-irreversible-terminal-hide

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(conversations-v3): pin the historical gate on owner-recognition telemetry

Backfilled v3 rows skip owner-recognition telemetry and capture-loss
accounting; legacy processing already observed the same speech.

Failure-Class: FC-irreversible-terminal-hide

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(conversations-v3): declare the backfill lifecycle payload sites

The run ledger's run/partition status, the re-derive reset of a prior
backfilled copy, and undo's donor restore are reviewed entries in the
lifecycle writer inventory (restore is a backfill-lease-fenced extra writer).

Failure-Class: FC-irreversible-terminal-hide

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(home): import home_feed at collection so the CPU guard measures the test

The file-isolated runner charged the cold database.home_feed import to the
first feed-read case's call phase, which crossed the 1.00s CPU guard on CI.

Failure-Class: FC-irreversible-terminal-hide

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(desktop): drop the retired /v2/agent out-of-scope prefix (main red after #25050)

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* config(conversations-v3): enable the operator-only backfill route on prod backend-sync

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(deploy): omit the stale-head canary uid from the Cloud Run manifest

#25679 bound BATCH_PIPELINE_MERGE_STALE_HEAD_UID_ALLOWLIST as a literal in the
prod backend-integration overlay. test_rollout_cohort_deploy's contract is
that the Cloud Run manifest omits private uid bindings so deploys keep the
live value (gcloud preserves undeclared env), so main's backend unit suite
went red. Remove the literal and its known-gaps exception; the uid is bound
on the service at deploy time.

Unchanged: the test, #25673's skip code, #25679's regression case, and the
GPU worker Helm value. Helm is declarative, so omitting it there would drop
the canary on the next upgrade instead of preserving it; that literal keeps
its reviewed no-uid-literals exception.

Failure-Class: none
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(conversations-v3): undo never resurrects a deletion; fence it with both builders

- A donor whose backfilled copy the owner deleted (a post-run deleted span, or
  no claim left) is kept converted, with every copy it shares and their donors;
  the restore transaction re-checks, and a deletion that races undo is kept.
- Undo holds the backfill and live builder leases before it enumerates the
  run, so no pass commits or stamps a row while it restores and deletes.
- A converted donor that no longer reads blocks the partition
  (backfill_source_unreadable) instead of retiring its only copy.
- undo on a re-derive run id names the original run and exits 1; the dry-run
  counts donors the owner deleted; classification splits not-completed rows.

Failure-Class: FC-irreversible-terminal-hide

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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