Skip to content

feat(edge): D2 shadow ingest — decode, Silero VAD and listen-gate parity - #22944

Merged
Git-on-my-level merged 3 commits into
mainfrom
lane/edge-d2
Oct 20, 2026
Merged

Git-on-my-level merged 3 commits into
mainfrom
lane/edge-d2

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Summary

Plan D, D2 edge half (not deployed). listen-edge gains a shadow ingest, /v1/shadow, where listen mirrors a static uid-hash cohort's raw client frames together with its own VAD window probabilities and gate opens. The edge decodes the frames and runs a port of listen's VAD gate. It then compares the two window by window and open by open. It opens no provider legs, spends nothing with vendors, and sends nothing back to listen or the client. The listen-side mirror (EDGE_SHADOW_PERCENT, default 0) is a separate PR.

  • Decode (src/codec.rs): opus and opus_fs320 (libopus, 120 ms capacity like opus_decode_capacity), pcm16 passthrough, and pcm8 (audioop.bias(-128) + lin2lin(1,2)). LC3 (lc3_fs1030) and AAC come later; the edge rejects them at the handshake and listen does not mirror them.
  • Gate parity (src/gate.rs, port of VADStreamingGate):
    • listen's 30 ms STT-buffer chunking (stt_buffer_flush_size), with split PCM bytes carried across chunks;
    • per-chunk resample to 16 kHz exactly as numpy does it (linspace + interp, truncated to int16);
    • 512-sample windows with the 64-sample context through Silero v6 (src/silero.rs, ort 2.0.0-rc.10, static ORT, one intra- and one inter-op thread, the same model file as listen);
    • chunk speech = any window with prob > threshold (f32 compared as f64, like Python), using the start or continue threshold by gate state (0.65 / 0.65);
    • SILENCE/SPEECH/HANGOVER with 300 ms pre-roll; hangover 4000 ms on the standard lane and 300 ms on the window lane;
    • the window lane's SessionPcmGain AGC copy (float32 multiply, clip, truncating cast).
  • Alignment: the edge decodes every frame on arrival but holds the PCM (up to 10 s) until listen's first gate announces its origin sample. It then starts its own gate there with listen's parameters, so window k covers the same samples on both sides. Later listen gates (failover replacements fed replayed audio, or activate() resets) count as not_comparable. A frame gap ends comparison (desync); listen stops mirroring after any drop.
  • Comparison output:
    • Metrics, every label from a closed enum, series budget 200: omi_edge_shadow_window_compare_total{codec,variant,result}, ..._gate_opens_total{result}, ..._gate_open_offset_seconds, ..._prob_abs_diff, ..._frames_total{codec,result}, ..._processing_seconds_total{stage} (thread CPU time), ..._audio_seconds_total{codec}, ..._sessions_total{outcome} and ..._handshakes_total{result}.
    • Bounded comparison stream: one shadow_session JSON log line per session, keyed by the hashed session key (never a uid), plus at most 5 shadow_window_disagreement lines per session and 20 per second per process.
  • Safety:
    • EDGE_VAD_MODEL_PATH unset (the default) → /v1/shadow answers 503.
    • EDGE_SHADOW_MAX_SESSIONS (default 500) sheds load.
    • An optional EDGE_SHADOW_TOKEN is checked in constant time.
    • On drain, shadow sessions close with 1001.
    • /v1/shadow is reserved and cannot be configured as a proxy path.
  • Offline: edge-shadow-replay <model> <stream>... runs recorded mirror streams through the same ShadowCore and prints one JSON summary line per stream.

Goldens (D2 deliverable 4)

  • Source: there was no curated listen VAD golden set in the repo. The harness (backend/scripts/edge_shadow_goldens.py, in the listen PR) runs listen's real path offline (opuslib decode, capture positions, 30 ms STT buffer, VADStreamingGate with its tap, SessionPcmGain) over the repo's speech fixtures (transcription-release-probe.wav, parakeet-canary-pt.wav, parakeet_route_synthetic.wav) plus a local 20.8 s speech clip. Each clip sits between room-noise gaps longer than the 4 s hangover.
  • Matrix: 7 encodings (pcm16 8/16/48 kHz, pcm8 8 kHz, opus_fs320 16 kHz, opus 16 kHz with 60 ms frames, opus 48 kHz) × 2 gate profiles (standard; window with AGC).
  • Results:
