Repository navigation
feat(listen): D2 edge shadow mirror behind EDGE_SHADOW_PERCENT (default 0) - #22945
Conversation
…lt 0) For a static uid-hash cohort, listen mirrors every decoded client frame (raw payload, capture start sample, decoded sample count) and its own VAD gate's per-window Silero probabilities and gate opens to listen-edge's /v1/shadow, so the edge can measure decode+VAD agreement (plan D, D2). - utils/stt/edge_shadow.py: cohort hash, hashed session key (never a uid), protocol v1 encoders, GateTap, EdgeShadowMirror. offer() only appends to a bounded queue; one background task owns the socket. Overflow, connect or send failure, or an edge close stops that session's mirror. - vad_gate.py: optional edge_tap observes windows/opens; a tap failure detaches the tap, never the gate. activate() reports a new gate. - receiver.py / live_session.py: start the mirror once per single-channel server-STT session, tap every gate, copy frames after capture accept. At the default 0 nothing is read or started. - scripts/edge_shadow_goldens.py: listen's real path over speech fixtures -> recorded mirror streams -> edge replay (+ optional live mirror). - scripts/edge_shadow_gate.py: D2 gate over listen-edge /metrics scrapes. - Registry rows for EDGE_SHADOW_PERCENT (ramp block), _URL and _TOKEN. 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: f9dfd71cb2
ℹ️ 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".
| with open(path, 'rb') as src, open(os.path.join(EDGE_FIXTURES, os.path.basename(path)), 'wb') as dst: | ||
| dst.write(src.read()) | ||
|
|
||
| ok = compared > 0 and agreement >= AGREEMENT_GATE and unmatched == 0 and open_p95 <= OPEN_OFFSET_P95_GATE_MS |
There was a problem hiding this comment.
Reject goldens with unmatched gate opens
When the edge omits gate opens or produces extra ones, opens_unmatched is calculated and printed but never included in ok; the script can therefore pass the gate-open-offset criterion using only a small matching subset while ignoring arbitrarily many missing or spurious opens. Require zero unmatched opens, or otherwise incorporate them into the acceptance gate, so this verification cannot approve a broken edge state machine.
Useful? React with 👍 / 👎.
| try: | ||
| self._queue.put_nowait(None) |
There was a problem hiding this comment.
Record an outcome when teardown cancels the mirror
When a session ends with queued messages or a slow in-progress send, close() only appends a sentinel; the session supervisor can subsequently cancel this tracked task during teardown, and _run() records no outcome for CancelledError. Those sessions disappear from omi_listen_edge_shadow_sessions_total instead of counting as non-completed, biasing the rollout's failure-rate gate toward success; record a terminal cancellation/incomplete outcome before the task exits.
AGENTS.md reference: backend/AGENTS.md:L293-L294
Useful? React with 👍 / 👎.
| if shadow is not None: # D2 edge shadow copy, fire-and-forget | ||
| shadow.frame(start_sample, end_sample - start_sample, data) |
There was a problem hiding this comment.
Document the new listen audio wire contract
This adds a new outbound listen WebSocket carrying raw audio frames and VAD decisions, but backend/docs/listen_pusher_pipeline.mdx is unchanged. That file is the repository-owned audio/listen wire-contract map, so omitting /v1/shadow, its cohort gate, payload behavior, and failure semantics leaves operators and future changes without the required contract documentation.
AGENTS.md reference: backend/AGENTS.md:L159-L159
Useful? React with 👍 / 👎.
| return 0.0 | ||
| if not math.isfinite(value) or value <= 0: | ||
| return 0.0 | ||
| return min(value, 100.0) |
There was a problem hiding this comment.
Fail closed for percentages above 100
When EDGE_SHADOW_PERCENT is accidentally configured above 100, this clamps it to 100 and mirrors every eligible user's raw audio instead of disabling the rollout. Both this function's contract and the new feature-flag registry say out-of-range/invalid values fail closed to zero, so values greater than 100 must return 0.0 rather than silently becoming a full rollout.
Useful? React with 👍 / 👎.
| with open(path, 'rb') as src, open(os.path.join(EDGE_FIXTURES, os.path.basename(path)), 'wb') as dst: | ||
| dst.write(src.read()) | ||
|
|
||
| ok = compared > 0 and agreement >= AGREEMENT_GATE and unmatched == 0 and open_p95 <= OPEN_OFFSET_P95_GATE_MS |
There was a problem hiding this comment.
Enforce the CPU budget in the golden gate
The default golden run can return GATE PASS even when every replay row exceeds the documented 7.92 ms-per-audio-second CPU limit, because ok checks only agreement, unmatched windows, and open offsets while merely printing vad_ms_per_audio_s. Include the replay rows' CPU measurements in this condition so the advertised D2 performance gate cannot approve an edge implementation that is too expensive.
Useful? React with 👍 / 👎.
| encode_gate_start( | ||
| self.gen, | ||
| agc=agc, | ||
| active=gate.mode == 'active', |
There was a problem hiding this comment.
Reannounce the gate after replay restores active mode
When a non-window replacement leg replays retained window audio, process_replay_capture temporarily sets gate.mode to shadow; if that replay packet is the gate's first chunk, this permanently announces the generation as inactive. The wrapper then restores the gate to active without renewing the tap, so the edge continues modeling a shadow gate for the subsequent live tail and its gate-open comparison is invalid. Announce the steady-state mode or start a new generation when replay passthrough ends.
Useful? React with 👍 / 👎.
| receiver.edge_shadow = maybe_start( | ||
| uid=request.uid, | ||
| session_id=host.session_id, | ||
| codec=request.codec, |
There was a problem hiding this comment.
Preserve the declared codec in shadow metadata
For clients declaring opus_fs320, bootstrap normalizes host.request.codec to opus before constructing the receiver, so this always sends codec=opus and the opus_fs320 branch in MIRRORED_CODECS is unreachable in production. As a result, live D2 metrics cannot distinguish or exercise the fixed-frame variant that the golden suite treats separately; use host.declared_codec for the mirror's protocol metadata while retaining the normalized codec for local decoding.
Useful? React with 👍 / 👎.
| if shadow is not None: | ||
| shadow.close() |
There was a problem hiding this comment.
Close the mirror after flushing the final VAD buffer
Every disconnect closes the mirror before _teardown_body() force-flushes the remaining STT buffer. The raw frames for that tail have already been mirrored, but the final gate.process_audio() calls occur after active is cleared and therefore their window probabilities and gate opens are discarded, producing systematic unmatched edge windows at session ends. Move the mirror close until after the forced STT flush has emitted its tap messages.
Useful? React with 👍 / 👎.
| audio = sum(v for (n, _), v in series.items() if n == 'omi_edge_shadow_audio_seconds_total') | ||
| ms_per_s = processing * 1000 / audio if audio else 0.0 | ||
|
|
||
| agree_ok = compared > 0 and agreement >= AGREEMENT_GATE |
There was a problem hiding this comment.
Fail the live gate on unmatched VAD windows
If one codec or variant has some valid comparisons but also many unmatched or not_comparable windows, those discarded windows are only printed and do not affect agree_ok; the rollout gate can therefore pass on a small clean subset while most mirrored data failed to align. Treat either category as a gate failure or include it in the denominator so incomplete comparisons cannot satisfy the 99.5% threshold.
Useful? React with 👍 / 👎.
| patch('utils.stt.vad_gate.run_vad_window', side_effect=_scripted_vad(probs)), | ||
| patch('utils.stt.vad_gate.make_fresh_state', side_effect=_fresh_state), | ||
| patch('utils.stt.vad_gate._get_ort_session'), |
There was a problem hiding this comment.
Patch imported modules instead of string targets
These new tests repeatedly use string-based patch() targets for functions already consumed by the imported VAD module. The backend test contract requires patch.object(target_module, "func") because string lookup can silently patch a different reference after import refactors, allowing the parity tests to pass without controlling the implementation they intend to exercise; import the module object and patch its attributes directly.
AGENTS.md reference: backend/AGENTS.md:L227-L227
Useful? React with 👍 / 👎.
…test, gate coverage - EdgeShadowMirror.frame()/close()/offer() can no longer raise into the session: any unexpected error stops the mirror (send_failed); the outcome metric and task cancel are guarded too. - The stall test now waits until a send is actually stuck on the edge, then proves offers never await, the queue stays bounded, a live task keeps running, and overflow cancels the stuck sender. No wall-clock thresholds. - edge_shadow_gate.py: coverage gate (compared >= 95% of listen windows; not_comparable/unmatched no longer silently ignored) and a counter-reset check on the before/after delta; tests for both. - Goldens harness force-flushes the tail like listen's teardown (43,678 windows, 100.00%). - Registry notes for EDGE_SHADOW_URL/_TOKEN say they are deleted with the mirror. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Grok review round 1 (changes_requested) — addressed in 9fa1cfe:
Also from your harness note: the goldens harness now force-flushes the tail like listen's teardown, and the edge (#22944) does the same. Re-run: 43,678 windows, 100.00% agreement, 129/129 opens on the same chunk. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9fa1cfe550
ℹ️ 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".
| mirror = EdgeShadowMirror( | ||
| url, |
There was a problem hiding this comment.
Ship the shadow endpoint before starting mirrors
The checked target tree contains no /v1/shadow handler, ShadowCore, or edge-shadow-replay binary: backend/edge/src/server.rs:223-241 exposes only health/readiness/metrics and configured proxy paths, while backend/edge/Cargo.toml:9-11 defines only listen-edge. Consequently, configuring this mirror against the repository's shipped edge yields a failed WebSocket upgrade for every session, and the golden command cannot run, so the D2 rollout cannot produce any of its claimed comparison metrics; add and register the edge implementation and replay binary before this path is ramped.
Useful? React with 👍 / 👎.
| self._url = f'{url}?{query}' | ||
| self._headers = {'x-edge-shadow-token': token} if token else {} | ||
| self._connect = connect | ||
| self._queue: asyncio.Queue[Optional[bytes]] = asyncio.Queue(maxsize=queue_messages) |
There was a problem hiding this comment.
Bound the mirror queue by retained bytes
When shadowing is enabled and the edge sender stalls, a client can submit large valid PCM WebSocket messages and this queue retains up to 1,024 complete payload copies before overflow stops the mirror. Because the receive path has no per-audio-frame byte limit, the nominally bounded fire-and-forget path can consume gigabytes for one session and OOM the listen process; enforce a byte budget or stop mirroring oversized frames rather than bounding only the message count.
Useful? React with 👍 / 👎.
| rows = [json.loads(line) for line in out.stdout.splitlines() if line.strip()] | ||
| for row in rows: | ||
| row.update(listen_counts.get(row['stream'], {})) |
There was a problem hiding this comment.
Require one replay row for every golden stream
If the replay binary silently skips a stream or unsupported codec while still exiting zero, this accepts the partial rows list and computes every gate over only the surviving results. A single good stream can therefore produce GATE PASS while entire fixtures, codecs, or gate profiles were never evaluated; verify that row stream names form an exact one-to-one match with streams before calculating the aggregate.
Useful? React with 👍 / 👎.
| audio = sum(v for (n, _), v in series.items() if n == 'omi_edge_shadow_audio_seconds_total') | ||
| ms_per_s = processing * 1000 / audio if audio else 0.0 | ||
|
|
||
| agree_ok = compared > 0 and agreement >= AGREEMENT_GATE |
There was a problem hiding this comment.
Gate agreement per codec and variant
When traffic is skewed, a high-volume healthy Opus/plain lane can mask a broken low-volume PCM or AGC lane because agreed and compared are summed across every (codec, variant) before this check. The script prints per-lane ratios but never gates them, and the golden script performs the same pooling, so a decoder- or variant-specific regression can still receive GATE PASS; require the threshold for every observed or required pair rather than only the fleet-wide ratio.
Useful? React with 👍 / 👎.
…per-service image opt-in (#22971) ## Summary Plan B B2 prerequisites: role images become built, probed and published from one SHA, and each backend-stack service can take its role image by digest. **Merging changes nothing any service deploys.** Every deploy keeps shipping today's image until a dispatch passes `service_images`. David named this workflow change on 2026-10-21 (two-lane lead session): role-image build job + per-service image inputs (plan B B2) 1. **CI role-image build job: new `.github/workflows/role_images.yml`.** - It builds every `backend/Dockerfile.roles` target (`api`, `workers`, `realtime`, `gateway`, `pusher`) and the new `listen-edge` image (`backend/edge/Dockerfile`). - It runs on PRs that touch an image input (Dockerfile.roles, locks, registry, contract scripts, `backend/edge/**`) and on every backend merge to main. - Each Python role image runs its offline dependency probe (`runtime_image_contracts.py smoke --target`). This closes B1's "no built-image probe ran" gap. - `listen-edge` gets an HTTP probe: `/healthz` and `/readyz`, the `omi_edge_build_info{release_sha}` identity, and a clean SIGTERM drain. - Each run records image size and cold-start import time (an offline, timed entrypoint import in a fresh container) in the job summary. On main it also records the fat `backend` image as a baseline. - It has no registry access and pushes nothing. PRs build on the public `python:3.11-slim` base, because no PR workflow holds a GCP credential. 2. **Per-service image inputs in `deploy-backend-stack`, plus the `gcp_backend.yml` dispatch input `service_images`.** - **Format:** `service=gcr.io/<project>/<role image>@sha256:<digest>` pairs for `backend`, `backend-sync`, `backend-sync-backfill`, `backend-integration`, `backend-listen` (needs `deploy_targets=all`) and `llm-gateway` (needs `deploy_gateway=true`). - **Blank, the default, gives today's image everywhere.** - **Validation before any mutation:** `backend/scripts/resolve_service_images.py` checks that each ref is in this project's registry, is the role image the registry maps that service to, carries `OMI_ROLE=<role>`, and is labelled with the admitted SHA. - **Release vector:** `verify_backend_release_vector.py --service-image` expects each moved service at its digest and records it in evidence. The default evidence schema is unchanged. - **Charts:** the listen and gateway charts accept `image.digest`, rendering `repo@digest`. `image.tag` is still required and still set. - The flag is documented in `backend/docs/runbooks/role-image-cutover.md`. 3. **Release-train wiring (main only): new job `gcp_backend.yml` `build-role-images` in `mode=build-only`.** - It shares build-image's boundary, admission, break-glass and Environment, so prod approval and the prod WIF apply. - It builds every role image plus `listen-edge` on the private base at the admitted SHA, stamped with `OMI_RELEASE_SHA` and the revision label, and probes each one before publish. - It pushes `gcr.io/<project>/<image>:<sha7>`. It refuses to overwrite a tag of another SHA and reuses a same-SHA tag. - It prints the digests and a ready-to-paste `service_images` value, and uploads `role-images-<env>.json`. - It deploys nothing. 4. **Structured logging.** `main.py`, `pusher/main.py`, `llm_gateway/main.py` and `utils/messaging/maintenance.py` adopt `omi_logging.configure_logging(..., default_format='text')`. Their five pending logging-guard entries are removed, and the role images (no longer `build_only`) now pass the guard. - **Text mode keeps** today's INFO→stdout / WARNING+→stderr split and `textPayload`. Several live log metrics are `textPayload`-only (messaging maintenance failures, daily summary extractors), so JSON is a per-service `OMI_LOG_FORMAT=json` step after consumer admission (runbook updated). - **Visible deltas:** - the line prefix changes from `INFO:logger:msg` to `INFO logger: msg`; - Uvicorn's own records go through the root handler, so `uvicorn.error` startup lines move from stderr to stdout; - gateway INFO app logs now emit (before, they went to `lastResort`, WARNING+ only); - pusher keeps its access lines (`access_policy='keep'`). The listen-edge image is in this train for D2 (#22945). Its deploy still needs the GKE Deployment and Service, which is D2's deploy step. ## Lane / contract Swarm label `arch-b2` (plan B B2, P8 brief). Owner sign-offs: none needed. B1's files (`Dockerfile.roles`, `runtime_images.json`, the contract script and its tests) are this lane's predecessor. The edge Dockerfile adds no crate changes. ## Product invariants affected INV-DATA-1: path match only (`.github/workflows/gcp_backend.yml`). No desktop-backend deployment authority or customer data-plane route changes; the backend stack keeps its projects and routing. ## Verification All runs were on m5 (shared, high load), through `bin/omi-heavy run -- nice -n 19`. | Layer | Command | Result | |---|---|---| | Unit | `backend/test.sh` on test_role_images, test_resolve_service_images, test_verify_backend_release_vector, test_omi_logging, test_logging_entrypoint_guard, test_runtime_image_contracts, test_backend_listen_helm_defaults (Helm render of digest mode) | all passed | | Unit (touched contracts) | test.sh on test_llm_gateway_deploy_contract, test_rendered_deployment_contract, test_listen_helm_env_overrides, test_internal_gateway_helm, test_messaging_operations, test_messaging_launch_hardening, test_workflow_contracts, test_pusher_deployment_control_workflow, test_logging_config, test_fleet_deployment, and others | all passed | | Static contract | `runtime_image_contracts.py check` | passed, 19 images | | Logging guard | `check_logging_entrypoints.py --base origin/main` | passed, 20 migrations remain (was 25) | | CI budget | `check_ci_budget.py --base origin/main` | passed | | checks-manifest | `run_checks.py --lane local` | all passed except product-invariants, which needed this body (now cited) | | Built image | this PR's `Role Images` run (public base) | all 5 Python role probes ok; api/workers/realtime 2.63 GB, one shared image, cold import 5.3 s; gateway 1.1 s; pusher 1.44 GB, 4.0 s. listen-edge: see latest run | | Review | Grok | FIX-FIRST at 8501aac; 2 blockers + 3 minors fixed in 106ef2c, 1 minor rebutted (PR comment) | **Not run locally:** any docker build. m5 has no Docker daemon up, and B1's local amd64 build OOM'd. This PR's own `Role Images` run is the first built-image probe. The private-base build and the publish path (`build-role-images`) first run on the lead's next build-only train. ## Rollback Revert this PR. Blank `service_images` already ships today's images. A logging rollback is `OMI_LOG_FORMAT=text` (already the default) or a revert. ## Next steps (B3 cutover, lead-owned deploys; out of scope here) 1. **gateway / pusher.** The production gateway ships through `gcp_llm_gateway.yml`, and pusher through `gcp_backend_pusher.yml` with dev-qualified `pusher_image_digest`. Each needs a role-digest input (`backend-gateway`, and `backend-pusher` in the qualification flow) before its production cutover. In development the gateway can cut over now via `service_images=llm-gateway=…` with `deploy_gateway=true`. 2. **messaging-maintenance-job.** Point the admitted image in `deploy/messaging/maintenance-job.json` / `messaging_operations.py` at the `backend-workers` digest. 3. **backend-listen.** `service_images=backend-listen=…` with `deploy_targets=all` (development). The prod path is Cloud Run-only today, so listen prod goes via `gcp_backend_listen_helm.yml`, which needs the same digest input. 4. **Cloud Run four, one train.** `backend` → `backend-api`, and the other three → `backend-workers`. 5. **After each cutover,** delete the replaced registry entry and Dockerfile (§9f.5). Failure-Class: none 🤖 Generated with [Claude Code](https://claude.com/claude-code)
…adow runbook (#23088) ## What changed and why Plan D **D2 deploy prerequisites, chart side** (lane `p41-d2`; D2 code is already on main: edge #22944, listen #22945). Nothing deploys and no env flips: `EDGE_SHADOW_PERCENT` stays **0**. - **New `backend/charts/listen-edge`**: GKE Deployment + ClusterIP Service for the Rust edge, reachable from `backend-listen` pods only (NetworkPolicy; no NEG annotation; no Ingress), `terminationGracePeriodSeconds: 40` above the binary's 23 s worst-case drain, **no preStop** (SIGTERM starts the drain directly), Silero model at the image's baked `EDGE_VAD_MODEL_PATH=/models/silero_vad.onnx`, the listen chart's `privateEnv` pattern for `EDGE_SHADOW_TOKEN`, image by **digest** from the role-image train (B2). Token-less service account, non-root uid 10001, read-only rootfs, zone spread, PDB. Prod 3 replicas @ 1 vCPU / 512 Mi (plan D sizing), dev 2. - **`backend-listen` values plumbing**: `EDGE_SHADOW_URL` = the in-cluster edge `/v1/shadow`, `EDGE_SHADOW_TOKEN` committed empty (privateEnv-overridable through `LISTEN_PRIVATE_VALUES_YAML`), `EDGE_SHADOW_PERCENT: "0"` in the **prod values only** — `scripts/check_feature_flag_registry.py` allows exactly one declaration of a ramp key, so dev relies on the code default 0. - **Runbook `backend/docs/runbooks/edge-shadow-rollout.md`**: lead-owned deploy order (off-peak), the registry ramp 1% → 5% (24 h) → 25% (≥ 3 d) → 0% + remove, the `edge_shadow_gate.py` gates (agreement ≥ 99.5%, coverage ≥ 95%, open-offset p95 ≤ 32 ms, ≤ 7.92 ms per audio second), rollback, invariants. - `backend/docs/feature-flag-registry.md` regenerated (as-of 2026-10-22; the EDGE rows now show their chart values). The deploy-workflow wiring (`.github/workflows/gcp_backend_listen_helm.yml` + digest admission script) is a **separate PR** that waits for David to name the `.github` change. ## Product invariants affected none (no locked path; `backend/charts/listen-edge` and `backend/charts/backend-listen` are not INV-locked). ## How it was verified Repository `BasedHardware/omi`, branch `lane/p41-d2` at `1ccaa70a90`, base `origin/main`. All local commands ran under `bin/omi-heavy run -- nice -n 19`. - `helm template` of the chart with prod and dev values, by digest and by tag; untagged render refused (`image.tag is required`). Rendered Deployment carries grace 40, no `lifecycle`, the env set above, `privateEnv.EDGE_SHADOW_TOKEN` replaces the committed entry exactly once. **Layer: chart render (offline).** - `pytest tests/unit/test_listen_edge_chart.py tests/unit/test_edge_shadow.py tests/unit/test_listen_helm_env_overrides.py`: **85 passed** (12 new chart contract tests + the existing mirror-off-by-default and private-values suites). **Layer: unit.** - `scripts/check_feature_flag_registry.py`: OK after regeneration (it caught the duplicate ramp declaration when `EDGE_SHADOW_PERCENT` was in both listen values files — hence prod-only). **Layer: repo check.** - `cargo test --locked` in `backend/edge` (unchanged crate, pinned 1.99.1 toolchain): **52 passed, 0 failed**. **Layer: unit.** Note `backend-edge.yml` is path-filtered to `backend/edge/**` and does not run on this PR because the crate is untouched. - Offline replay "through the rendered config": rendered the prod chart, asserted its `EDGE_VAD_MODEL_PATH` equals the path `backend/edge/Dockerfile` bakes the model at, then `cargo run --release --bin edge-shadow-replay` with that same source model file over the 3 committed shadow fixtures: all `completed`, `aligned: true`, 0 decode errors, 0 edge/listen-only windows, agreement 1.0. **Layer: offline replay (local).** **Not verified** (by design, lead-owned): any deploy, the live agreement gate (measured only when the lead rolls shadow at 1%), and NetworkPolicy *enforcement* on the prod cluster (declarative here; the ClusterIP + no-NEG boundary holds regardless). ## Tests `backend/tests/unit/test_listen_edge_chart.py` — core path: render by digest, env/model path, listen-only NetworkPolicy, mirror off by default in both listen values files, percent declared once, upstream equals the listen chart's Service name. Error path: untagged render must fail; `networkPolicy.enabled=false` drops the policy. ## UI evidence UI-Evidence: none -- backend chart, values, runbook and tests only. ## Rollback Revert the PR. Nothing is deployed by it; the committed percent is 0 and `EDGE_SHADOW_URL` alone mirrors nothing (`maybe_start` requires percent > 0). Failure-Class: none <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/23088?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/23088?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F23088&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. -->
Summary
Plan D, D2 listen half. Behind
EDGE_SHADOW_PERCENT(default 0, kill switch), listen mirrors a static uid-hash cohort to listen-edge's/v1/shadow(edge half: #22944). Each mirrored session sends every decoded client frame (raw payload, capture start sample, decoded sample count) and its own VAD gate's per-window Silero probabilities and gate opens. The edge decodes and runs the same gate, then exports the agreement. Nothing comes back, nothing reaches a provider, and nothing is spent with vendors. Merging changes no behaviour: at 0 the receiver reads nothing and starts nothing.utils/stt/edge_shadow.py:sha256('edge-shadow:'+uid)into 10,000 buckets, so a uid is always in or out at a given percent and the cohorts nest.sha256('edge-shadow-session:'+session_id)[:32]); the uid is never sent.backend/edge/src/shadow.rs.EdgeShadowMirror:offer()is synchronous and only doesput_nowaiton a bounded queue (1,024 messages, about 10 s of frames); one background task owns the websocket. A full queue, a failed connect (2 s), a failed or slow send (2 s), or an edge close stops mirroring for the rest of that session. A gap would desync the edge's decoder anyway. Outcomes go toomi_listen_edge_shadow_sessions_total{outcome}(completed, queue_full, connect_failed, send_failed, edge_closed).maybe_start/attach_tap: these never raise.vad_gate.py: an optionaledge_tapcollects the window probabilities the gate already computes, plus SILENCE→SPEECH opens. A tap exception detaches the tap and leaves the gate unchanged; a test proves gating output is identical with and without a tap.activate()resets VAD state, so it reports a new gate generation.receiver.py/live_session.py: the mirror starts once per single-channel server-STT session (the ones with capture positions: no multi-channel, no custom STT), only for opus, opus_fs320, pcm8 and pcm16. Every gate built for the session gets a tap (legacy gate, managed-chain standard and window gates, and failover rebuilds). Frames are copied right aftercapture_timeline.accept, and the mirror is closed inreceive_data'sfinally.scripts/edge_shadow_goldens.py(D2 deliverable 4): runs listen's real path offline (opuslib decode, capture positions, the 30 ms STT buffer,VADStreamingGatewith its tap,SessionPcmGain) over speech fixtures × 7 encodings × 2 gate profiles. It records the exact mirror streams and replays them through the edge'sedge-shadow-replay.--edge-urlalso sends them live throughEdgeShadowMirrorto a running edge and gates on its/metrics.scripts/edge_shadow_gate.py: the offline comparator, computing the D2 gate over one or two listen-edge/metricsscrapes:EDGE_SHADOW_PERCENT(rollout, with a ramp block),EDGE_SHADOW_URLandEDGE_SHADOW_TOKEN, plus the regenerated doc.Agreement on goldens
--edge-url, locallisten-edgerelease build)completed; 22,488 windows across opus, pcm16 and pcm8 × plain and agcThe live run's gate: PASS.
Ramp plan (
EDGE_SHADOW_PERCENT; the registry row has the same block)EDGE_VAD_MODEL_PATHset), andEDGE_SHADOW_URLis set on backend-listen. The lead deploys.completedoutcomes onomi_listen_edge_shadow_sessions_total≤ 1%, and listen loop-lag p99 and first-text latency unchanged against unmirrored sessions;scripts/edge_shadow_gate.py --before <scrape at hold start> <scrape at hold end>passes.EDGE_SHADOW_PERCENT=0, or unsetEDGE_SHADOW_URL. New sessions stop mirroring at once, and open mirrors end with their sessions.Lane / contract
edge-d2 (P7, plan D D2), contract: plan D §5 D2 row. Owner sign-offs for edits to other lanes' files: none. The
vad_gate.py,receiver.pyandlive_session.pyedits are additive hooks that are inert at 0.Product invariants affected
none
Verification
tests/unit/test_edge_shadow.py(23 tests,backend/test.sh, file-isolated, CPU guard):maybe_startgating;test_stalled_edge_never_blocks_the_live_session: 20,000 frames are offered against an edge whose send never completes. Every offer returns without awaiting (worst offer < 50 ms on this loaded host, typically microseconds), the queue stays at most at its bound, the mirror stops itself withqueue_full, and a concurrent 1 ms "live" ticker never stalls more than 250 ms.activate(). A tap failure detaches without touching the gate. The receiver reads nothing at percent 0.test_vad_gate.py,test_parakeet_window_live.pyandtest_vad_onnx.py;grep -l 'receive_data(|VADStreamingGate|build_gate|initialize_stt' tests/unit.scripts/check_feature_flag_registry.py: OK.Rollback
EDGE_SHADOW_PERCENT=0(the default) or an emptyEDGE_SHADOW_URL; otherwise revert this PR.Out of scope / next
EDGE_SHADOW_URL, an optional token), then the ramp above.not_comparable, not compared. The D2 gate measures each session's first gate.Failure-Class: none
Line-Count-Exception: backend/routers/listen/receiver.py | 2746 -> 2759 | D2 edge shadow hooks only (mirror start, frame copy after capture accept, close, gate tap); the logic lives in utils/stt/edge_shadow.py
🤖 Generated with Claude Code