Repository navigation
test(backend): virtual-clock batch-pipeline capacity simulation - #22201
Conversation
Add backend/testing/pipeline_sim: a deterministic discrete-event simulation that drives the real batch state machine (admit, Scheduler, Pump.run, PipelineWorker, OrderedMerge, Serving.reconcile, QuarantineRecovery, RecoveryStore, the privacy fence) on StrictFirestore with a virtual clock. Parakeet capacity/HPA, the paid Modulate fallback, Cloud Tasks, projection and first summary, the shared executor, the legacy per-owner sequencer and revision drain are small named models citing the code they mirror. A scorer emits a fleet_gate-shaped sample (completion, projection latency, terminal unrecovered speech, quarantine->projection p95 with n, first-summary breaches, obligations over 15m, paid calls) and a verdict. Seven scenarios reproduce the 2026-10-18 production phenomena: serial per-owner burst, provider exhaustion, revision replacement, stale finalize targets, privacy-blocked users, summaries behind transcription, plus a healthy mixed-fleet baseline. Same seed, byte-identical output; 29 tests in ~5 s. A workflow contract selects the sim tests when the batch scheduler, pump, serving, merge, recovery, admission or worker change. Test and harness code only; no production behavior change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… CPU guard 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a6917653bc
ℹ️ 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".
| async def replace(self) -> None: | ||
| old = self.generation | ||
| self.generation += 1 | ||
| self.report.replaced_at = self.clock.now |
There was a problem hiding this comment.
Preserve the originating revision for nested work
When replacement begins, incrementing this global generation immediately causes work spawned later by still-running old-revision tasks to be tagged as belonging to the new revision. For example, the old serving supervisor continues reconciling during request drain and can spawn projections; those units then escape the old-generation cancellation at SIGKILL even though they execute on the retiring instance. This makes the revision-replacement scenario underreport lost background work, so revision identity needs to follow the spawning task rather than the current global generation.
Useful? React with 👍 / 👎.
| try: | ||
| await asyncio.wait_for(asyncio.shield(waiter), timeout) | ||
| return True | ||
| except asyncio.TimeoutError: |
There was a problem hiding this comment.
Release slots when a queued acquisition is cancelled
If a task is cancelled while waiting here, shield leaves its waiter pending and CancelledError bypasses the timeout cleanup. A later release grants that abandoned future and increments in_use, but no task remains to release the slot; queued summaries cancelled during revision replacement can therefore permanently consume executor capacity and produce artificial starvation or incomplete-work verdicts.
Useful? React with 👍 / 👎.
| if record.status != 'admitted': | ||
| continue | ||
| for segment in record.spec.segments: | ||
| failed = record.projected_at is not None and segment.kind == 'speech' and record.failed_segments > 0 |
There was a problem hiding this comment.
Track legacy failures per segment
For a legacy multipart upload where one speech segment fails but another succeeds, failed_segments > 0 marks every speech segment in the upload as no_recoverable_speech. The scorer consequently charges successful segments to the terminal-unrecovered numerator and can turn a mixed result into a false terminal_unrecovered_speech_over_0_2pct verdict; retain each segment's outcome instead of applying the upload-level count to all segments.
Useful? React with 👍 / 👎.
| if kind != SILENCE: | ||
| first = await sim.stt.request(kind, item.duration_seconds, purpose='batch') | ||
| samples = self._decode(item) | ||
| if first == EMPTY and padded_retry_fits(samples, self.config.max_padded_seconds): | ||
| retry = await sim.stt.request(kind, padded_retry_seconds(samples), purpose='padded_retry') |
There was a problem hiding this comment.
Model STT capacity at the packed-window call boundary
For every nonsilent item this makes exactly one capacity-model request using the entire segment duration, then reuses that outcome for all calls made by the real worker. A segment longer than the worker's 30-second window can produce several transcribe_batch calls, while windows from multiple segments can be packed into one call; therefore this one-request-per-item approximation miscounts provider concurrency, queueing, latency, and failure/exhaustion exposure. Since those values drive the capacity scenarios and their gate verdicts, the fake should model requests after speech_windows/pack_windows, at the same boundary as transcribe_batch.
Useful? React with 👍 / 👎.
| job = self.store.get('jobs', segment_id) | ||
| if not job: | ||
| return 'held' | ||
| if job.get('recovery_state') == 'prepared': | ||
| await self.modulate.occupy(job['duration_seconds']) | ||
| outcome = self.recovery.recover(segment_id, job['owner_id']) |
There was a problem hiding this comment.
Fence recovery before consuming provider capacity
When duplicate Cloud Tasks deliveries observe the same prepared row, each delivery waits through occupy() before RecoveryStore.start inside recover() lets only one of them issue the paid call. The losing delivery therefore consumes a provider slot and full synthetic service time despite making no request; with the configured duplicate-delivery scenarios this can inflate recovery queue latency and even consume capacity for work fenced during the wait. Acquire the durable recovery intent before applying provider latency so only the winning delivery occupies capacity.
Useful? React with 👍 / 👎.
| failed_polls = [poll for poll in getattr(result, 'polls', ()) if poll[2] == 1] | ||
| sample['sim']['gate_polls'] = len(getattr(result, 'polls', ())) | ||
| if final and failed_polls: | ||
| # The real gate exits at its first failing poll; report that, plus the end state. | ||
| sample['sim']['end_state_verdict'] = message | ||
| sample['sim']['first_failing_poll_seconds'] = failed_polls[0][0] | ||
| message, code = failed_polls[0][1], 1 |
There was a problem hiding this comment.
Retain the metrics from the first failing poll
When an intermediate poll fails but the workload later drains, this overwrites only the final verdict text and leaves all metric fields from the successful end state. For example, a serial backlog can report GATE_FAIL obligation_over_15m while the returned sample has zero outstanding obligations; calling verdict(sample) or feeding the documented gate-shaped JSON to an external gate then produces a pass. Store and return the first failing poll's sample, or otherwise retain its metric evidence, rather than combining its label with unrelated end-state metrics.
Useful? React with 👍 / 👎.
# Conflicts: # backend/testing/workflow_contracts.json
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 294ec0963e
ℹ️ 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".
| 'result': {'outcome': 'no_recoverable_speech' if failed else 'success'}, | ||
| '_projected_speech': segment.duration if record.projected_at is not None else None, |
There was a problem hiding this comment.
Use actual projected speech in legacy rows
For legacy workloads containing silence or empty ASR, this assigns the full segment duration to _projected_speech and reports a successful result even though _legacy_segment only records speech when the outcome is WORDS. Those segments therefore inflate projected_speech_seconds and projected_success_units, which can dilute genuine terminal failures below the 0.2% threshold or suppress projection_stalled; retain each segment's outcome and emit only its actually projected speech.
Useful? React with 👍 / 👎.
| record.projecting = True | ||
| self.revision.spawn('projection', self._project(record)) | ||
| break |
There was a problem hiding this comment.
Process all projection candidates in each sweep
When one owner has multiple complete bindings ready, this starts only the first and then waits for the next 20-second supervisor tick before considering another. The production Projector.sweep in backend/utils/batch_pipeline/projection.py loops over as many as 100 discovered candidates and synchronously projects each one, so same-owner bindings can drain within a single sweep in capture order. This artificial one-upload-per-owner-per-tick cap inflates projection latency and 15-minute obligations and can flip capacity verdicts; model the bounded production sweep instead of breaking after the first record.
Useful? React with 👍 / 👎.
| await self.modulate.occupy(job['duration_seconds']) | ||
| outcome = self.recovery.recover(segment_id, job['owner_id']) |
There was a problem hiding this comment.
Hold a sync-executor slot during recovery
During provider-exhaustion workloads, the simulated handler holds only a Modulate slot and invokes recover() directly, whereas routers/batch_pipeline.py::recover_quarantine runs the entire blocking recovery call on the shared 16-worker sync_executor. Paid recovery therefore does not contend with simulated projections or summaries, making executor waits and quarantine-to-projection tails optimistically low precisely when recovery volume is highest; model the whole paid recovery operation inside self.sync_exec.run(...).
AGENTS.md reference: backend/AGENTS.md:L263-L275
Useful? React with 👍 / 👎.
…#22921) ## What changed and why D1 of plan D (realtime gateway; internal KB `projects/backend-target-architecture/plan-d-realtime-gateway.md`, §4 and §5). This adds `backend/edge/`, the `listen-edge` Rust crate (tokio, hyper and tokio-tungstenite), in **passthrough mode only**. It accepts `/v4/listen`, opens the same path and query on an upstream listen URL with the client's headers, and relays text and binary messages in both directions, in order, with byte-identical payloads. **Nothing deploys it.** No Dockerfile, chart, Helm or deploy workflow changes, and no change to listen's Python behaviour. The gateway exists so that a deploy stops dropping live sockets. D1 builds and proves that mechanism (the drain) before any decode or VAD work goes in. **In scope** - **Config from env** (`EDGE_*`). Everything is validated at startup, and `EDGE_UPSTREAM_URL` is the only required key. The table is in `backend/edge/README.md`. - **Handshake.** The upstream websocket handshake completes before the client gets its 101. Listen's rejections (403 on bad or missing auth) therefore reach the client with the same status and body. If upstream is unreachable the client gets 502, and 504 on a timeout. Hop-by-hop and handshake headers are regenerated; all others are forwarded, and the peer is appended to `X-Forwarded-For`. - **Relay.** There are two independent pumps per session, so a slow reader on one side never blocks the other direction. Close frames (code and reason) are relayed both ways. A side that ends without a close frame is mirrored to the other side as a drop, exactly what listen sees today when a client vanishes. Pings are answered per hop. - **Graceful drain on SIGTERM.** 1. `/readyz` returns 503 immediately, and new sockets are still accepted for `EDGE_DRAIN_READY_DELAY_MS` (5s) while the load balancer deregisters the pod. 2. The listener closes. Connections still in their upstream handshake are waited for and drained like any other session. 3. Each session gets close **1012** at a per-session offset within `EDGE_DRAIN_SPREAD_MS` (10s), so clients don't all reconnect at once. 4. Every frame the client sent before it saw the close is still relayed upstream. 5. Listen then gets **1001**, whether the client echoes the 1012 or drops TCP. Listen treats only 1000 and 1001 as ordinary closes, and only 1000 finalizes a desktop conversation (`routers/listen/runtime.py` `_ordinary_client_close` and `_teardown`). With 1001 the conversation stays in progress for the reconnect, as it does today when a client drops. 6. A client that stops reading cannot stall the drain: every close write is bounded, and the close deadline starts from the session's own drain timer. 7. The drain is bounded at ready delay + spread + close timeout + 3s (23s by default). - **Load shedding.** `EDGE_MAX_SESSIONS` (5000) and `EDGE_MAX_PENDING_HANDSHAKES` (512) return 503 with `Retry-After` before any upstream work. `EDGE_HEADER_READ_TIMEOUT_MS` (10s) guards against slow request headers. - **`/healthz`, `/readyz`, `/metrics`** on the same port. - **Prometheus metrics under plan B's rules.** - Label values come only from closed enums (`outcome`, `result`, `direction`, `kind`), plus a bounded `release_sha` on `omi_edge_build_info`. - There are no uid, session, path or peer labels. - Every child is created at startup, and the per-frame path uses cached counters. - A unit test fails on any label value outside the enums, or on more than 120 exported series. - **Harness.** `FakeListen` (`tests/common/mod.rs`) is a fake listen upstream whose behaviour is chosen per connection by query parameters: echo, flood, blob, close with a code, drop, reject, slow handshake, mute, and linger. - **CI.** `.github/workflows/backend-edge.yml` runs `cargo fmt --check`, build, `clippy -D warnings` and test, only on `backend/edge/**` changes. - Action SHAs are pinned, and the toolchain is pinned to 1.99.1 (also in `rust-toolchain.toml`). - Permissions are `contents: read`, and the job has a CI budget entry. - The first run took 1m04s. David named this workflow change on 2026-10-20 (two-lane lead session): CI job for backend/edge **Out of scope (D2+):** Opus/LC3/AAC decode, Silero VAD, provider legs (Soniox, Modulate, Parakeet window), the SessionBrain gRPC stream, the FakeSoniox/FakeParakeet billing meters (F3, shared with plan F), the container image and deploy. ## Product invariants affected none ## How it was verified **Crate (local, rustc 1.99.1, run through `omi-heavy` at nice 19):** ``` cd backend/edge cargo fmt --check cargo clippy --locked --all-targets -- -D warnings cargo test --locked # 10 unit + 15 passthrough + 4 drain tests ``` After the review fixes, the full suite ran 30 times in a row with no failures. Cold build, clippy and test took 85s locally. Mutation checks confirmed that the tests catch regressions: - with close forwarding disabled, the close-code and drain tests fail; - dropping 1 in 997 frames fails the lossless test; - with connection tasks left untracked, `drain_waits_for_handshakes_in_flight` fails 3 times out of 3; - without the session drain timer, `drain_is_bounded_when_client_stops_reading` fails. **Real-path smoke: the real `/v4/listen` behind the edge.** The stack was this branch's backend code running the real transcribe router, through the arch-d listenprof harness: Firestore emulator, local Redis, local protocol peers, demo project, loopback only, no credentials. The client was the arch-d Go listen client, sending real 20 ms Opus frames with ADMIN_KEY auth. The edge was the release binary (3 MB). The run used 10 sessions and a 30 s hold. | Check | Direct to listen | Through the edge | |---|---|---| | Bad key / no auth handshake | 403 / 403 | 403 / 403 | | Sessions connected, failed | 10, 0 | 10, 0 | | Frames the client sent vs frames the edge relayed upstream | — | 15,844 = 15,844 | | Transcript messages received | 120 | 120 | | Listen's close codes (`omi_listen_ws_close_total`) | 7 × 1000, 3 × 1006 | 7 × 1000, 3 × 1006 (matches the edge outcomes: 7 `client_closed`, 3 `client_dropped`) | **SIGTERM to the edge mid-session:** - `/readyz` 503, `/healthz` 200; - the edge exited 0 after 3.7 s; - all 10 sessions ended `drained`; - 6,356 frames sent and 6,356 relayed upstream; - listen counted exactly **10 client closes with code 1001**; - listen's active-socket gauge was 0 afterwards; - 0 tracebacks in listen's log. The smoke and the review found these, all fixed and now covered by tests: 1. Listen keeps its TCP socket open while it finalizes, after the close handshake. The edge now finishes on the close handshake, not on TCP EOF (`close_completes_while_upstream_keeps_tcp_open`). 2. A client that drops TCP on the drain close without replying now gives listen a clean close, not a drop (`drain_gives_listen_a_clean_close_when_client_vanishes`). 3. From Grok's review: the drain sends listen 1001, not 1012. A client that stops reading no longer stalls the drain (`drain_is_bounded_when_client_stops_reading`). Handshakes in flight are tracked; hyper's graceful shutdown broke a pending 101 (`drain_waits_for_handshakes_in_flight`). Load shedding and a header timeout were added (`session_cap_sheds_with_503`, `slow_headers_are_timed_out`). Already-buffered upstream frames are relayed before the drain close. The CI toolchain is pinned. Listen behaviour this PR doesn't change: on a client-initiated close, listen sometimes keeps sending segments ("Listen segment delivery after close") instead of replying to the close at once. When that takes longer than `EDGE_CLOSE_TIMEOUT_MS`, the edge records the session as `close_timeout`. A direct client sees the same wait today. Not verified here: the goldens (#22203) and simulator replay (#22201) through passthrough, and anything on GKE. D1 is not deployed, so those gates belong to D2 and D3. ## Tests - `tests/passthrough.rs`: - 3,000 mixed text and binary messages, lossless and ordered both ways, with frame and byte counters checked; - 32 concurrent sessions do not interleave; - upstream-first flood order; - close code and reason in both directions; - a 403 rejection is mirrored; upstream down returns 502; - an upstream drop and a client drop are mirrored; - path, query and headers are forwarded; - close-handshake timeout and a lingering upstream TCP socket; - the session cap returns 503; slow headers are timed out; - health, readiness, metrics and routing. - `tests/drain.rs`: - 16 streaming sessions plus one accepted during the ready delay: each client gets 1012, upstream receives exactly frames `0..sent` in order and then 1001, and the listener is closed afterwards; - a client that vanishes still gives listen 1001; - a client that stops reading does not stall the drain, and listen gets 1001; - a handshake in flight when the listener closes is waited for and drained. - Unit tests: - config validation; - the metric label enums and series budget; - drain jitter; - header filtering. ## UI evidence UI-Evidence: none -- backend Rust crate, no UI ## Failure class (fixes) Failure-Class: none ## What D2 needs - **Shadow mirror.** Listen mirrors raw frames of a uid-hash cohort to the edge (`EDGE_SHADOW_PERCENT`). Decode (opus first) and Silero VAD then run in the edge, with VAD agreement and gate-timing metrics against listen. There are no provider legs and no vendor spend. - **Container image.** A `listen-edge` image built in B's train with `OMI_RELEASE_SHA`. - **Pod drain settings.** The pod spec needs `terminationGracePeriodSeconds` above the 23 s drain deadline, and no preStop hook, because the edge handles SIGTERM itself. - **Before D3 (edge in the path).** Confirm that every released client reconnects promptly on close 1012. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Why
The two-lane rollout found its capacity and ordering failures in slow production ramps:
This simulation reproduces each of them in seconds, locally and in the existing unit CI. A fix shows up as a verdict change before a ramp.
What
backend/testing/pipeline_sim/is a deterministic discrete-event simulation on a virtual clock.Real code, unmodified, on
StrictFirestore:admit,Scheduler,Pump.runPipelineWorker(window packing, padded retry, empty-ASR classification)OrderedMerge,Serving.reconcileQuarantineRecovery.sweep/_dispatch/recover,RecoveryStoreassert_batch_write_allowedPumpandServingsee a virtualtimethrough module-attribute patches that are restored after each run.Small named models, each citing the code it mirrors:
admission.authorizecheckssync_executorScorer: emits a fleet_gate-shaped sample with the same keys the ops gate's
verdict()reads, plus a verdict:CLI:
python -m testing.pipeline_sim run <scenario> [--seed N] [--json] [--param k=v].Scenarios (seed 1)
burst_owner_serial_sequencerK=1obligation_over_15mmixed_fleet_steadyprovider_exhaustion_window(30 min of empty ASR)quarantine_projection_p95_over_5mrevision_replacement_mid_run, background summariesfirst_summary_deadlinestale_finalize_targetsprivacy_blocked_userssummary_behind_transcriptionsharedThe tests pin verdicts and orderings, not absolute latencies, which depend on the profiles. The same seed gives byte-identical JSON.
Findings in real code (for the owners; not changed here)
QuarantineRecovery.sweepbreaks after one dispatch per queried cohort (queuedincluded). When all owners are admitted, that means one dispatch perServingtick (20 s), so about 3 per minute per integration instance. There is no leader, so the fleet rate scales with instances. A quarantine burst faster than that grows the quarantine→projection tail.skipped_oversizeunits that get an empty Modulate response settlefailed_held, with no automatic exit. The terminal-empty disposition requirespadded_empty(job), andspeech_redriveexcludespadded_skipped.Scope
batch_pipeline_capacity_simworkflow contract selects the sim tests when the scheduler, pump, serving, merge, recovery, disposition, admission or worker change.Verification
Local, m5,
nice -n 19, onorigin/maine1fedc6 (after #22194):test.shwith the fast-unit CPU guard (scenarios run in module fixtures).test_workflow_contracts.pyandtest_backend_unit_selector_output.pyadded: 128 passed.check_workflow_contracts.pypasses.🤖 Generated with Claude Code