windows compared 43,660 (26,748 speech, 16,912 silence)
agreement 100.00% (gate ≥ 99.5%)
max probability difference 1.8e-6 (libopus 1.6.1 / ORT 1.22 here vs listen's 1.19)
gate opens 129/129 on the same chunk (offset p95 0 ms; gate ≤ 32 ms)
unmatched / not comparable 0
  • Negative controls: dropping the AGC variant moves probabilities (several streams fall below 99.5%), and a 300 ms hangover on standard streams produces edge-only opens. The comparator detects both.
  • CI: tests/shadow.rs replays three of these streams (opus_fs320 standard and window, pcm8 window) and runs the endpoint end to end (scoring, 400/401/503 rejections, 1003 on text, 1001 on drain, session cap).

Lane / contract

edge-d2 (P7, plan D D2), contract: plan D §5 D2 row. Owner sign-offs for edits to other lanes' files: none (backend/edge only).

Product invariants affected

none

Verification

  • Local, backend/edge, through bin/omi-heavy, toolchain 1.99.1: cargo fmt --check, cargo build --locked --all-targets, cargo clippy --locked --all-targets -D warnings, cargo test --locked: 45 tests pass (21 unit, 4 drain, 15 passthrough, 5 shadow). Layer: crate tests plus offline goldens; nothing is deployed.
  • Goldens as above (offline replay through ShadowCore, this Mac).
  • Not run: GKE, a live mirror from a real listen pod, and Linux CPU numbers. On this loaded Mac, decode+VAD measured 4.3–15 ms per audio second by wall clock; the metric now uses the thread CPU clock and must be re-read on GKE.

Rollback

Revert this PR. Nothing deploys it: there is no image, chart or listen sender yet.

D2 deploy needs (lead and David; out of scope here)

  • listen-edge image in B's release train (lane arch-b1), with OMI_RELEASE_SHA and the Silero model at EDGE_VAD_MODEL_PATH.
  • A GKE Deployment and Service reachable from listen only, with terminationGracePeriodSeconds > 23 s.
  • The listen mirror PR, then EDGE_SHADOW_URL plus a non-zero EDGE_SHADOW_PERCENT (ramp plan in that PR).

D3 prerequisites (not needed for D2's agreement harness): FakeSoniox / FakeParakeet with billing meters (plan F F3), LC3 and AAC decode, and confirming that released clients reconnect promptly on 1012.

Failure-Class: none

🤖 Generated with Claude Code

View guided diff Turn on auto-fix

listen-edge gains /v1/shadow, where listen mirrors a uid-hash cohort's raw
frames plus its own VAD window probabilities. The edge decodes (opus,
opus_fs320, pcm8, pcm16; LC3/AAC later), runs a port of listen's
VADStreamingGate (30 ms STT-buffer chunking, numpy-exact per-chunk resample,
512+64 Silero v6 windows via ort, 0.65 thresholds, 300 ms pre-roll,
4000/300 ms hangover, window-lane AGC) and compares window by window and
gate open by gate open. No provider legs, nothing sent back. Metrics use
closed enums only; per-session summary and rate-limited disagreement lines
form the bounded comparison stream. edge-shadow-replay runs recorded
streams offline through the same core.

Goldens recorded from listen's real gate (3 repo clips x 7 encodings x 2
profiles): 100.00% window agreement, max |dp| 1.8e-6, all gate opens on the
same chunk. Three streams are replayed in CI.

Not deployed; EDGE_VAD_MODEL_PATH unset keeps /v1/shadow disabled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 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-20T22:25:41.539077Z 4a9f7ca 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.

Comment on lines +434 to +441
Ok(()) if pcm.len() / 2 != samples as usize => {
self.summary.length_mismatches += 1;
FrameResult::LengthMismatch
}
Ok(()) => FrameResult::Decoded,
};
shadow.frame(codec, result);
self.accept_pcm(start, pcm)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Agentic Security Review
Severity: MEDIUM

on_frame caps the declared samples field to one second of audio, but it still decodes the full binary payload and, on LengthMismatch, passes that entire PCM buffer into accept_pcm / Silero scoring. For pcm16 and pcm8, Decoder copies or expands every byte of the WebSocket message (up to EDGE_WS_MAX_MESSAGE_BYTES, default 16 MiB).

