Skip to content

feat(listen): D2 edge shadow mirror behind EDGE_SHADOW_PERCENT (default 0) - #22945

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

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

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

…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]>
@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:09:46.603563Z 9fa1cfe 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.

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

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 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 👍 / 👎.

Comment on lines +205 to +206
try:
self._queue.put_nowait(None)

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 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 👍 / 👎.

Comment on lines +2470 to +2471
if shadow is not None: # D2 edge shadow copy, fire-and-forget
shadow.frame(start_sample, end_sample - start_sample, data)

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

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

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 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',

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 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,

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 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 👍 / 👎.

Comment on lines +2528 to +2529
if shadow is not None:
shadow.close()

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

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 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 👍 / 👎.

Comment on lines +317 to +319
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'),

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 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]>
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Grok review round 1 (changes_requested) — addressed in 9fa1cfe:

  1. Major: the stall test never stalled a send, and it relied on wall-clock checks. Fixed. The fake edge now signals when send() is entered, and the test waits for that before offering more frames. It then asserts:

    • frame and offer are plain functions, not coroutines;
    • the queue never exceeds its bound;
    • a concurrent "live" task makes progress between every frame;
    • the stalled send never completes;
    • overflow gives queue_full and cancels the stuck sender.

    There are no wall-clock thresholds, and 200 frames keep it well inside the CPU budget.

  2. Minor: the gate script ignored not_comparable/unmatched, and a counter reset fed a negative delta. Fixed. There is now a coverage gate (compared ≥ 95% of all listen windows), and delta() raises CounterReset on any counter, histogram count or bucket that goes down (exit 2). Both have tests. The histogram p95 stays a conservative bucket upper bound, as you noted.

  3. Nit: frame()/close() were not guarded. Fixed inside the mirror, so receiver.py does not grow. frame, offer and close catch any unexpected error and stop the mirror (send_failed). The outcome-metric increment and _cancel (when called off the loop) are guarded too. Test: test_unexpected_errors_stop_the_mirror_not_the_session.

  4. Registry note for URL/token. The notes now say they are keep config switches for as long as the mirror code exists, and are deleted with it. The registry requires terminal: keep for config switches.

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.

@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: 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".

Comment on lines +357 to +358
mirror = EdgeShadowMirror(
url,

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

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 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 👍 / 👎.

Comment on lines +247 to +249
rows = [json.loads(line) for line in out.stdout.splitlines() if line.strip()]
for row in rows:
row.update(listen_counts.get(row['stream'], {}))

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

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 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 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 9c850bb into main Oct 20, 2026
67 of 69 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/edge-d2-listen branch October 20, 2026 22:24
Git-on-my-level added a commit that referenced this pull request Oct 21, 2026
…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)
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