Repository navigation
test(backend): batch-pipeline characterization goldens - #22203
Conversation
Add a normalized, externally visible trace of the batch pipeline driven by the pipeline sim (testing/pipeline_sim/trace.py): per segment, the durable job and result-log transitions with bucketed relative times, /recover-quarantine responses, paid calls and final rows; per upload, the intake status, dedupe target and conversation view. IDs are renamed by first appearance and volatile fields dropped, so a behavior-preserving refactor keeps the trace stable. Eight seeded goldens (healthy, padded retry, terminal empty, provider failure -> paid recovery, privacy fence mid-flight, deleted/merged targets, duplicate delivery, revision replacement) are pinned in tests/unit/fixtures/pipeline_sim_goldens. PIPELINE_GOLDEN_UPDATE=1 regenerates them. Perturbation tests prove that skipping the padded retry or disabling the terminal-empty disposition changes the trace. Existing pipeline_sim outputs are byte-identical. Test code only; no production behavior change. 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: c7c0283978
ℹ️ 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".
c7c0283 to
53a56d5
Compare
…ed modules The golden contract claimed backend/utils/batch_pipeline/** and backend/database/batch_pipeline*.py wholesale, but the simulation never executes projection, enrichment, artifacts, speech redrive, purge or the Firestore store itself (SimStore implements the Store protocol; the projector sweep is a model). A regression in those modules would have selected this test and passed with unchanged goldens, certifying coverage that does not exist. Narrow the sources to the real modules the simulation imports and runs (per testing/pipeline_sim/sim.py's inventory): diarizer worker, scheduler, pump, serving, merge, quarantine recovery, recovery disposition, contracts, correctness metrics, worker silence, intake, privacy, projection protocol, quarantine recovery store and staging.
53a56d5 to
87151a9
Compare
|
Addressed the Codex review thread on Fix: the Narrowed Verification: |
# Conflicts: # backend/testing/workflow_contracts.json
…#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)
Stacked on #22201 (pipeline sim). Review that PR first. Once it merges, this PR's base becomes
main.Why
The sync/batch pipeline needs a refactor and tech-debt repayment after the rollout. Today nothing pins its externally visible behavior, so a rewrite can't be checked for equivalence. These goldens make the check concrete: a trace diff means behavior changed.
What
backend/testing/pipeline_sim/trace.pybuilds a normalized trace (pipeline_sim.trace/v1). It reads only durable store state and observable responses, never internal call order.Per segment:
/recover-quarantineresponsesPer upload:
Normalization: IDs are renamed by first appearance and keys are sorted.
Goldens: eight seeded goldens in
backend/tests/unit/fixtures/pipeline_sim_goldens/(144 KB):healthyempty_asr_padded_retryempty_asr_terminalprovider_failure_quarantineprivacy_fence_midflightdeleted_merged_targetsduplicate_deliveryrevision_replacementTests:
tests/unit/test_pipeline_characterization.pyhas 13 tests:failed_heldUpdating:
PIPELINE_GOLDEN_UPDATE=1 pytest tests/unit/test_pipeline_characterization.pyrewrites the goldens. Review the diff in the refactor PR.CI selection: a
batch_pipeline_characterization_goldensworkflow contract selects the test whenutils/batch_pipeline/**,diarizer/batch_pipeline.py,database/batch_pipeline*.py, the sim or the goldens change.Not pinned: the sim's modeled parts (projection and first summary, Parakeet, Modulate, Cloud Tasks, the legacy sync path). The README says so.
Behavior this pins (for reviewers)
skipped_oversizeunit whose paid recovery is also empty settlesfailed_held.speech_redrivewithholds terminal-empty forpadded_skippedunits on purpose.completereturns True. Replayedfailafter quarantine returns False. There is no double commit or double spend.late_capture: trueon the result.Verification
Local, m5,
nice -n 19:BACKEND_UNIT_TEST_FILE_LIST=… bash test.sh(the fast-unit CPU guard) over this file plus the 3 sim files: 42 passed, and every call phase is ~0 s because the simulations run in module fixtures.PYTHONHASHSEEDvalues.Test code only. No production behavior change, no new workflow.
🤖 Generated with Claude Code