When /v1/shadow is enabled (EDGE_VAD_MODEL_PATH set) and EDGE_SHADOW_TOKEN is unset, anyone who can reach listen-edge can send a tiny samples value with a multi-megabyte FRAME and force decode plus VAD work far beyond the intended 1 s per-frame bound. That CPU lands on the same worker that will also serve /v4/listen.

Impact: Unauthenticated CPU/memory amplification against the shared edge process, bypassing the MAX_FRAME_SECONDS work limit.

Fix in Cursor Fix in Web

Reviewed by Cursor Security Reviewer for commit 78ee79d. Configure here.

Comment thread backend/edge/src/server.rs Outdated
Comment on lines +348 to +376
if shadow.sessions_active.get() >= shared.cfg.shadow_max_sessions as i64 {
shadow.handshake(ShadowHandshake::Overloaded);
return overloaded();
}
let core = match ShadowCore::new(meta, shared.metrics.clone()) {
Ok(core) => core,
Err(_) => {
shadow.handshake(ShadowHandshake::InvalidRequest);
return text(StatusCode::BAD_REQUEST, "bad shadow request\n");
}
};
shadow.handshake(ShadowHandshake::Accepted);
let on_upgrade = hyper::upgrade::on(&mut req);
let task_shared = shared.clone();
shared.sessions.spawn(async move {
let Ok(upgraded) = on_upgrade.await else {
return;
};
let ws =
WebSocketStream::from_raw_socket(TokioIo::new(upgraded), Role::Server, Some(task_shared.ws_config)).await;
shadow::serve(
ws,
core,
task_shared.close_sessions.clone(),
task_shared.cfg.close_timeout,
)
.await;
});
switching_protocols(&key)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Agentic Security Review
Severity: MEDIUM

shadow_upgrade admits sessions by comparing sessions_active to EDGE_SHADOW_MAX_SESSIONS and then spawning the upgrade task. Unlike proxy, it never acquires handshake_slots, and sessions_active is incremented only later inside shadow::serve after the 101 response.

A burst of parallel /v1/shadow upgrades can all pass the cap while the gauge is still low, receive 101s, and spawn more in-flight decode/VAD sessions than the configured 500-session shed. The route is optionally unauthenticated when EDGE_SHADOW_TOKEN is unset.

Impact: Bypass of the documented shadow session quota, allowing a handshake flood to oversubscribe Silero VAD work on the shared edge worker.

Fix in Cursor Fix in Web

Reviewed by Cursor Security Reviewer for commit 78ee79d. Configure here.

@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: 78ee79d61e

ℹ️ 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".

Comment thread backend/edge/README.md
Comment on lines +67 to +68
listen (`backend/utils/stt/edge_shadow.py`, `EDGE_SHADOW_PERCENT`) mirrors a
static uid-hash cohort: every decoded client frame (raw payload, capture start

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 Add the listen-side shadow producer

The endpoint cannot collect live shadow data because the documented producer is absent: a repo-wide search for EDGE_SHADOW_PERCENT, x-edge-shadow-token, and /v1/shadow outside backend/edge finds no sender, and backend/utils/stt/edge_shadow.py does not exist. Consequently, only the checked-in replay fixtures can exercise this feature; no listen session can open the socket or emit FRAME/GATE_START/WINDOWS/OPEN messages.

Useful? React with 👍 / 👎.

Comment on lines +434 to +441
Ok(()) if pcm.len() / 2 != samples as usize => {
self.summary.length_mismatches += 1;
FrameResult::LengthMismatch
}
Ok(()) => FrameResult::Decoded,
};
shadow.frame(codec, result);
self.accept_pcm(start, pcm)

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 Bound PCM work by the declared frame length

When /v1/shadow is enabled without the optional token, an unauthenticated caller can declare at most one second in samples but attach a PCM8/PCM16 payload up to the 16 MiB websocket limit. A length mismatch is merely counted and the entire decoded buffer is passed to accept_pcm, causing thousands of synchronous Silero invocations and large allocations on a Tokio worker; reject the mismatch or truncate/pad to the declared sample count before scoring.

Useful? React with 👍 / 👎.

