Skip to content

perf(batch): raise worker throughput per replica - #22373

Merged
Git-on-my-level merged 12 commits into
mainfrom
lane/opus-worker-throughput
Oct 19, 2026
Merged

Git-on-my-level merged 12 commits into
mainfrom
lane/opus-worker-throughput

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

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:

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_once runs every stage in sequence on one asyncio task:

  1. maintenance every 5 s: project_pending, recover, a due('result_ready', 100) scan that reads each job in its own transaction, and owner drains, plus a metrics refresh every 15 s
  2. claim: up to 8 _pull_shard transactions with privacy checks and head-priority reads
  3. compute admission: the spend RPC
  4. the GPU chain
  5. publication: per-lease complete plus drain_owner

The 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_batch I/O or model batching.

  • BATCH_PIPELINE_WORKER_PIPELINE_DEPTH (Helm worker.pipelineDepth) defaults to 2, allowed range 1–4. It runs that many pump lanes per GPU process.
    • While one lane is in its chain, another lane can claim, get admission, publish, or wait.
    • The chain (fetch/decode through persist and CUDA quiescence, including the memory probe) runs inside one asyncio.Lock. Device and host memory stay at one flight, and there is still exactly one process_batch at a time.
  • When depth > 1, maintenance (recover, the result-ready drain scan, metrics) runs in its own task at the same 5 s/15 s cadence instead of inside a lane between flights.
  • Kill switch: 1 restores the serial loop exactly (the same code path; sim results are identical to main). A malformed value keeps the default.
  • Leases: each lane renews its own leases, including while it waits for the GPU.
    • On SIGTERM, or when a sibling hits a fatal GPU error, a lane that is still waiting refunds its leases through Scheduler.defer (no attempt charge) instead of starting another chain.
    • A fatal GPU error stops all lanes and is re-raised.
  • Unchanged: lease tokens, ordered merge (the transaction remains the per-owner order authority across lanes, as it already is across replicas and the serving reconciler), privacy fences, paid-intent admission and seals, batch size, replicas and HPA.
  • Trade-off: a waiting lane holds one claimed flight, so a fresh arrival can wait up to one extra chain.

Registered in config/feature-flags.yaml (ops_kill) and deployment-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_blocking leaf in zero virtual time, so a measurement-only harness (not in this PR) adds a latency model:

cost value
per transaction 30 ms
per in-transaction read 10 ms
per privacy check 20 ms
per query 30 ms
admission RPC 400 ms
per item, non-GPU chain work 0.3 s
per item, GPU 0.4 s + 0.012 s per audio second

Calibrated so that main reproduces 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).

arrival build jobs leased/min per replica admit→lease p95 GPU util (whole run) backlog drain after arrivals stop
5% (20.5/min) main 19.7 (= arrival) 23.9 s 39% 0.1 min
5% (20.5/min) depth 2 19.8 (= arrival) 4.0 s 39% 0.1 min
25% (102.5/min) main 19.6 1,397 s 34% 127.7 min
25% (102.5/min) depth 2 39.6 (2.0×) 1,110 s 58% 47.1 min
25% (102.5/min) depth 3 39.6 1,098 s 57% 47.1 min
25% (102.5/min) depth 1 (kill switch) 19.6 (identical to main) 1,397 s 34% 127.7 min

Sensitivity to the database latency assumption (25%, seed 1):

DB latency main depth 2 gain
×0.5 26.2 39.7 1.5×
×1 19.8 39.7 2.0×
×2 13.4 34.6 2.6×

Reading the numbers:

  • At depth 2 the replica is effectively chain-bound: depth 3 adds nothing. The next limit is inside process_batch, which other lanes own.
  • At 5% one replica already keeps up on average, so the gain shows as about 6× lower admit→lease p95.
  • These are model numbers, not production measurements. Sol's omi_batch_pipeline_stage_seconds profile 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: defer is fenced by owns_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):

  • The late renewal lands before the refund: the job ends retry at attempt 0 and is recoverable.
  • The late renewal lands after the refund: the cleared token fences it, and the job ends retry at 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_ready behind 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.py merge 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}.py
  • test_pipeline_sim*.py
  • test_pipeline_characterization.py

scripts/check_feature_flag_registry.py passes.

Earlier, at the pre-merge head, the emulator gauntlet --only batch passed 7/7.

Not run: the gauntlet on the merged head (CI runs it), and no production measurement.

Rollback

Set worker.pipelineDepth=1 (or BATCH_PIPELINE_WORKER_PIPELINE_DEPTH=1) and roll the worker. Revert the PR to undo the pump change.

Failure-Class: none

🤖 Generated with Claude Code

Git-on-my-level and others added 3 commits October 19, 2026 10:10
…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]>
@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:43:56.927818Z 7d21aa2 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.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

CI note: the 5 red checks are already red on current main (0d8e125) without this PR. #22321 (preserve pending polls, bounded recovery batches) landed after #22203, #22201 and #22208 were written against the old behavior, and three checks still pin that old behavior:

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.

Git-on-my-level and others added 4 commits October 19, 2026 12:33
…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
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
…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

@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: 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)

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 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)]

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 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]>
@Git-on-my-level
Git-on-my-level merged commit 7d709f4 into main Oct 19, 2026
58 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/opus-worker-throughput branch October 19, 2026 12:24
Git-on-my-level added a commit that referenced this pull request Oct 20, 2026
…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. -->
Andu1223 pushed a commit to Andu1223/omi that referenced this pull request Oct 20, 2026
…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]>
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