Repository navigation
fix(batch): make owner drains claim-aware with contention backoff - #24710
Conversation
Failure-Class: FC-immediate-retry-loses-shared-cas
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.
3 issues found across 10 files
Confidence score: 3/5
projection_drain.py: A delayed retry timer can fire during shutdown and restart an owner-drain task after the serving loop has stopped. Ensure the projector is closed when serving shuts down.batch_pipeline_projection_claim.py: Peek failures are reported ascomponent=otherbecausebatch_pipelineis missing from the fallback allowlist. Add it toALLOWED_COMPONENTSor use an existing component.pipeline_sim/projection_drain.py: The no-holder stub skips the Redis admission peek latency, so simulated throughput and claim counts can diverge from production. Model the claim-lane cost in the stub.
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/database/batch_pipeline_projection_claim.py">
<violation number="1" location="backend/database/batch_pipeline_projection_claim.py:38">
P2: `component='batch_pipeline'` is not in `ALLOWED_COMPONENTS` in `utils/observability/fallback.py`, so every peek failure is bucketed to `component=other`. Add `batch_pipeline` to that allowlist, or use an existing component, so this fallback is attributable. The peek-error test should also assert the `record_fallback` call.</violation>
</file>
<file name="backend/utils/batch_pipeline/projection_drain.py">
<violation number="1" location="backend/utils/batch_pipeline/projection_drain.py:109">
P2: `close()` is not invoked when serving shuts down with only delayed retry timers, so a timer can fire during shutdown and resurrect an owner-drain task after the serving loop has stopped. Close the projector's owner drains from the serving shutdown path before allowing cleanup to continue.</violation>
</file>
<file name="backend/testing/pipeline_sim/projection_drain.py">
<violation number="1" location="backend/testing/pipeline_sim/projection_drain.py:474">
P3: This stub makes the virtual drain skip the new Redis admission peek's modeled latency, so throughput and claim counts no longer reflect production behavior. Charge the claim lane in the no-holder stub (and model a held result if contention is intended).</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| return bool(_redis_client().get(f'batch_projection:{namespace}:{hashed_owner}')) | ||
| except Exception as error: | ||
| record_fallback( | ||
| component='batch_pipeline', |
There was a problem hiding this comment.
P2: component='batch_pipeline' is not in ALLOWED_COMPONENTS in utils/observability/fallback.py, so every peek failure is bucketed to component=other. Add batch_pipeline to that allowlist, or use an existing component, so this fallback is attributable. The peek-error test should also assert the record_fallback call.
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/database/batch_pipeline_projection_claim.py, line 38:
<comment>`component='batch_pipeline'` is not in `ALLOWED_COMPONENTS` in `utils/observability/fallback.py`, so every peek failure is bucketed to `component=other`. Add `batch_pipeline` to that allowlist, or use an existing component, so this fallback is attributable. The peek-error test should also assert the `record_fallback` call.</comment>
<file context>
@@ -28,6 +29,24 @@ def _redis_client():
+ return bool(_redis_client().get(f'batch_projection:{namespace}:{hashed_owner}'))
+ except Exception as error:
+ record_fallback(
+ component='batch_pipeline',
+ from_mode='claim_peek',
+ to_mode='enqueue',
</file context>
|
|
||
| self.delayed[owner] = asyncio.get_running_loop().call_later(random.uniform(5.0, 15.0), retry) | ||
|
|
||
| def close(self) -> None: |
There was a problem hiding this comment.
P2: close() is not invoked when serving shuts down with only delayed retry timers, so a timer can fire during shutdown and resurrect an owner-drain task after the serving loop has stopped. Close the projector's owner drains from the serving shutdown path before allowing cleanup to continue.
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/projection_drain.py, line 109:
<comment>`close()` is not invoked when serving shuts down with only delayed retry timers, so a timer can fire during shutdown and resurrect an owner-drain task after the serving loop has stopped. Close the projector's owner drains from the serving shutdown path before allowing cleanup to continue.</comment>
<file context>
@@ -51,22 +69,77 @@ def launch(self) -> None:
+
+ self.delayed[owner] = asyncio.get_running_loop().call_later(random.uniform(5.0, 15.0), retry)
+
+ def close(self) -> None:
+ self.closed = True
+ self.queue.clear()
</file context>
| patch.object(projection_drain, 'time', lanes.module()), | ||
| patch.object(projection_drain, 'run_blocking', inline_blocking), | ||
| patch.object(projection, 'projection_claim', claim), | ||
| patch.object(projection_drain, 'projection_claim_held', lambda *args: False), |
There was a problem hiding this comment.
P3: This stub makes the virtual drain skip the new Redis admission peek's modeled latency, so throughput and claim counts no longer reflect production behavior. Charge the claim lane in the no-holder stub (and model a held result if contention is intended).
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/testing/pipeline_sim/projection_drain.py, line 474:
<comment>This stub makes the virtual drain skip the new Redis admission peek's modeled latency, so throughput and claim counts no longer reflect production behavior. Charge the claim lane in the no-holder stub (and model a held result if contention is intended).</comment>
<file context>
@@ -471,6 +471,7 @@ async def serve():
patch.object(projection_drain, 'time', lanes.module()),
patch.object(projection_drain, 'run_blocking', inline_blocking),
patch.object(projection, 'projection_claim', claim),
+ patch.object(projection_drain, 'projection_claim_held', lambda *args: False),
patch.object(projection, 'build_incoming', build_incoming),
patch.object(projection_parts, 'split_result', lambda item, payload: [(item, payload)]),
</file context>
| patch.object(projection_drain, 'projection_claim_held', lambda *args: False), | |
| patch.object(projection_drain, 'projection_claim_held', lambda *args: (lanes.spend('claim') or False)), |
Failure-Class: FC-immediate-retry-loses-shared-cas
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e35743acce
ℹ️ 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".
| self.delayed.pop(owner, None) | ||
| self.request([owner]) | ||
|
|
||
| self.delayed[owner] = asyncio.get_running_loop().call_later(random.uniform(5.0, 15.0), retry) |
There was a problem hiding this comment.
Close delayed owner drains explicitly during shutdown
When an OwnerDrains instance has only delayed owners and no active tasks at shutdown, nothing calls its close(): the only production call is from finished() after an active task is cancelled. stop_serving() does not close owner drains, and drain_background_tasks() only cancels a snapshot of tracked tasks, not these timer handles. Consequently, a retry can fire after the background-task drain and start a new projection task during the remaining shutdown cleanup, escaping cancellation and potentially running against clients or executors being closed. Explicitly close the drain scheduler from the serving shutdown path so delayed retries are cancelled even when no owner task is active.
Useful? React with 👍 / 👎.
## Problem Projection sweep supply is tied to serving instance count. Moving discovery onto dedicated instances needs an independent loop that cannot compete for maintenance/recovery leadership. This implements David's 2026-11-05 pump plan, sections 2 and 4; deployment shape remains pending. ## Fix - Add `serving_projection_sweep_enabled()` using the shared kill-switch helper. `BATCH_PIPELINE_SERVING_PROJECTION_SWEEP` is on unless explicitly `off`; it gates only `Serving.reconcile()`'s sweep, preserving wakes, held drains, metrics and maintenance/recovery. - `BATCH_PIPELINE_PROJECTION_PUMP_ENABLED=true` selects one lean projection loop instead of the three serving loops, independently of `BATCH_PIPELINE_SERVING_ENABLED`. It never invokes reconcile, maintenance or recovery dispatch. Sweeps use `run_blocking(sync_executor, ...)`; owed drains start on the event loop. After each sweep, it schedules discovered or owed projection follow-ups via `start_followups(())` and the owed index flush on the event loop, before starting owner drains after all pages. Each completed tick, including a failed tick, updates `omi_batch_projection_pump_last_tick_seconds` (Unix timestamp, zero before first tick). It logs successful sweeps, owners requested and elapsed time; errors log and retry. - Pump metrics scrapes use refresh-only regardless of the serving/read-only metrics controls; they never invoke the reconcile coordinator on the configured pump role. - Bound pages/tick (default 1, range 1-4), sleep (default 20s, range 2-60s) and owner drains (default 8, range 1-16); malformed values retain defaults. Register all five env names, and regenerate the registry. All unset defaults preserve today's behavior. `projection_drain.py` changes only its capacity constant and the config import. No deployment files or `.github/**` changes. ## Validation Code and hermetic tests only; no production access or GCP tier used. Merged `origin/main` at `148bf4c1c57073dba4ec9a750415f2c72f5adb87` using a merge commit, without rebase. Six files had conflicts: batch config, flag budget, kill-switch helper, pipeline contract docs, policy tests and projection drain. Both #24710 claim-aware behavior and pump capacity accessor are retained. The drain implementation is byte-for-byte main after removing only the capacity accessor import and restoring the old constant. Main advanced during CI; a second merge includes `f8edd96cdbe` (#24716). Its four conflicts in flag budget, kill-switch helper, rendered registry and policy tests retain the new striping controls alongside the pump controls. `bin/omi-heavy run -- env BACKEND_UNIT_TEST_FILE_LIST=<file> bash backend/test.sh`: - Pump: **92 passed**. - Serving (including four pump metrics-route combinations): **61 passed**. - Projection follow-ups: **36 passed**. - Owner drain / claim-aware admission: **66 passed**. - Metrics: **32 passed**. - GMP sidecar: **117 passed**. - Policy: **76 passed**. - Projection simulation: **1 passed, 2 slow tests deselected** by the standard runner filter. - Stage env ratchet: **7 passed**. - Flag budget: **24 passed**. Additional post-merge suites: projection discovery **67**, follow-up desync **36**, follow-up reads **6**, sweep owner chain **34**, and timeliness **18** passed. Total: **673 passed**, fifteen isolated files (plus the same 2 slow simulations deselected). Registry validation passed; the env-ratchet baseline is unchanged. The enforced push gate passed **41 checks**; pyright reported **0 errors**; selected push-time unit tests passed. The requested merge reconciliation and metrics-route P1 are included. The listed P2 follow-ups are outside this change; no new review round was started. ## Risk Enabling a pump adds discovery work and shared-executor load. Bounds are pages 1-4, tick 2-60 seconds and owner drains 1-16; defaults remain 1, 20 and 8. The pump stays disabled by default. Durable receipts, owner claims and fencing are unchanged. ## Ramp plan Owner: lead2, after David's deployment-shape decision. Studio safe start on a **dedicated service**: - **4 instances**. - `BATCH_PIPELINE_PUMP_SWEEP_PAGES=1`. - `BATCH_PIPELINE_PUMP_TICK_SECONDS=2`. - `BATCH_PIPELINE_MAX_OWNER_DRAINS=8` per instance. **Never set `BATCH_PIPELINE_PROJECTION_PUMP_ENABLED=true` on backend-integration itself: the toggle is service-wide.** Keep `BATCH_PIPELINE_SERVING_ENABLED` false/unset on the dedicated pump service. **Cutover gate:** owner_drain advanced **>=20 rows/s for 30 minutes** before disabling serving sweeps. Install and verify a missing/stale alert on the dedicated service's `omi_batch_projection_pump_last_tick_seconds` beforehand, including never-observed zero and missing instance series; a stale/missing alert must prevent cutover. Fallback: serving sweeps stay **ON** until both the throughput gate and heartbeat-alert prerequisite pass. Alarm if Firestore read rate rises more than 50% over pre-cutover. Retain the owner_drain rows/s floor of 70% of pre-cutover; watch sweep elapsed time and executor saturation. Evaluate claim_busy share (no higher than pre-cutover) **after serving sweeps are switched off, not during dual-running**. This PR authorizes no deployment or cutover. ## ROLLBACK Env only, through new revisions, in this order: 1. Restore serving sweeps **ON on the existing service first** (`BATCH_PIPELINE_SERVING_PROJECTION_SWEEP=on`). 2. Set `BATCH_PIPELINE_PROJECTION_PUMP_ENABLED=false` on the dedicated service. 3. Restore `BATCH_PIPELINE_MAX_OWNER_DRAINS=8`. Failure-Class: none These are pre-merge qualification corrections to the newly introduced pump role; no existing semantic failure-class definition matches the missing follow-up scheduling, pump-specific capacity bounds, and metrics-route role isolation. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/24712?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/24712?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24712&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. -->
…4943) <!-- claude-projects-attribution: {"github_login":"Git-on-my-level"} --> _Requested by **David**_ ## What changes Retro P6 adds `batch-pipeline-tuning-disclosure` to the shared manifest in both local and CI lanes. Numeric capacity assignments and concurrency environment defaults in the batch config, pipeline source, worker/pusher charts, and `backend/utils/pusher_*.py` require numeric disclosures in one PR-body section naming a matched knob: before/after, from/to, or a nearby numeric arrow (`6 -> 4` or `6 → 4`). A knob with no removed numeric assignment may instead use `new: <num>` or `initial <num>`. Newly added literals directly assigned or compared to state-like names, or passed as state/status/phase/disposition/outcome/reason kwargs, must name an exit, terminal, dead-letter, re-entry, clear, or recovery path; literals already anywhere in the merge-base tree are exempt. `Numbers-waived: <reason>` and `State-exit-waived: <reason>` waive their respective requirement and echo the reason. HTML comments, fenced code blocks and inline code are stripped before validating disclosures, state exits or waivers. Logging arguments and literals merely near state-related words do not count as new states. The same single manifest entry runs hermetic regression tests before checking the body. Only changed lines trigger detection; flags, comment-only lines, and unchanged context do not count. The detector deliberately misses indirect/formula tuning: this is a disclosure ratchet. David approved this exact manifest and script/test change on **2026-11-08 at 16:13Z**. No workflow file changed. The change is limited to `.github/checks-manifest.yaml` and the two P6 files under `.github/scripts/`. ## Why this check The retro's #24481 HPA retune is the design precedent; the sweep below exercises HPA bounds changes such as #24742. Its from/to wording is supported, but its knob names are only in inline code, which the requested prose-only rule excludes. Existing product-invariant and failure-class checks validate different author declarations; neither detects capacity knobs or new lifecycle literals. This check reuses the manifest's existing diff/metadata plumbing without changing workflow wiring or inventing another PR orchestration layer. ## Product invariants affected none Failure-Class: none ## Merged-PR false-positive sweep (2026-11-08T20:01:42.025036+00:00) **200 merged PRs screened; 69 trigger-touching diffs checked; 16 would fail and 53 would pass.** 14 failing PRs require numeric disclosures; 2 require state declarations (3 state literals total). The prior sweep reported 18 failures; the refreshed capped corpus also advances its merge cutoff. Method: `gh pr list --repo BasedHardware/omi --state merged --search 'merged:>=2026-10-09' --limit 200 --json number,title,body,mergeCommit,mergedAt,files`, followed by `gh pr diff <number> --repo BasedHardware/omi` for matching paths. Full paginated file lists were checked whenever the initial listing reached 100 files. Each diff was checked against its PR body and reconstructed PR merge-base: merge-parent merge-base for normal merges; PR-head/merge-parent merge-base cross-checked with the recorded PR base for one-parent merges. State candidates use a whole-tree lookup at that merge-base. The capped corpus spans **2026-11-04T12:58:21Z through 2026-11-08T19:20:24Z**: a sample within the requested 30-day window, not full-month coverage. No production reads or GCP tier were used. The stricter state association passes #24743 (the prior proximity-only candidate). #24733 and #24729 now pass the expanded numeric wording. The required inline-code stripping means #24742 still fails: its from/to numbers are supported, but its matched knob names appear only in inline code. #24884 and #24725 also fail when their state names are excluded as inline code. These are explicit effects of the requested prose-only policy, not claims that those historical PRs omitted all semantic explanation. Sample of would-fail PRs: | PR | Detected change | Missing disclosure | | --- | --- | --- | | [#24889](#24889) | Tuning: `max_count` | Initial/new numeric value naming a matched knob in prose, before/after disclosure, or Numbers-waived | | [#24884](#24884) | New state: `record_barrier_aged` | State literal and exit declaration in prose, or State-exit-waived (inline code is excluded) | | [#24799](#24799) | Tuning: `MIN_STORAGE_PCM_BUDGET_MB` | Initial/new numeric value naming a matched knob in prose, before/after disclosure, or Numbers-waived | | [#24742](#24742) | Tuning: `maxReplicas`, `minReplicas` | Matched knob name in prose alongside the existing from/to numbers | | [#24736](#24736) | Tuning: `PAGE_SIZE` | Initial/new numeric value naming a matched knob in prose, before/after disclosure, or Numbers-waived | | [#24725](#24725) | New state: `marker_retry_overflow`, `marker_write_failed` | State literal and exit declaration in prose, or State-exit-waived (inline code is excluded) | | [#24716](#24716) | Tuning: `limit` | Initial/new numeric value naming a matched knob in prose, before/after disclosure, or Numbers-waived | | [#24712](#24712) | Tuning: `MAX_OWNER_DRAINS` | Numeric before/after, from/to or arrow disclosure naming a matched knob in prose, or Numbers-waived | | [#24710](#24710) | Tuning: `MAX_DELAYED_OWNERS` | Initial/new numeric value naming a matched knob in prose, before/after disclosure, or Numbers-waived | | [#24707](#24707) | Tuning: `MAX_HEAD_REQUEUES` | Numeric before/after, from/to or arrow disclosure naming a matched knob in prose, or Numbers-waived | All would-fail PRs: #24889, #24884, #24799, #24742, #24736, #24725, #24716, #24712, #24710, #24707, #24703, #24697, #24689, #24680, #24643, #24601. ## Validation - **26 focused regression tests passed** on head `1788dd10315e7a709dcaf6150838907638386ad0`, covering fenced/inline examples, direct state association (including the logging regression), from/to and arrows, and first-time versus changed numeric values. - **`make preflight` passed all 14 selected local checks**, including 26 P6 tests and 78 manifest-contract tests, with `OMI_PR_BODY_FILE` and `BACKEND_UNIT_FILE_BUDGET_SECONDS=900`. The normal bounded pre-push gate also passed all 14 checks using the final body and the same budget, with `GOOGLE_APPLICATION_CREDENTIALS` and every `CLOUDSDK_*` variable removed. - `scripts/pr-preflight --suggest` required no invariant citations; `Failure-Class: none` is declared above. - No workflow file changed; only the manifest and two P6 scripts differ from the merge base. - No production reads or GCP tier used. Full-month coverage beyond the 200-PR cap, indirect/formula tuning and product/runtime behavior are not established by this check. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Problem
Fleet instances repeatedly request the same projection owners. Requests arriving during a losing claim-busy turn immediately re-enter the FIFO and repeat the contention.
Fix
again. Productivemore=Truecontinuations retain immediate FIFO progress and bypass the new admission peek.Based on merged revert #24707 (e88fb82); only L2 is included. Prefetch, capacity, page sizes, assignment fencing and the #24697 collapse remain unchanged. The optional head item was skipped: the cited code is a read-before-owner-draining skip, not a clear head-staleness skip.
Tests
BACKEND_UNIT_TEST_FILE_LIST=/tmp/l2f.txt bash test.sh: 97 passed across 3 isolated files.config.batch_pipeline/config.policy.kill_switch, with an owned helper-backed flag-budget entry and generated registry documentation. Onlyoffdisables it in every parser mode.Risk and rollback
Low-risk advisory scheduling change; durable result rows remain discoverable.
PROJECTION_DRAIN_CLAIM_AWARE=offrestores previous admission, re-request and FIFO behavior. Default is on; onlyoffdisables it.Failure-Class: FC-immediate-retry-loses-shared-cas
Line-Count-Exception: backend/config/batch_pipeline.py | 818 -> 825 | Add the requested seven-line policy kill-switch accessor to remove the raw stage env read; no stage-env ratchet baseline change.