Repository navigation
perf(batch): raise worker throughput per replica - #22373
Conversation
…U chain The dedicated worker ran claim, compute admission, the GPU chain, completion and ordered merge strictly in sequence, so the GPU idled for every Firestore and admission round trip between flights. BATCH_PIPELINE_WORKER_PIPELINE_DEPTH (default 2, 1 restores the serial pump) runs that many pump lanes; the chain itself stays exclusive behind one asyncio lock, so GPU and host memory remain one flight. Waiting lanes renew their leases and refund them without an attempt charge on SIGTERM or a fatal GPU error. Periodic maintenance runs in one lane at a time. Merge, privacy fences and paid admission are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Recovery, the result-ready drain scan and queue metrics no longer occupy a pump lane between flights; depth 1 keeps the inline serial loop. 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. |
|
CI note: the 5 red checks are already red on current
I reproduced the unit failures on a pure-main checkout. The full batch gauntlet passed on this branch before #22321 landed, all 7 scenarios at the default depth 2. |
…ughput # Conflicts: # backend/config/batch_pipeline.py # backend/docs/feature-flag-registry.md
A renewal whose bounded wait times out marks the lease lost, but the blocking DB leaf may still own (or later extend) it. The stop hand-back skipped lost leases, leaving them leased with the pull's attempt charged. Refund every claimed lease; defer is fenced by owns_lease, so another owner's job is never touched. Name the renewal timeout so tests can bound it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lock Lanes race for the chain lock, so the waiting segment is identified from the chain rather than assumed; a computed later capture stays result_ready behind its refunded predecessor. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ughput # Conflicts: # backend/tests/unit/test_batch_pipeline_chart.py # config/feature-flags.yaml
…22425) * feat(rollout): runtime _ramp percents and the ramp controller (lane 6 M1) Contract (f): rollout_cohorts/_ramp holds per-env percents and legacy_sync. utils/rollout/runtime_percent.py reads it with a 30s process cache on the rollout executor, serves last-known-good on error, and falls back to the env value on a cold start or a missing document, so with no document behaviour is unchanged. config/ reaches it through a resolver seam in config/rollout_cohorts.py, bound by configure_rollout_runtime(). Unbound processes keep env values. summary_guarantee and batch_live_preview now read their percent through the seam. valid_uid rejects _ramp* ids. CAS writes create a history row in the same transaction and refuse range or nesting violations. Contract (g): scripts/rollout/ramp_controller.py has a pure decide() and a thin runner. The runner writes only the batch-pipeline/first-summary percents and acts only while legacy_sync=on. It moves one step at a time, at most once per 10 minutes, and never past 100. It uses the fleet gate's data-loss tokens for ROLLBACK_ZERO and stops after two rollbacks in 24h until a human lock_cleared write. Every decision goes to STATE and every action to anx. After a sleep or restart gap, the first tick only holds (S9). scripts/rollout/ramp_set.py is the operator CLI. inject_gate.py is the staging-only rehearsal wrapper. config/batch_pipeline.py is untouched (frozen until #22362/#22373 reach integration). Co-Authored-By: Claude Opus 5.5 <[email protected]> * refactor(rollout): align runtime_percent with the lane 1 stub; no package __init__ files Snapshot source 'firestore' and revision int (0 = no document) match lr/01-stubs. RAMP_DOC_ID re-exported. utils/rollout and scripts/rollout are namespace packages, because the dead-code ratchet blocks __init__.py there. LIFECYCLE headers are now on line 1. Co-Authored-By: Claude Opus 5.5 <[email protected]> * refactor(rollout): run _ramp reads in a fresh context, never the request's Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(rollout): C1 gate-unavailable escalation; BYOK not re-held at dispatch C1 (lead ruling): a gate that cannot run (ro_prod_unavailable, timeout_incomplete, parity_not_run, ...) holds. After 3 consecutive such ticks (~30 min) the controller pages the lead, then pages again every 3 ticks. The streak lives in the heartbeat file, so it survives a restart; a pause gap resets it. admission.authorize: admission decides funding once (contract (c)). A unit whose admission policy snapshot records provider_reason=byok skips the dispatch-time funded re-check, which runs without the user's keys or BYOK consent and would re-hold a BYOK owner on every lease (David: BYOK routes like everyone). A missing or other policy keeps today's re-check, so this stays behaviour-neutral until E1 writes binding.policy. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
…ughput # Conflicts: # backend/tests/unit/test_batch_pipeline_pump.py # backend/utils/batch_pipeline/pump.py # config/feature-flags.yaml
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7d21aa2cca
ℹ️ 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".
| halt.set() | ||
| outcomes = await asyncio.gather(*lanes, return_exceptions=True) | ||
| relaying.cancel() | ||
| await asyncio.gather(maintaining, relaying, return_exceptions=True) |
There was a problem hiding this comment.
Cancel maintenance before awaiting fatal shutdown
When a fatal CUDA error or SIGTERM arrives while _maintain() is awaiting a blocking Firestore operation, this unconditional gather waits for that maintenance task to finish instead of cancelling it. In the worker runtime, the supervisor's tick task therefore keeps /health fresh while state.stopping only closes /ready, so the lone quarantined GPU pod can remain alive and never reach the required process restart until the database call returns. Cancel maintaining before gathering it, as the supervisor already does for its auxiliary tasks.
Useful? React with 👍 / 👎.
| # Periodic recovery and queue sampling get their own cadence so no | ||
| # lane spends a claim/publication window on them between flights. | ||
| maintaining = asyncio.create_task(self._maintain_loop(halt)) | ||
| lanes = [asyncio.create_task(self._lane(halt, maintain=False)) for _ in range(self.flights)] |
There was a problem hiding this comment.
Preserve the per-replica fair-use overshoot bound
When both default lanes claim fresh jobs for an owner near the daily audio ceiling, they can call compute authorization concurrently before either flight is projected into the fair-use meter. utils/batch_pipeline/admission.py explicitly documents that this check-then-act path has no reservation and bounds overshoot to one batch per worker replica; spawning two lanes raises that bound to two batches (16 jobs with the default batch size), allowing extra GPU spend past the hard restriction. Serialize fresh-work spend admission per replica or reserve the usage before admitting the second flight.
Useful? React with 👍 / 👎.
At pipeline depth 2, one replica holds up to depth x capacity claimed units (one chain plus a waiting lane). With the stack capacity of 4 that covers the whole six-unit batch-two-workers scenario, so the peer replica could see no work and the "both replicas drain" assertion failed. Claiming one unit per flight keeps both replicas draining. The cross-replica once-only, capture-order and single paid-call checks are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…puted (#22866) ## Summary The `batch-two-workers` scenario in the Sync Cloud Tasks Stack Gauntlet fails intermittently with "a segment was computed or completed more than once across replicas", and that blocks the Backend Hermetic Merge Gate. This is a test-timing problem, not a production double completion. **When it started.** On main, the scenario passed in all 41 runs before #22373 (10-19 12:24Z). From 10-19 14:40Z it failed with this message in: - 3 of 54 runs before #22805 (Fix B) - 2 of 14 runs between Fix B and #22820 (Fix C) - 1 of 7 runs after Fix C Counting all branches, 15 gauntlet jobs failed this way, and 5 of those failures came before Fix B. So neither Fix B nor Fix C caused it, although Fix C's head-wait probes may add load to the emulator. **Why it fails.** Both counters the assertion checked, `words_started` and `worker_item_result`, are recorded when a segment is computed, not when it is completed. Batch compute is at-least-once by design: 1. A renewal that times out (`HEARTBEAT_TIMEOUT_SECONDS=8`; the emulator takes a collection-wide lock for every transactional query) marks the lease lost. 2. If the re-heartbeat at publication is also ambiguous, the pump drops its result and lets the lease expire. 3. `recover()` re-queues the segment and the other replica leases it again. Publication still happens exactly once. `complete()`, `fail()`, `defer()` and `release()` are all fenced by `owns_lease(job, token, now)` inside the transaction. Result artifacts use create-only random names (`if_generation_match=0`), so a stale holder cannot overwrite the result that was committed. ## Change (test only) `_two_workers` now asserts the real cross-replica invariants: - **Every compute held its own lease.** For each segment, computes and worker results are at most `job.attempt`. A recompute is only allowed after a lease transition. Two replicas computing under one lease still fails. - **Each segment is committed once.** The job state is `committed`, the segment has one result-log entry, and the burst's `log_sequence` values are unique. - **The log chain is intact**, in log order. - **Capture order holds.** If no entry is marked `late_capture`, the burst must be in strict capture order. If some are, every late entry must be a recomputed head (one that outlasted the #22820 bounded head wait), and the remaining entries must still be in capture order. The verified event now records `recomputed_after_lease_loss`, so the rate of recomputes stays visible. ## Verification - `backend/testing/sync_cloud_tasks_stack/run.sh --only batch` (local Firestore emulator, `nice -n 19`): all 10 batch scenarios pass; `batch-two-workers` passed in 64.0s. - `BACKEND_UNIT_TEST_FILE_LIST=<tests/unit/test_sync_cloud_tasks_stack_ci_wiring.py> bash test.sh`: 3 passed. ## Follow-up (not in this PR) `Pump._publish` refuses to publish when the pre-publication heartbeat is ambiguous, even though `complete()` re-checks lease ownership inside its own transaction. When Firestore is slow, that wastes GPU time: a finished result is thrown away and computed again. It is worth measuring with `omi_batch_pipeline_events_total{event="lease_expired"}` before changing it. 🤖 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/22866?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/22866?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F22866&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. -->
…puted batch-two-workers failed ~6-14% of main runs with "a segment was computed or completed more than once across replicas" since 2026-10-19 14:40Z (after BasedHardware#22373, before BasedHardware#22805 and BasedHardware#22820). Both counters it checked (words_started, worker_item_result) are compute-side. Batch compute is at-least-once by design: a lease whose renewal stalls (the emulator takes a collection-wide lock per transactional query; HEARTBEAT_TIMEOUT_SECONDS is 8s) is left to expire, recovered and leased again, while the stale holder's complete() is fenced by owns_lease(token). Publication stays exactly once. The scenario now asserts the real cross-replica invariants: - every compute ran under its own lease (computes <= job attempt); - each segment is committed with exactly one result-log entry; - the burst log chain is intact and in capture order; a late_capture entry is accepted only for a recomputed head that outlasted the BasedHardware#22820 head wait. The verified event records recomputed_after_lease_loss so the rate stays visible. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
BATCH_PIPELINE_WORKER_PIPELINE_DEPTH(default 2, range 1–4,1= exact serial kill switch) runs that many pump lanes per GPU process. A lane can claim, admit and publish while another lane holds the exclusive GPU chain. The GPU chain stays one flight at a time. In the virtual-clock sim this doubles leases/min per replica at the 25% arrival rate (19.6 → 39.6).Merge with current main. Main now has #22371 (leader lease), #22362 (bounded publication), #22458 (recovery wake), #21932, #22461 and #22452. All of the following were kept:
Pump.__init__takespublish_concurrency,leader,inline_metricsandflights._maintainkeeps fix(batch): multi-replica hardening and non-5xx enrichment retries #22371'sleader is None or acquire()check aroundproject_pending,recoverand theresult_readydrain. That drain now uses perf(batch): batch cross-owner publication and per-flight merge drains #22362's_drain_ready_owners. The metrics refresh still goes throughsample_metrics()wheninline_metricsis on._maintainis called both by the depth-1run_onceand by the depth>1_maintain_loop._flightpublishes through perf(batch): batch cross-owner publication and per-flight merge drains #22362's_publish_flight, with bounded cross-owner publication and one drain per owner per flight._owner_serialstays insidedrain_owner, so same-owner merges are serialized across lanes too._gpuis unchanged.run_processpassesflights=worker_pipeline_depth(),leader=LeaderLease(...)andinline_metrics=False.BATCH_PIPELINE_WORKER_PIPELINE_DEPTHandBATCH_PIPELINE_LEADER_LEASE_ENABLEDflag rows are kept, and the registry is regenerated.Why
The prod batch worker is one replica with autoscaling off. At the 5% record-lane ramp it leased about 18–24 jobs/min while recent-backfill ready age climbed to 933 s, and its GPU averaged about 35%.
Pump.run_onceruns every stage in sequence on one asyncio task:project_pending,recover, adue('result_ready', 100)scan that reads each job in its own transaction, and owner drains, plus a metrics refresh every 15 s_pull_shardtransactions with privacy checks and head-priority readscompleteplusdrain_ownerThe GPU is idle during steps 1–3 and 5 of every cycle. The chain itself is already exclusive (
_GPU_CHAIN_LOCK).What
Pump-level overlap only. It doesn't touch merge internals,
process_batchI/O or model batching.BATCH_PIPELINE_WORKER_PIPELINE_DEPTH(Helmworker.pipelineDepth) defaults to 2, allowed range 1–4. It runs that many pump lanes per GPU process.asyncio.Lock. Device and host memory stay at one flight, and there is still exactly oneprocess_batchat a time.1restores the serial loop exactly (the same code path; sim results are identical tomain). A malformed value keeps the default.Scheduler.defer(no attempt charge) instead of starting another chain.Registered in
config/feature-flags.yaml(ops_kill) anddeployment-setting-classification.json. The chart renders the env.Measurement (virtual-clock sim from #22201)
Setup. One pump (one replica), batch 8, production-shaped capture spans (30–120 s, 10 owners), fresh lane, head priority on.
The stock simulation runs every
run_blockingleaf in zero virtual time, so a measurement-only harness (not in this PR) adds a latency model:Calibrated so that
mainreproduces production at saturation: 19.6 leases/min, GPU 34%.Arrival rates come from
sol-ramp-throughput.md§4: 5% ≈ 20.5 jobs/min; 25% = 5× ≈ 102.5 jobs/min. Values are means of seeds 1–3, measured over the steady window (minute 5 to the end of 30 minutes of arrivals).Sensitivity to the database latency assumption (25%, seed 1):
Reading the numbers:
process_batch, which other lanes own.omi_batch_pipeline_stage_secondsprofile should confirm the pump/chain split after an authorized rollout.Review fix (Grok, item 3)
On stop, a lane waiting behind another lane's chain now hands back every lease it claimed, including leases marked lost by a renewal that timed out.
Why: a timed-out renewal marks a lease lost, but the lease may still be ours, and the blocking renewal can still land later. The old hand-back skipped lost leases, so those jobs stayed leased with the pull's attempt charged.
Safety:
deferis fenced byowns_lease, so it never touches a job another owner now holds. This matches the fatal-GPU path.Tests (both cases fail with the old skip):
retryat attempt 0 and is recoverable.retryat attempt 0 and is recoverable.The stop tests no longer assume which lane wins the GPU lock. A later capture that was computed stays
result_readybehind its refunded predecessor. 40 out of 40 repeat runs passed.Lane / contract
Agent A (pump-level flight overlap) of the batch-worker throughput swarm. Owner sign-offs for edits to other lanes' files:
pump.pymerge with #22362 (agent B, opus-worker-publish: author of this resolution) and #22371 (multireplica: resolution follows Grok's 22373 re-review item 5).Product invariants affected
none. Lease, ordered-merge, privacy-fence and paid-intent semantics are unchanged; only concurrency between pump stages changes.
Verification
After merging current main (local, m5,
omi-heavy run --slots 3 -- nice -n 19 bash test.sh), all 17 selected files passed:test_batch_pipeline_{pump,publication,leader,runtime,worker,worker_io,serving,quarantine,quarantine_recovery,scheduler,chart,cohort_config,validation_disposition}.pytest_pipeline_sim*.pytest_pipeline_characterization.pyscripts/check_feature_flag_registry.pypasses.Earlier, at the pre-merge head, the emulator gauntlet
--only batchpassed 7/7.Not run: the gauntlet on the merged head (CI runs it), and no production measurement.
Rollback
Set
worker.pipelineDepth=1(orBATCH_PIPELINE_WORKER_PIPELINE_DEPTH=1) and roll the worker. Revert the PR to undo the pump change.Failure-Class: none
🤖 Generated with Claude Code