Repository navigation
fix(batch): one outstanding quarantine-recovery wake per paid intent - #22458
Conversation
The recovery sweep named each wake task by a 120s time bucket, so every waiting unit got a new Cloud Tasks task every two minutes. During the 2026-10-19 5% re-qualification the batch-quarantine-recovery queue reached 363 tasks for 180 quarantines, and duplicates took slots from first deliveries. The sweep now leases one wake per prepared intent (recovery_wake on the job, default 600s) and names the task by intent token and wake sequence. While the lease is live the sweep reports `pending` and enqueues nothing. Expiry repairs a lost or exhausted task with the next sequence. A delivery that leaves the intent prepared re-arms a 120s wake. The wake claim runs through the same privacy/ownership check as prepare; RecoveryStore.start remains the only paid-intent fence. BATCH_PIPELINE_RECOVERY_WAKE_LEASE_SECONDS=0 restores the legacy bucketed wakes. Failure-Class: FC-event-wakes-bypass-request-cadence Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4d8f7dd4ae
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| def delivered(self, segment_id, outcome): | ||
| """A task delivery that left the intent prepared re-arms the legacy cadence.""" | ||
| if outcome == 'held' and recovery_wake_lease_seconds(): | ||
| self.protocol.shorten_wake(segment_id, self.clock(), REWAKE_AFTER_HELD_SECONDS) |
There was a problem hiding this comment.
Shorten only the wake that was actually delivered
When a wake is delayed past 600 seconds, a sweep may already have claimed and enqueued w2 before w1 finally delivers. If w1 then returns held (for example, because the allowance check refuses the start), this call has no delivered sequence and therefore shortens the lease stored for w2; after 120 seconds the sweep can enqueue w3 while w2 is still outstanding, recreating the duplicate queue pressure this change is intended to prevent. Carry the wake token/sequence in the task payload and shorten only the matching wake.
Useful? React with 👍 / 👎.
| Each prepared intent has at most one outstanding wake task: the sweep leases a | ||
| wake (`recovery_wake`, default 600s, `BATCH_PIPELINE_RECOVERY_WAKE_LEASE_SECONDS`) | ||
| and names the task by intent token and wake sequence, so a backlog no longer | ||
| adds a new task per unit on every sweep. An expired lease repairs an exhausted or | ||
| lost task with the next sequence; a delivery that leaves the intent prepared | ||
| re-arms a 120-second wake. `0` restores the legacy two-minute wake-name |
There was a problem hiding this comment.
Update the owning pipeline contract
This transcription-recovery change updates only the secondary diarizer runtime document, while backend/docs/listen_pusher_pipeline.mdx:5811-5813 still says wake names rotate every two minutes and omits the new lease flag. Operators following the owning pipeline contract therefore receive incorrect timing and rollback guidance; mirror the lease, sequence, expiry, and kill-switch behavior there.
AGENTS.md reference: backend/AGENTS.md:L159-L159
Useful? React with 👍 / 👎.
| outcome = await run_blocking(sync_executor, service.recovery.recover, body.segment_id, job['owner_id']) | ||
| if outcome == 'held': | ||
| try: | ||
| await run_blocking(db_executor, service.recovery.delivered, body.segment_id, outcome) | ||
| except Exception: | ||
| pass # The lease still expires; the sweep repairs the wake then. |
There was a problem hiding this comment.
Keep the simulator aligned with held-delivery rearming
The production handler now calls delivered() for a held outcome and shortens the wake lease from 600 seconds to 120 seconds, but the mirror in backend/testing/pipeline_sim/sim.py:415-426 still returns the outcome without this call. Consequently, held or allowance-refused units wait the full lease in every regenerated simulation golden, so the changed queue-depth, recovery-timing, and paid-call results do not represent deployed behavior. Update the simulator mirror before accepting the new goldens.
Useful? React with 👍 / 👎.
| def commit(tx): | ||
| job = tx.get('jobs', segment_id) | ||
| wake = job.get('recovery_wake') if job else None | ||
| if ( | ||
| not wake | ||
| or job.get('recovery_state') != 'prepared' | ||
| or wake.get('token') != job.get('recovery', {}).get('token') |
There was a problem hiding this comment.
Recheck the privacy fence when shortening a wake
If account deletion or a source tombstone is committed after recover() completes its earlier privacy check but before the handler invokes delivered(), this transaction reads and updates the job without calling checked() or assert_batch_write_allowed(). That permits a post-revocation batch-job mutation even though claim_wake() fences the equivalent scheduling write and the runtime contract says privacy fences apply to every delivery. Perform the privacy/content-ownership check in this same transaction and refuse or cancel the shortening when it is blocked.
Useful? React with 👍 / 👎.
…y fence Review and CI follow-ups for the one-outstanding-wake lease: - Shorten only the wake that was delivered. The handler reads the X-CloudTasks-TaskName header and passes its `-w<seq>` to `delivered()`; `shorten_wake` matches that sequence, so a late w1 delivery cannot cut the lease of an outstanding w2. Legacy or unnamed deliveries change nothing. - `shorten_wake` now runs `checked()`, the same privacy/ownership fence as claim_wake, so a revoked owner's job is never mutated. - A failed enqueue shortens only the wake it just claimed (moved into `_dispatch`), instead of trusting the full lease. - The sync Cloud Tasks stack harness accepted only numeric wake suffixes and rejected `-w<seq>` task names, which timed out the batch-empty-asr-recovery gauntlet scenario. It now accepts both forms and sends the task-name header like Cloud Tasks does. - The pipeline sim mirrors the handler's held re-arm (task id passed through the recorder). Regenerated goldens are byte-identical to the previous commit's, and the kill switch still reproduces main's goldens. - Document the lease in the owning contract, listen_pusher_pipeline.mdx. Failure-Class: FC-event-wakes-bypass-request-cadence Co-Authored-By: Claude Opus 5.5 <[email protected]>
Pyright rejected the optional Request default and a possibly-unbound wake sequence. The handler takes the injected Request as before; direct test callers pass a header-less stand-in. Failure-Class: FC-event-wakes-bypass-request-cadence Co-Authored-By: Claude Opus 5.5 <[email protected]>
Grok review (SCA-827) finding 1: lease expiry alone treated a task still waiting in a saturated queue (or inside its 1,500s dispatch window) as lost, so a backlog longer than the lease still duplicated wakes, on a 600s cadence instead of 120s. At expiry the sweep now probes the previous wake with named_task_exists (BASIC view, the primitive sync reprocess already uses on integration). - If the task exists, the lease is extended (`extend_wake`) and the sweep reports `pending`. - Only an authoritative NotFound mints the next sequence. - A failed probe also extends, and counts in `probe_errors`. After three consecutive failures the next wake is minted anyway, so a missing tasks.get permission cannot strand the intent. - `claim_wake` is a compare-and-set on the inspected sequence, so two sweepers cannot both advance an expired wake. The lease timestamp is now `wake_until`: the trace scrubber drops `*_until`, so goldens no longer carry an absolute epoch (Grok finding 3). The pipeline sim models task custody (a task exists until a delivery answers it). Regenerated goldens differ only in that field shape. The kill switch still reproduces main's goldens, and privacy_fence_midflight keeps 0 paid calls after the fence. Failure-Class: FC-event-wakes-bypass-request-cadence Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1079e8122e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| errors = wake.get('probe_errors', 0) + 1 if probe_error else 0 | ||
| job['recovery_wake'] = {**wake, 'wake_until': now + lease_seconds, 'probe_errors': errors} | ||
| tx.put('jobs', segment_id, job) |
There was a problem hiding this comment.
Preserve a concurrent held-delivery shortening
When an expired wake is still present because its handler is concurrently finishing, the handler can commit shorten_wake() after the sweep's named_task_exists() probe but before this transaction runs. Since extend_wake() checks only the token and sequence, it then overwrites the newly shortened deadline with a full lease, so an allowance- or cap-refused unit waits roughly another 600 seconds instead of the promised 120-second retry cadence. Make the extension conditional on the previously observed expiry/deadline, or avoid lengthening a deadline that another transaction has already shortened.
Useful? React with 👍 / 👎.
| alive = named_task_exists(wake.get('queue') or queue, previous) | ||
| except Exception: | ||
| # Unknown custody keeps the old wake; bounded so a broken | ||
| # probe cannot strand the intent. | ||
| alive, probe_error = True, True | ||
| if alive: | ||
| self.protocol.extend_wake(segment_id, token, current, now, lease, probe_error=probe_error) |
There was a problem hiding this comment.
Keep failed enqueue attempts on the short retry cadence
When enqueue_named_task() fails before creating a task—for example because the queue binding is incomplete—the exception path shortens the wake to 120 seconds, but at that expiry the same incomplete binding makes named_task_exists() raise. This branch treats the probe error as a live task and extends the wake for the full 600-second lease; it repeats this three times before attempting another enqueue or inline recovery, turning the documented two-minute fallback into roughly a 30-minute stall. Preserve the failed-enqueue state so probe errors continue short rearming or retry inline recovery rather than extending an uncreated task as live.
Useful? React with 👍 / 👎.
| pass | ||
| if outcome in {'recovered', 'reconciled'}: | ||
| self.serving.reconcile() | ||
| self._live_tasks.discard(task_id) |
There was a problem hiding this comment.
Retry failed deliveries in the Cloud Tasks simulator
When a revision replacement cancels a simulated recovery request before _recover_handler() reaches this line, the task name remains in _live_tasks, but _enqueue_named_task() scheduled only that single delivery attempt. Every later lease-expiry probe therefore reports the task as still alive and extends its lease forever, whereas real Cloud Tasks redelivers the failed attempt. Any experiment that replaces a revision while paid recovery is in flight can consequently strand the intent and report incorrect drain and recovery results; model a retry or otherwise transition the simulated task out of live custody when an attempt is killed.
Useful? React with 👍 / 👎.
| try: | ||
| value = int(os.getenv('BATCH_PIPELINE_RECOVERY_WAKE_LEASE_SECONDS', str(RECOVERY_WAKE_LEASE_DEFAULT))) | ||
| except ValueError: | ||
| return RECOVERY_WAKE_LEASE_DEFAULT | ||
| if value == 0: | ||
| return 0 |
There was a problem hiding this comment.
Pin the wake lease in the simulator flag set
The simulator's _patched() context overrides and restores only keys present in DEFAULT_FLAGS or a scenario's overrides, but the new BATCH_PIPELINE_RECOVERY_WAKE_LEASE_SECONDS key was not added there. An ambient operator or developer value such as 0 therefore silently switches every simulation and regenerated golden back to legacy wake behavior instead of the intended production-like 600-second default, making results depend on the shell environment. Add the new flag to DEFAULT_FLAGS so simulations remain reproducible.
Useful? React with 👍 / 👎.
Grok re-review (SCA-833, SHIP) non-blocking LOW: extend_wake could restore a 600s lease over a 120s held re-arm written while the custody probe was in flight. extend_wake now skips a live wake_until. shorten_wake re-arms an already-expired lease too, so a held delivery answered during the probe wins. Failure-Class: FC-event-wakes-bypass-request-cadence Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # backend/config/batch_pipeline.py
, #22362, #22461, #22471 sync) - config/feature-flags.yaml: kept both new rows (LISTEN_LOOP_METRICS_ENABLED from main, ENRICHMENT_ROUTE from integration); rendered doc regenerated. - #21932 moved the legacy sync runner's 500/503 into _run_sync_job_attempt: known gaps and the task-target KNOWN set gain the four _run_sync_job_attempt keys (legacy, leave with C11), drop the _run_sync_job_body/503 keys and recover_quarantine/503 (fixed by #22476).
What changed and why
The quarantine-recovery sweep named each wake task
bpr-…-{token}-{clock//120}. Every waiting unit therefore got a new Cloud Tasks task every two minutes, whether or not its earlier task had been delivered.During the 2026-10-19 5% re-qualification (T0 07:59:20Z), the
batch-quarantine-recoveryqueue reached a depth of 363 for 180 quarantines:The duplicate wakes held concurrency slots that first deliveries needed. Together with the queue reset to 4/4, this pushed quarantine→projection p95 to 383s, and then 1,285s. Evidence:
data/run-2026-10-13-two-lane-nemotron/requal-5pct-0819Z.mdin the workspace repo.This PR allows at most one outstanding wake per prepared paid intent:
RecoveryStore.claim_wakeleases a wake on the job (default 600s) and returns the next sequence. It runs inside the samechecked()privacy/ownership fence asprepare(). It accepts only a quarantined job in thepreparedstate with a matching intent token._dispatchnames the taskbpr-{stage}-{sha}-{token}-w{seq}. While the lease is live, the sweep returnspendingand enqueues nothing. It reads the lease fromprepare()'s snapshot, so a pending unit costs no extra transaction.named_task_exists, the BASIC-view probe sync reprocess already uses on integration.extend_wakekeeps the lease and the sweep returnspending.probe_errors. After 3 consecutive failures the next wake is minted anyway, so a missingtasks.getpermission cannot strand the intent.claim_wakeis a compare-and-set on the inspected sequence, so they cannot both advance an expired wake.X-CloudTasks-TaskNameheader and passes its-w<seq>toQuarantineRecovery.delivered.shorten_wakeacts only on that sequence, so a latew1cannot shorten an outstandingw2. Legacy or unnamed deliveries change nothing.claim_wake,extend_wakeandshorten_wakeall runchecked(), the same privacy/ownership fence asprepare().runningunits are unchanged: dispatch reconciles them inline and never wakes them.recovery_wake = {token, seq, wake_until, queue[, probe_errors]}.The paid-intent fence is unchanged.
RecoveryStore.start(prepared→running, token CAS) is still the only path to a provider call. The wake lease is scheduling metadata only. A duplicate delivery, whether an old-style task or a concurrent sweeper, still spends at most once.Kill switch:
BATCH_PIPELINE_RECOVERY_WAKE_LEASE_SECONDS=0restores the legacy time-bucketed wake on every sweep, byte-for-byte: the characterization goldens reproduce exactly under0. The default is 600; the bound is 120..3600, and malformed values keep 600. The flag is registered inconfig/feature-flags.yamland the deployment-setting classification.Product invariants affected
none
How it was verified
Targeted tests on m5 under
bin/omi-heavy run -- nice -n 19 bash test.sh, all passing:test_batch_pipeline_quarantine_recovery.py(86 tests)test_batch_pipeline_quarantine*.py,test_batch_pipeline_recovery*.py,test_batch_pipeline_serving.pytest_batch_pipeline_speech_redrive.py,test_batch_pipeline_terminal_empty.py,test_batch_pipeline_privacy.py,test_batch_pipeline_cohort_config.pytest_pipeline_sim*.pytest_pipeline_characterization.py, after regenerating the goldens.Golden changes come from
PIPELINE_GOLDEN_UPDATE=1. WithBATCH_PIPELINE_RECOVERY_WAKE_LEASE_SECONDS=0, the old goldens pass unchanged (13/13).recovery_wakefield, and some recovery timelines shorten. The trace scrubber drops the absolutewake_until.privacy_fence_midflightshows the effect on its one slow paid slot:paid_fallback_calls_after_privacy_fencestays 0 andmax_paid_calls_per_segmentstays 1.CI follow-up (Sync Cloud Tasks Stack Gauntlet, and the Backend Hermetic Merge Gate that depends on it):
-[0-9]{1,12}), so it rejected-w<seq>task names. That timed outbatch-empty-asr-recovery.X-CloudTasks-TaskNamethe way Cloud Tasks does.Tests
New tests in
backend/tests/unit/test_batch_pipeline_quarantine_recovery.py:test_waiting_unit_gets_one_task_across_sweeps_until_the_wake_lease_expires: 30 sweeps at 20s intervals over a 10-minute undelivered backlog produce exactly oneenqueue_named_taskcall (w1). At expiry, a task that still exists keeps its lease. Only NotFound repairs it withw2. The paid intent is unchanged and there is no audio fetch or STT call.test_duplicate_wake_names_are_deterministic_and_deliveries_spend_once:None, and a repeat dispatch ispending.test_held_delivery_rearms_the_former_cadence_without_new_intent: a held delivery of the named wake re-arms after 120s. An unnamed delivery, or one with any other outcome, does not.test_stale_held_delivery_never_shortens_a_newer_waketest_unknown_task_custody_extends_a_bounded_number_of_timestest_concurrent_sweepers_cannot_both_advance_an_expired_waketest_enqueue_failure_rearms_the_former_cadence_instead_of_the_full_leasetest_wake_shortening_keeps_the_privacy_fencetest_asgi_held_delivery_rearms_only_its_named_waketest_stack_harness_accepts_leased_and_legacy_wake_namestest_wake_kill_switch_restores_time_bucketed_wakes:0writes norecovery_wake, and every dispatch enqueues again.test_wake_claim_keeps_the_privacy_fence: an account deletion makesclaim_wakeraiseBatchPrivacyBlocked, dispatch cancels, and nothing is enqueued.test_recovery_wake_lease_config_is_boundedThe existing legacy dispatch test now pins the kill switch, so the old two-minute behaviour stays covered.
UI evidence
UI-Evidence: none -- backend recovery dispatch only
Failure class (fixes)
Failure-Class: FC-event-wakes-bypass-request-cadence
🤖 Generated with Claude Code