Skip to content

fix(batch): one outstanding quarantine-recovery wake per paid intent - #22458

Merged
Git-on-my-level merged 6 commits into
mainfrom
lane/opus-recovery-wake
Oct 19, 2026
Merged

Git-on-my-level merged 6 commits into
mainfrom
lane/opus-recovery-wake

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

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-recovery queue reached a depth of 363 for 180 quarantines:

  • CreateTask succeeded 184 times in one 10-minute bucket and 223 times in the next.
  • Only 30–61 attempts were delivered in those buckets.

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.md in the workspace repo.

This PR allows at most one outstanding wake per prepared paid intent:

  • RecoveryStore.claim_wake leases a wake on the job (default 600s) and returns the next sequence. It runs inside the same checked() privacy/ownership fence as prepare(). It accepts only a quarantined job in the prepared state with a matching intent token.
  • _dispatch names the task bpr-{stage}-{sha}-{token}-w{seq}. While the lease is live, the sweep returns pending and enqueues nothing. It reads the lease from prepare()'s snapshot, so a pending unit costs no extra transaction.
  • At lease expiry the sweep checks the previous task first. It calls named_task_exists, the BASIC-view probe sync reprocess already uses on integration.
    • Task still exists: it may be waiting in a saturated queue or inside its 1,500s dispatch window. extend_wake keeps the lease and the sweep returns pending.
    • Authoritative NotFound: only this mints the next sequence, which gets a new deterministic name. The intent token is unchanged.
    • Probe fails: the lease is also extended, and the failure is counted in probe_errors. After 3 consecutive failures the next wake is minted anyway, so a missing tasks.get permission cannot strand the intent.
    • Two sweepers: claim_wake is a compare-and-set on the inspected sequence, so they cannot both advance an expired wake.
  • A delivery of that same wake that leaves the intent prepared shortens the lease to 120s. This applies, for example, when an allowance check refuses the start.
    • The handler reads Cloud Tasks' X-CloudTasks-TaskName header and passes its -w<seq> to QuarantineRecovery.delivered.
    • shorten_wake acts only on that sequence, so a late w1 cannot shorten an outstanding w2. Legacy or unnamed deliveries change nothing.
    • A failed enqueue shortens only the wake it just claimed.
  • Privacy fence: claim_wake, extend_wake and shorten_wake all run checked(), the same privacy/ownership fence as prepare().
  • running units are unchanged: dispatch reconciles them inline and never wakes them.
  • Lease field name: the stored field is 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=0 restores the legacy time-bucketed wake on every sweep, byte-for-byte: the characterization goldens reproduce exactly under 0. The default is 600; the bound is 120..3600, and malformed values keep 600. The flag is registered in config/feature-flags.yaml and 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.py
  • test_batch_pipeline_speech_redrive.py, test_batch_pipeline_terminal_empty.py, test_batch_pipeline_privacy.py, test_batch_pipeline_cohort_config.py
  • test_pipeline_sim*.py
  • test_pipeline_characterization.py, after regenerating the goldens.

Golden changes come from PIPELINE_GOLDEN_UPDATE=1. With BATCH_PIPELINE_RECOVERY_WAKE_LEASE_SECONDS=0, the old goldens pass unchanged (13/13).

  • All six changed goldens: the job rows gain the new recovery_wake field, and some recovery timelines shorten. The trace scrubber drops the absolute wake_until.
  • privacy_fence_midflight shows the effect on its one slow paid slot:
Metric Before After
Recovery tasks enqueued 27 12
Last paid call 1,243s 867s
Several recoveries completed under 15 min under 5 min
Paid calls 6 7
  • The extra paid call is at 668.6s, before the privacy fence at 680s, for a unit that was legitimately recoverable then. Before this change, wasted duplicate slots kept it queued past the fence.
  • No calls after the fence: paid_fallback_calls_after_privacy_fence stays 0 and max_paid_calls_per_segment stays 1.

CI follow-up (Sync Cloud Tasks Stack Gauntlet, and the Backend Hermetic Merge Gate that depends on it):

  • Cause: the stack harness's Cloud Tasks fake accepted only numeric wake suffixes (-[0-9]{1,12}), so it rejected -w<seq> task names. That timed out batch-empty-asr-recovery.
  • Fix: the harness now accepts both forms and sends X-CloudTasks-TaskName the way Cloud Tasks does.
  • Simulator: the sim mirrors the handler's held re-arm and models task custody: a task exists until a delivery answers it.

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 one enqueue_named_task call (w1). At expiry, a task that still exists keeps its lease. Only NotFound repairs it with w2. The paid intent is unchanged and there is no audio fetch or STT call.
  • test_duplicate_wake_names_are_deterministic_and_deliveries_spend_once:
    • A concurrent claim against a live lease returns None, and a repeat dispatch is pending.
    • Two deliveries give one STT call.
    • A settled intent gets no further wakes.
  • 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_wake
  • test_unknown_task_custody_extends_a_bounded_number_of_times
  • test_concurrent_sweepers_cannot_both_advance_an_expired_wake
  • test_enqueue_failure_rearms_the_former_cadence_instead_of_the_full_lease
  • test_wake_shortening_keeps_the_privacy_fence
  • test_asgi_held_delivery_rearms_only_its_named_wake
  • test_stack_harness_accepts_leased_and_legacy_wake_names
  • test_wake_kill_switch_restores_time_bucketed_wakes: 0 writes no recovery_wake, and every dispatch enqueues again.
  • test_wake_claim_keeps_the_privacy_fence: an account deletion makes claim_wake raise BatchPrivacyBlocked, dispatch cancels, and nothing is enqueued.
  • test_recovery_wake_lease_config_is_bounded

The 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

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]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-19T11:01:30.023893Z f294a16 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +347 to +350
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +336 to +341
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines 169 to +174
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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +139 to +145
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')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Git-on-my-level and others added 3 commits October 19, 2026 16:28
…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]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +156 to +158
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +341 to +347
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +240 to +245
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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
@Git-on-my-level
Git-on-my-level merged commit 873a693 into main Oct 19, 2026
59 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/opus-recovery-wake branch October 19, 2026 11:15
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
, #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).
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