Repository navigation
fix(batch): back off barrier-blocked record_pending retries by age - #24863
Conversation
Rows whose capture upload/finalization barrier is still open cannot admit until the conversation finalizes; the drainer retried ~19k of them every 60 s after #24841 exposed them (~$15/h of Firestore churn). Back off 60 s -> 15 min (>10 min old) -> 1 h (>24 h old); other errors unchanged. Kill switch RECORD_DRAIN_BARRIER_BACKOFF=off. Failure-Class: none Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codex Review Summary: ✅ CompletedThis 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: 30f791bb34
ℹ️ 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 record_drain_barrier_backoff_enabled() -> bool: | ||
| """Kill switch: RECORD_DRAIN_BARRIER_BACKOFF=off restores the flat 60 s retry.""" | ||
| return os.getenv('RECORD_DRAIN_BARRIER_BACKOFF', 'on').strip().lower() != 'off' |
There was a problem hiding this comment.
Document the record-drain retry change and kill switch
This changes audio-admission retry latency from 60 seconds to as much as an hour and introduces RECORD_DRAIN_BARRIER_BACKOFF, but the commit contains neither a pipeline change note nor an update to the environment contract. Repository-wide search found no documentation for the new switch under backend/docs/listen_pusher_pipeline*. Add the required change note describing the age tiers, rollout, and rollback, and document the switch and its default in the pipeline contract so operators can distinguish the intentional delay from a stalled drain. backend/AGENTS.md explicitly requires these documentation updates for audio/lifecycle and environment-contract changes.
AGENTS.md reference: backend/AGENTS.md:L164-L164
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
3 issues found across 3 files
Confidence score: 4/5
- Malformed
enqueued_atvalues inlive.pycan send a barrier row to the one-hour retry instead of the safe young-row fallback. Validate that the value is a finite, non-boolean number before calculating its age. - The normal barrier assertions in
test_record_drain_barrier_backoff.pydepend on the ambientRECORD_DRAIN_BARRIER_BACKOFFsetting, so the test can vary across environments. Set it toonin the fixture and let the kill-switch test override it tooff. - The barrier text is duplicated across
config/record_audio.pyandlive.py, which can let the raise message and retry reasons drift apart. Define the constant next to the raise and import it inlive.py.
You’re at about 91% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/tests/unit/test_record_drain_barrier_backoff.py">
<violation number="1" location="backend/tests/unit/test_record_drain_barrier_backoff.py:21">
P3: The normal barrier assertions depend on the ambient `RECORD_DRAIN_BARRIER_BACKOFF` value. Set the switch to `on` in the fixture, leaving the kill-switch test to override it to `off`, so this unit file remains deterministic when run with deployment environment variables.</violation>
</file>
<file name="backend/utils/batch_pipeline/live.py">
<violation number="1" location="backend/utils/batch_pipeline/live.py:60">
P3: The barrier text is now duplicated in three places (`config/record_audio.py`, this constant, and `_RETRY_REASONS`). Define the constant next to the raise in `config/record_audio.py`, import it here, and use it in `_RETRY_REASONS` too. Otherwise a wording change silently disables the backoff.</violation>
<violation number="2" location="backend/utils/batch_pipeline/live.py:578">
P3: Malformed `enqueued_at` values can force a barrier row onto the one-hour retry instead of the safe young-row fallback. Validate that the value is a non-boolean finite number before calculating age, treating invalid values like a missing timestamp.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| def drained(monkeypatch): | ||
| from utils.batch_pipeline import live | ||
|
|
||
| monkeypatch.setenv('RECORD_DRAIN_CONCURRENCY', '1') |
There was a problem hiding this comment.
P3: The normal barrier assertions depend on the ambient RECORD_DRAIN_BARRIER_BACKOFF value. Set the switch to on in the fixture, leaving the kill-switch test to override it to off, so this unit file remains deterministic when run with deployment environment variables.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_record_drain_barrier_backoff.py, line 21:
<comment>The normal barrier assertions depend on the ambient `RECORD_DRAIN_BARRIER_BACKOFF` value. Set the switch to `on` in the fixture, leaving the kill-switch test to override it to `off`, so this unit file remains deterministic when run with deployment environment variables.</comment>
<file context>
@@ -0,0 +1,74 @@
+def drained(monkeypatch):
+ from utils.batch_pipeline import live
+
+ monkeypatch.setenv('RECORD_DRAIN_CONCURRENCY', '1')
+ monkeypatch.setattr(live.time, 'time', lambda: 100000.0)
+
</file context>
| OWNER = 'batch_live_v1' | ||
| UPLOAD_GRACE_SECONDS = 0 | ||
| # config.record_audio.require_record_audio_barrier: the capture is not finalized yet. | ||
| BARRIER_NOT_CLOSED = 'capture upload/finalization barrier not closed' |
There was a problem hiding this comment.
P3: The barrier text is now duplicated in three places (config/record_audio.py, this constant, and _RETRY_REASONS). Define the constant next to the raise in config/record_audio.py, import it here, and use it in _RETRY_REASONS too. Otherwise a wording change silently disables the backoff.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/batch_pipeline/live.py, line 60:
<comment>The barrier text is now duplicated in three places (`config/record_audio.py`, this constant, and `_RETRY_REASONS`). Define the constant next to the raise in `config/record_audio.py`, import it here, and use it in `_RETRY_REASONS` too. Otherwise a wording change silently disables the backoff.</comment>
<file context>
@@ -54,6 +56,8 @@
OWNER = 'batch_live_v1'
UPLOAD_GRACE_SECONDS = 0
+# config.record_audio.require_record_audio_barrier: the capture is not finalized yet.
+BARRIER_NOT_CLOSED = 'capture upload/finalization barrier not closed'
# Literal admission refusals worth counting; any other text could carry a value
# and is reported only as `other`.
</file context>
| elif barrier_open and record_drain_barrier_backoff_enabled(): | ||
| # The capture is not finalized yet: back off by how long it has waited. | ||
| enqueued = latest.get('enqueued_at') | ||
| age = time.time() - enqueued if isinstance(enqueued, (int, float)) else 0.0 |
There was a problem hiding this comment.
P3: Malformed enqueued_at values can force a barrier row onto the one-hour retry instead of the safe young-row fallback. Validate that the value is a non-boolean finite number before calculating age, treating invalid values like a missing timestamp.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/batch_pipeline/live.py, line 578:
<comment>Malformed `enqueued_at` values can force a barrier row onto the one-hour retry instead of the safe young-row fallback. Validate that the value is a non-boolean finite number before calculating age, treating invalid values like a missing timestamp.</comment>
<file context>
@@ -567,6 +572,11 @@ def defer(tx):
+ elif barrier_open and record_drain_barrier_backoff_enabled():
+ # The capture is not finalized yet: back off by how long it has waited.
+ enqueued = latest.get('enqueued_at')
+ age = time.time() - enqueued if isinstance(enqueued, (int, float)) else 0.0
+ delay = barrier_retry_delay(age)
# Our own lease ends now; a later deferral written during
</file context>
…, ghost settle on, assignment expiry) (#24884) ## What David 2026-11-07 16:24Z: "settle this the cheapest way possible ... and least debt for future agents". Built into code, with no one-off scripts or operator campaigns. State flips only; raw audio and custody markers are never deleted; no GPU/STT/LLM replays. 1. **Aged record dead letter.** - Barrier-blocked `record_pending` jobs ("capture upload/finalization barrier not closed", about 22k on 11-07) retried forever. - Inside the record drainer's EXISTING defer transaction (no new loop or query), the first barrier refusal stamps `record_dead_letter_deadline_at` (+14 d, a full window even for old rows). Once the window passes, the row flips to `state='dead'`, `dead_letter_reason='record_barrier_aged'`. - A malformed deadline never expires a row. Conversation, audio and custody are untouched. - Private OIDC `requeue-record` CASes only this reason back to `record_pending` through the normal privacy fence. - New `omi_batch_record_dead_letter_*` inflow, stock and freshness metrics, admitted by the Cloud Run ingestion allowlists, plus an alert. 2. **Ghost settle: stays OFF in this PR** (no runtime config change). - Ghost settle was tripped off on 2026-11-08 at about 02:00Z (lead2 ea819b/f5a331). The ghost branch bypassed `_target_restorable`, so rows with an unpersisted live record target failed at the head of their owner chain (`SyncAssignmentConflict` 'batch live target not persisted'), blocking later conversations. - Turning ghost on waits for the `_target_restorable` fix (lcwake/uicleanup) plus a head-error baseline. - This PR keeps only the code-side ghost-vs-expiry ordering: ghost classification runs before assignment expiry, so a ghost-eligible or cap/age-skipped row is never expired. 3. **Aged assignment_held expiry.** - Committed `recovery_state=held` rows that fail the real-held gate now get the SAME `held_expired` markers after a full window. They settle through the existing metric and nightly re-drive. - Ghost classification runs first: a ghost-eligible row, or one skipped by the cap or age floor, is never stamped or expired. - Identity, privacy-refusal and open-operator-intent fences hold; malformed anchors never expire. Also folds in lead2's #24863 follow-ups (f85d74): a shared barrier-message constant with the raise site, bool/NaN `enqueued_at` treated as young, and a deterministic kill-switch test. ## Kill switches (zero new flags; net-zero rule) - `BATCH_HELD_DEAD_LETTER_ENABLED=false` stops record dead-letter stamps and flips (normal retries continue) and the assignment expiry. - `BATCH_PIPELINE_PROJECTION_GHOST_SETTLE_ENABLED` stays at its default false in every environment (this PR does not enable it). - The switches are independent and documented in CONTRACT.md and config/feature-flags.yaml. ## Cost (firestore-lead estimate, sent before any live run: bus 051ef4) - Record: 0 added reads; the stamp and flip fold into existing defer writes; +1 aggregate count per 5-min leader tick. Nothing settles before about 11-21 (full window). - Ghost: none (stays off in this PR). - Assignment: reuses the existing 3 reads per observation; +1 stamp and +1 expiry write per row (8.45k rows, at most about 17k writes one-time). ## Review - Luna correctness + prod safety, one parallel round. - Blockers, both fixed in this branch: - (1) the new metrics were dropped by ingestion allowlists, so the alert stayed silent; - (2) kill-switch scope documentation. - Earlier rounds fixed: a new flag replaced by reuse (net-zero), and the ghost-vs-expiry ordering. ## Tests 3,294 passed, 75 expected xfails, 51 preflight checks (see the branch's settle reports). Firestore loopback integration passed in the earlier round (28 passed). ## Product invariants affected - INV-MEM-4: `backend/deploy/runtime_env.yaml` is touched only to set `BATCH_PIPELINE_PROJECTION_GHOST_SETTLE_ENABLED` for the batch serving role. No memory intake, Short-term/Long-term promotion, consolidation route or memory projection changes. Failure-Class: none 🤖 Generated with [Claude Code](https://claude.com/claude-code)
…mitted nothing (#24882) ## What The record drain loop has no pacing: every full page (100 rows) immediately triggers another pass. While privacy-blocked heads stayed on the page, the pass returned "blocked" and idled; #24841 moved them off, and since then any full page rescans at once even when nothing is admitted. - 2026-11-07 20:43Z to 21:13Z, after the #24841 defer was re-enabled: `store:due` reads rose 108 to 431/s and `store:get` 1,088 to 1,751/s. - Barrier-blocked rows (#24863 backoff) return due in waves and are rescanned without any admission. - firestore-lead tripped the defer back to 0 (bus cd411f/87a934). ## Change A full page that ADMITTED nothing (every row deferred, failed or still behind its barrier) keeps the idle wait, like a privacy-blocked page. Only passes that made progress continue immediately. - The drain still reaches every due row (a page per idle interval); it just stops the hot rescan. - Kill switch: `RECORD_DRAIN_IDLE_WITHOUT_PROGRESS=off` restores the old behavior. It lives in `config/record_drain.py` with the other `RECORD_DRAIN_*` capacity knobs, outside flag-budget scope. With this live, `RECORD_DRAIN_PRIVACY_DEFER_SECONDS` can be unset again (#24841 behavior) without the read climb. ## Tests - `tests/unit/test_record_drain_pacing.py`: - a no-admission full page idles; - a page with progress continues; - the kill switch restores the old behavior; - a partial page never continues. - `test_record_drain_privacy_defer`: a fully blocked page now idles one interval, and the starved row is still admitted on the next pass. - Also ran `test_batch_pipeline_live`, `test_record_drain_barrier_backoff`, `test_batch_record_dead_letter`, `test_batch_pipeline_serving`, `test_record_partial`, `test_record_gap_fill` and `test_replay_harness`: 489 passed on the rebased head. ## Review One Luna round (blocking-only). Its blocker is fixed: a normal return can be a no-op (an unchanged partial inventory poll), so progress now counts only when the defer transaction sees the row out of `record_pending`. The paging/shuffle tests pin the old mode through the kill switch. lead2 ddc817: the defer stays at its default (900) meanwhile. SCA-2036 review fix: rebased onto `main` (`af24862981`). The defer transaction now also reports dead-letter expiry, so it returns `(progress, expired)` — a row that left `record_pending` is progress, a dead-letter expiry is not, and a peer's dead-letter is not either. `test_record_drain_pacing` pins both. ## Verify after deploy (backend-integration) - `omi_firestore_billed_reads_by_caller_total{caller="database.batch_pipeline_store:due"}` falls back to about 100/s. - `store:get` falls. - Record admissions per minute stay unchanged. 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/24882?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/24882?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24882&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. --> ## Landing follow-up Operator documentation now covers the default-on pacing control, its `off` rollback value, and the conservative 20-second idle for partial-record coordinators that admit children while their parent remains pending. See `backend/docs/listen_pusher_pipeline/changes/2026-11-14-record-drain-pacing.md` and the record-drain pacing contract in `backend/docs/listen_pusher_pipeline.mdx`. CI on code head `d1a80c8081`: all eight backend unit shards and Backend Hermetic Merge Gate passed. The advisory Backend Emulator Proofs job failed the same six provider merge conformance cases already failing on main (`54b960d947`; run https://github.com/BasedHardware/omi/actions/runs/43578026940). The affected merge implementation and conformance tests are unchanged between that main snapshot and this PR. Deployment read-rate and admission checks remain post-deploy work.
…PL-487/482) (#24963) ## What changed and why A record whose capture barrier stays open needs bounded retries and a recoverable terminal state without releasing audio custody. Follow-up to #24884 and #24863: add the same production-drainer and reason-bound requeue contract on legacy Firestore, replacement Postgres and the simulator, covering parity rows **PL-487/PL-482**. The suite pins a full nonrenewing expiry window, exact deadline settlement, malformed deadline refusal, stale selection leases, current account/conversation/generation privacy fences, idempotent requeue and complete custody/policy preservation. It also proves age-based barrier delays, discovery at the retry deadline and both kill switches. Only audio admission and the drainer clock are injected; Store discovery, transactions and privacy checks remain real. The existing emulator runner executes the suite. Its `*_emulator_test.py` path matches the existing workflow trigger, so future test-only changes still select the proof. CI requires simulator and emulator; full local qualification requires `OMI_REQUIRE_STORE_BACKENDS=all`. No serving implementation, configuration, workflow, language gate or firmware changes. ## Product invariants affected none ## How it was verified - Simulator: 27 passed / zero skips or expected failures. - All-required simulator/Firestore/Postgres matrix: **80 passed, one strict expected failure, zero skips**. The unannotated run first reproduced 80 passes / one failure. [#24960](#24960) tracks Postgres rejecting a legacy boolean enqueue age in its generated-column cast. The strict annotation accepts only that exact SQL error; PL-482 remains incomplete. Every PL-487 case passes on all stores. - The existing full emulator runner passed every pre-existing group; its sole initial failing group was the new boolean-age case. The corrected new suite passes as qualified above. - `make preflight` passed all 34 selected checks. The ordinary final-commit push gates pass, including full backend typecheck (zero errors). - Three in-memory mutations fail at their intended assertions (renewed expiry, stale expiry, flattened retry); a simulated repaired boolean backend produces strict XPASS. Production files stay unchanged. Measured layer: local synthetic store conformance, not a deployed migration or physical audio erasure. ## Tests `backend/scripts/record_dead_letter_emulator_test.py`; `backend/scripts/run-emulator-proofs.sh` runs it with the mandatory backend matrix. Missing required infrastructure fails. ## UI evidence UI-Evidence: none -- test-only backend conformance. ## Failure class (fixes) Failure-Class: none ## New guards The merged #24884 recording-settlement change and #24863 barrier-retry incident motivate this regression contract. It extends the existing shared Store harness around the production drainer and requeue instead of adding another state authority or standalone gate. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/24963?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/24963?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24963&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. --> 🤖 Generated with [Claude Code](https://claude.com/claude-code)
What
Since #24841 went live, the record drainer reaches about 19k due
record_pendingrows that the privacy-blocked heads used to hide. Nearly all of them fail admission withcapture upload/finalization barrier not closed: the conversation is notcompleted, orrecord_audio_closedis unset, or upload sessions are still open (config/record_audio.require_record_audio_barrier). Each is re-selected about every 60 s.Change
A barrier-blocked row backs off by its
record_pendingage (enqueued_at):Other admission errors, and partial-inventory polling, keep their current delays. Rows that finalize are picked up within one backoff period. Expected: about 15-60x fewer reads on stuck rows.
Kill switch:
RECORD_DRAIN_BARRIER_BACKOFF=offrestores the flat 60 s. It lives inconfig/record_drain.pybeside the otherRECORD_DRAIN_*capacity knobs, outside the flag-budget scope.Not in scope: rows stuck for days behind a barrier that will never close need a lifecycle (park/dead-letter), which is the architecture thread's per-conversation state machine.
Tests
tests/unit/test_record_drain_barrier_backoff.py:enqueued_atcounts as young;Also run:
test_batch_pipeline_live,test_record_drain_privacy_defer, env ratchet, flag budget. 151 passed.Verify after deploy (backend-integration)
batch_live_admission ... barrier_not_closedlog rate drops about 15x.batch_pipeline_prod_jobsfall (firestore-lead's meter).record_pending(funnelcurrent.md) keeps admitting rows as captures finalize.Failure-Class: none
🤖 Generated with Claude Code