Comment thread backend/edge/src/server.rs Outdated
Comment on lines +348 to +350
if shadow.sessions_active.get() >= shared.cfg.shadow_max_sessions as i64 {
shadow.handshake(ShadowHandshake::Overloaded);
return overloaded();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reserve shadow capacity atomically

Under concurrent shadow upgrades, multiple requests can observe the gauge below EDGE_SHADOW_MAX_SESSIONS because it is incremented only later, after each spawned upgrade task reaches shadow::serve. A burst can therefore admit well above the configured CPU-protection cap; acquire an atomic/semaphore permit before returning 101 and hold it for the session lifetime.

Useful? React with 👍 / 👎.

Comment thread backend/edge/README.md
Comment on lines +71 to +73
of listen's gate, and compares window by window. Nothing goes back to listen,
the client, or any provider. The wire protocol (v1) is documented in
`src/shadow.rs`.

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 Document the new wire contract in the pipeline guide

This adds a new audio/VAD websocket protocol, configuration, admission behavior, and failure modes, but the commit only documents them in the edge README and leaves backend/docs/listen_pusher_pipeline.mdx unchanged. Add the shadow path and its wire/environment contract to that canonical pipeline document as required for listen WebSocket changes.

AGENTS.md reference: backend/AGENTS.md:L159-L159

Useful? React with 👍 / 👎.

Comment on lines +690 to +695
/// Close out the session: unmatched leftovers, metrics and the summary line.
pub fn finish(mut self, outcome: ShadowOutcome) -> Summary {
let waiting = self.listen_waiting.len() as u64;
if waiting > 0 {
self.count(CompareResult::Unmatched, waiting);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Flush the final STT-buffer remainder

When a session ends with less than 30 ms left in SttBuffer, listen still processes that data via _flush_stt_buffer(..., force=True), but ShadowCore::finish never passes the edge remainder through its gate. If that tail completes a buffered 512-sample VAD window, listen reports a window that the edge marks unmatched, and the edge also undercounts VAD work; flush the remainder before resolving comparisons.

Useful? React with 👍 / 👎.

Comment on lines +614 to +615
let edge_speech = edge_prob as f64 > threshold;
let listen_speech = listen_prob as f64 > threshold;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Compare listen decisions with listen's threshold state

For active gates with continue_threshold < speech_threshold, an earlier edge/listen disagreement can leave their gate states different, so they may use different thresholds on subsequent windows. These lines classify both probabilities using the edge threshold, which can report false agreement—for example, an edge in SPEECH applies the lower continue threshold to a listen gate that is still in SILENCE. Carry listen's per-window decision/threshold or independently track its state before classifying the listen probability.

Useful? React with 👍 / 👎.

Comment on lines +498 to +500
let Some(origin) = origin else {
return Ok(());
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Remember an unalignable first gate generation

If the first GATE_START carries the protocol's unknown-origin sentinel, this returns without recording that a gate has already been seen. A subsequent failover gate with a known origin is then accepted as the initial aligned gate, even though its replay-fed audio is explicitly not comparable, producing misleading agreement and open-offset metrics; retain the first generation as unalignable so all later generations stay not_comparable.

Useful? React with 👍 / 👎.

Comment on lines +25 to +27
format!("{}/../utils/stt/assets/silero_vad.onnx", env!("CARGO_MANIFEST_DIR"))
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Trigger edge CI when the Silero model changes

The new integration tests load backend/utils/stt/assets/silero_vad.onnx, but the checked .github/workflows/backend-edge.yml path filter runs only for backend/edge/** and the workflow file itself. A model replacement can therefore change tensor names, shapes, or probabilities and break this runtime without running the only tests that exercise it; include the model asset path in the workflow trigger.

Useful? React with 👍 / 👎.

Comment on lines +763 to +767
msg = ws.next() => match msg {
// listen's close (echoed by tungstenite on the next poll), a
// drop, or an error all end the session normally.
None | Some(Err(_)) => break ShadowOutcome::Completed,
Some(Ok(Message::Close(_))) => closing = 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 Bound idle and peer-initiated close waits

An accepted mirror can wait on ws.next() forever, and after receiving a Close frame closing = true additionally disables the drain branch while the peer can keep the TCP connection open. Stalled or malicious mirrors therefore retain active-session capacity indefinitely and can force shutdown to hit its global deadline; apply a receive timeout and bound the peer-initiated close phase with close_timeout.

AGENTS.md reference: backend/AGENTS.md:L297-L297

Useful? React with 👍 / 👎.

…ent guards

- Decode and VAD run on a separate bounded runtime (EDGE_SHADOW_WORKER_THREADS,
  default 2; one ORT session per worker), never on the relay/health workers.
- Session slots are reserved atomically before the 101, so concurrent
  handshakes cannot overshoot EDGE_SHADOW_MAX_SESSIONS.
- A decode whose length differs from listen's is padded/truncated to listen's
  count, so later windows stay on listen's positions.
- The window-lane AGC copy keeps an odd trailing byte, so the sample carry
  stays aligned.
- finish() force-flushes the partial STT buffer, as listen's teardown does.
- Repeated WINDOWS ordinals are counted once; position arithmetic is checked.
- Token comparison no longer returns early on a length mismatch.

Goldens unchanged: 43,660 windows, 100.00% agreement, 129/129 opens.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Grok review round 1 (changes_requested) — addressed in 39d103d:

  1. Blocker (opus links dylib=opus on the ubuntu runner, so the build fails): rebutted with evidence. The backend-edge job on this PR's first head (78ee79d) built and passed on ubuntu-latest: cargo build --locked --all-targets, clippy -D warnings, and all tests, including the opus round-trip and the opus golden replays (job edge, 1m36s, run 39497615928). No workflow change was made.
  2. Major (a length mismatch shifts later windows): fixed. A decode whose sample count differs from listen's is padded or truncated to listen's count before scoring (length_mismatch is still counted). Test: length_mismatch_keeps_listen_positions.
  3. Major (AGC drops an odd trailing byte): fixed. The gained copy keeps the leftover byte, so the gate's sample carry stays aligned. Unit vector added.
  4. Major (the session cap is a non-atomic gauge read): fixed. ShadowPool::reserve() takes a slot with an atomic try_update before the 101; the slot is released on drop, including on a failed upgrade. Test: pool_slots_are_reserved_atomically_and_released.
  5. Major (decode and VAD run on the relay/health workers): fixed. Shadow sessions run on a separate multi-thread runtime (EDGE_SHADOW_WORKER_THREADS, default 2, one ORT session per worker thread) and are still tracked for drain. /v4/listen, /healthz and /readyz stay on the main runtime. Overload backs up into the mirror socket, and listen's mirror then stops itself (bounded queue, 2 s send timeout).
  6. Minor (no tail flush): fixed. finish(Completed) force-flushes the partial STT buffer, as listen's teardown does.
  7. Minor (overflow): fixed. checked_add on frame positions (overflow is a protocol error); saturating adds elsewhere. Test: position_overflow_is_a_protocol_error.
  8. Minor (repeated WINDOWS are double-counted): fixed. Ordinals already seen are ignored. Test: repeated_window_reports_are_counted_once.
  9. Nit (token length leak): fixed. The compare runs over the longer input and folds the length difference in. Test added.

Local CI-equivalent run (fmt, build, clippy -D warnings, test): 50 tests pass. Goldens re-replayed through the new build: 43,660 windows, 100.00% agreement, 129/129 opens, 0 unmatched.

@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: 39d103dcae

ℹ️ 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".

.iter()
.enumerate()
.filter(|(_, (_, matched))| !matched)
.map(|(i, (e, _))| (i, e.chunk_start.abs_diff(l.chunk_start)))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Compare the pre-roll boundary when matching opens

When both gates transition on the same chunk but retain different pre-roll—for example, after a ported eviction calculation regresses—this matcher reports a zero-offset matched open because it only compares chunk_start. The protocol carries preroll_start, but that value is otherwise unused, so the shadow experiment can claim gate-open parity even though the edge would forward a different audio span; include the pre-roll boundary in the match or expose its mismatch separately.

Useful? React with 👍 / 👎.

Comment on lines +718 to +720
let waiting = self.listen_waiting.len() as u64;
if waiting > 0 {
self.count(CompareResult::Unmatched, waiting);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Mark unreported edge windows as unmatched

When listen stops mirroring after a local queue drop or the mirror disconnects after FRAME messages have already been scored but before their WINDOWS reports arrive, finish counts only listen reports waiting for an edge result. Edge windows beyond listen_next remain invisible, so the documented agreement ratio can stay at 100% for the reported prefix even though part of the session was never compared; record the missing listen-side reports or invalidate such a session.

Useful? React with 👍 / 👎.

…edupe

- The window-lane AGC copy now carries a sample split across chunks ahead of
  gaining, so Silero always scores whole, unrotated samples (listen's window
  leg ends on such a chunk; the edge no longer garbles the rest).
- Repeated WINDOWS from non-aligned listen gates are counted once per
  ordinal per gen (bounded to 64 gens).

Goldens unchanged: 43,678 windows, 100.00% agreement.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Grok re-review (round 2) — confirmed round-1 items 1, 2 and 4–9 resolved, including the opus rebuttal. Addressed in 4a9f7ca: (1, major) the AGC odd byte is now carried as a whole sample ahead of gaining, so Silero scores unrotated samples (test agc_gate_carries_a_split_sample_before_gaining); (2, minor) repeated WINDOWS from non-aligned gens are counted once per ordinal per gen (test non_aligned_gen_windows_are_counted_once). Local CI-equivalent run: 52 tests pass. Goldens: 43,678 windows, 100.00%.

Git-on-my-level added a commit that referenced this pull request Oct 20, 2026
…lt 0) (#22945)

## 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`**:
- **Cohort**: `sha256('edge-shadow:'+uid)` into 10,000 buckets, so a uid
is always in or out at a given percent and the cohorts nest.
- **Session key**: a hashed key
(`sha256('edge-shadow-session:'+session_id)[:32]`); the uid is never
sent.
- **Encoding**: protocol v1 encoders that match
`backend/edge/src/shadow.rs`.
- **`EdgeShadowMirror`**: `offer()` is synchronous and only does
`put_nowait` on 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 to `omi_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 optional `edge_tap` collects 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 after `capture_timeline.accept`, and the mirror is
closed in `receive_data`'s `finally`.
- **`scripts/edge_shadow_goldens.py`** (D2 deliverable 4): runs listen's
real path offline (opuslib decode, capture positions, the 30 ms STT
buffer, `VADStreamingGate` with its tap, `SessionPcmGain`) over speech
fixtures × 7 encodings × 2 gate profiles. It records the exact mirror
streams and replays them through the edge's `edge-shadow-replay`.
`--edge-url` also sends them live through `EdgeShadowMirror` to 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 `/metrics` scrapes:
  - window agreement ≥ 99.5%;
  - gate-open offset p95 ≤ 32 ms;
  - decode+VAD ≤ 7.92 ms CPU per audio second.
- **Registry**: rows for `EDGE_SHADOW_PERCENT` (rollout, with a ramp
block), `EDGE_SHADOW_URL` and `EDGE_SHADOW_TOKEN`, plus the regenerated
doc.

### Agreement on goldens
| Run | Scope | Agreement | Gate opens | Unmatched / not comparable |
CPU |
|---|---|---|---|---|---|
| Offline (this Mac) | 43,678 windows (tail force-flushed): 3 repo clips
+ a 20.8 s local clip | **100.00%**, max probability difference 1.8e-6 |
129/129 matched on the same chunk (offset p95 0 ms) | 0 | — |
| Live (`--edge-url`, local `listen-edge` release build) | 42/42 mirrors
`completed`; 22,488 windows across opus, pcm16 and pcm8 × plain and agc
| **100.00%** | offset p95 0 ms | — | decode+VAD **4.18 ms** CPU per
audio second |

The live run's gate: PASS.

### Ramp plan (`EDGE_SHADOW_PERCENT`; the registry row has the same
block)
- **Precondition**: listen-edge runs in prod (plan B lane arch-b1 image,
GKE Deployment and in-cluster Service, `EDGE_VAD_MODEL_PATH` set), and
`EDGE_SHADOW_URL` is set on backend-listen. The lead deploys.
- **Cohorts**:
  - **1%** (static uid hash);
  - **5%** after 24 h clean;
  - **25%** for the D2 gate hold of at least 3 days;
- **0% and remove the mirror** after the D2 readout. A shadow is
diagnostic; its end state is removal, not 100%.
- **Clean metrics**:
- **listen**: non-`completed` outcomes on
`omi_listen_edge_shadow_sessions_total` ≤ 1%, and listen loop-lag p99
and first-text latency unchanged against unmirrored sessions;
- **edge**: `scripts/edge_shadow_gate.py --before <scrape at hold start>
<scrape at hold end>` passes.
- **Expander**: dazheng (two-lane lead).
- **Done by**: 2026-11-20 (review_by 2026-11-20).
- **Rollback**: `EDGE_SHADOW_PERCENT=0`, or unset `EDGE_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.py` and
`live_session.py` edits 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):
- percent parsing as a kill switch; cohort determinism, proportion and
nesting; the hashed key;
  - the wire format byte for byte against protocol v1;
- close flushes messages in order; connect failure, edge close and
`maybe_start` gating;
- **`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 with `queue_full`, and a concurrent 1 ms "live"
ticker never stalls more than 250 ms.
- The tap leaves gate decisions identical, reports contiguous ordinals
and the open chunk, marks the AGC variant, and renews on `activate()`. A
tap failure detaches without touching the gate. The receiver reads
nothing at percent 0.
- **Existing tests touching the changed code** pass:
- `test_vad_gate.py`, `test_parakeet_window_live.py` and
`test_vad_onnx.py`;
- 33 receiver, live-session and timeline files: `grep -l
'receive_data(|VADStreamingGate|build_gate|initialize_stt' tests/unit`.
- **Goldens and live check** as above. The layer is offline plus a local
edge process; nothing is deployed.
- `scripts/check_feature_flag_registry.py`: OK.
- **Not run**: a real listen pod mirroring to a deployed edge; that
needs the D2 deploy.

## Rollback
`EDGE_SHADOW_PERCENT=0` (the default) or an empty `EDGE_SHADOW_URL`;
otherwise revert this PR.

## Out of scope / next
- **D2 deploy** (lead and David): the listen-edge image in B's release
train, the GKE Deployment and Service, listen env (`EDGE_SHADOW_URL`, an
optional token), then the ramp above.
- **D3 prerequisites**: FakeSoniox and FakeParakeet with billing meters
(plan F F3; the D2 agreement harness does not need them), LC3 and AAC
decode on the edge, and confirming that released clients reconnect
promptly on 1012.
- **Coverage note**: later listen gates (failover replacements fed
replayed audio) are counted as `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](https://claude.com/claude-code)

@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: 4a9f7cab1f

ℹ️ 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".

Comment on lines +708 to +711
Some((i, offset)) => {
self.edge_opens[i].1 = true;
self.listen_opens.pop_front();
self.count_open(OpenResult::Matched);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Wait for the full open-match window

When the gates diverge and an unmatched edge open already falls within two seconds before a listen open, this branch pairs them immediately even though a much closer edge open may occur in subsequent audio. The method promises to wait until the edge has scored two seconds past the listen open, but that wait currently happens only when no candidate exists, so a short edge delay can be reported as a large offset followed by an edge_only open; defer choosing the nearest match until the comparison window has been fully scored.

Useful? React with 👍 / 👎.

Comment on lines +732 to +734
if let Some((chunk, chunk_start)) = self.stt.as_mut().and_then(SttBuffer::take_rest) {
let _ = self.process(&chunk, chunk_start);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Propagate failures from the final VAD flush

If Silero fails while processing the forced final STT-buffer remainder, this discarded error leaves the session outcome as completed and emits a partial summary rather than the available vad_error outcome. This hides runtime/model failures that occur specifically on the final window in both live shadow sessions and offline replays; propagate the failure or update the outcome before recording the session.

Useful? React with 👍 / 👎.


/// Close out the session: unmatched leftovers, metrics and the summary line.
pub fn finish(mut self, outcome: ShadowOutcome) -> Summary {
if outcome == ShadowOutcome::Completed {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Score pending audio when a short session ends

When listen has VAD disabled or otherwise never sends GATE_START and the mirrored session ends before PENDING_LIMIT_SECONDS, gate and stt remain unset and all decoded frames in pending are discarded here; the fallback in accept_pcm starts only after more than ten seconds. Short no-gate sessions therefore increase audio_seconds while reporting zero VAD windows and VAD CPU, biasing the experiment's CPU measurements; on a completed session, start the fallback gate and flush pending audio before handling the STT remainder.

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 2428d89 into main Oct 20, 2026
57 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/edge-d2 branch October 20, 2026 22:29
Git-on-my-level added a commit that referenced this pull request Oct 21, 2026
…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. -->
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