Skip to content

feat(edge): D1 Rust listen edge, passthrough + harness (not deployed) - #22921

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

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

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

What changed and why

D1 of plan D (realtime gateway; internal KB projects/backend-target-architecture/plan-d-realtime-gateway.md, §4 and §5). This adds backend/edge/, the listen-edge Rust crate (tokio, hyper and tokio-tungstenite), in passthrough mode only. It accepts /v4/listen, opens the same path and query on an upstream listen URL with the client's headers, and relays text and binary messages in both directions, in order, with byte-identical payloads. Nothing deploys it. No Dockerfile, chart, Helm or deploy workflow changes, and no change to listen's Python behaviour.

The gateway exists so that a deploy stops dropping live sockets. D1 builds and proves that mechanism (the drain) before any decode or VAD work goes in.

In scope

  • Config from env (EDGE_*). Everything is validated at startup, and EDGE_UPSTREAM_URL is the only required key. The table is in backend/edge/README.md.
  • Handshake. The upstream websocket handshake completes before the client gets its 101. Listen's rejections (403 on bad or missing auth) therefore reach the client with the same status and body. If upstream is unreachable the client gets 502, and 504 on a timeout. Hop-by-hop and handshake headers are regenerated; all others are forwarded, and the peer is appended to X-Forwarded-For.
  • Relay. There are two independent pumps per session, so a slow reader on one side never blocks the other direction. Close frames (code and reason) are relayed both ways. A side that ends without a close frame is mirrored to the other side as a drop, exactly what listen sees today when a client vanishes. Pings are answered per hop.
  • Graceful drain on SIGTERM.
    1. /readyz returns 503 immediately, and new sockets are still accepted for EDGE_DRAIN_READY_DELAY_MS (5s) while the load balancer deregisters the pod.
    2. The listener closes. Connections still in their upstream handshake are waited for and drained like any other session.
    3. Each session gets close 1012 at a per-session offset within EDGE_DRAIN_SPREAD_MS (10s), so clients don't all reconnect at once.
    4. Every frame the client sent before it saw the close is still relayed upstream.
    5. Listen then gets 1001, whether the client echoes the 1012 or drops TCP. Listen treats only 1000 and 1001 as ordinary closes, and only 1000 finalizes a desktop conversation (routers/listen/runtime.py _ordinary_client_close and _teardown). With 1001 the conversation stays in progress for the reconnect, as it does today when a client drops.
    6. A client that stops reading cannot stall the drain: every close write is bounded, and the close deadline starts from the session's own drain timer.
    7. The drain is bounded at ready delay + spread + close timeout + 3s (23s by default).
  • Load shedding. EDGE_MAX_SESSIONS (5000) and EDGE_MAX_PENDING_HANDSHAKES (512) return 503 with Retry-After before any upstream work. EDGE_HEADER_READ_TIMEOUT_MS (10s) guards against slow request headers.
  • /healthz, /readyz, /metrics on the same port.
  • Prometheus metrics under plan B's rules.
    • Label values come only from closed enums (outcome, result, direction, kind), plus a bounded release_sha on omi_edge_build_info.
    • There are no uid, session, path or peer labels.
    • Every child is created at startup, and the per-frame path uses cached counters.
    • A unit test fails on any label value outside the enums, or on more than 120 exported series.
  • Harness. FakeListen (tests/common/mod.rs) is a fake listen upstream whose behaviour is chosen per connection by query parameters: echo, flood, blob, close with a code, drop, reject, slow handshake, mute, and linger.
  • CI. .github/workflows/backend-edge.yml runs cargo fmt --check, build, clippy -D warnings and test, only on backend/edge/** changes.
    • Action SHAs are pinned, and the toolchain is pinned to 1.99.1 (also in rust-toolchain.toml).
    • Permissions are contents: read, and the job has a CI budget entry.
    • The first run took 1m04s.

David named this workflow change on 2026-10-20 (two-lane lead session): CI job for backend/edge

Out of scope (D2+): Opus/LC3/AAC decode, Silero VAD, provider legs (Soniox, Modulate, Parakeet window), the SessionBrain gRPC stream, the FakeSoniox/FakeParakeet billing meters (F3, shared with plan F), the container image and deploy.

Product invariants affected

none

How it was verified

Crate (local, rustc 1.99.1, run through omi-heavy at nice 19):

cd backend/edge
cargo fmt --check
cargo clippy --locked --all-targets -- -D warnings
cargo test --locked          # 10 unit + 15 passthrough + 4 drain tests

After the review fixes, the full suite ran 30 times in a row with no failures. Cold build, clippy and test took 85s locally.

Mutation checks confirmed that the tests catch regressions:

  • with close forwarding disabled, the close-code and drain tests fail;
  • dropping 1 in 997 frames fails the lossless test;
  • with connection tasks left untracked, drain_waits_for_handshakes_in_flight fails 3 times out of 3;
  • without the session drain timer, drain_is_bounded_when_client_stops_reading fails.

Real-path smoke: the real /v4/listen behind the edge. The stack was this branch's backend code running the real transcribe router, through the arch-d listenprof harness: Firestore emulator, local Redis, local protocol peers, demo project, loopback only, no credentials. The client was the arch-d Go listen client, sending real 20 ms Opus frames with ADMIN_KEY auth. The edge was the release binary (3 MB). The run used 10 sessions and a 30 s hold.

Check Direct to listen Through the edge
Bad key / no auth handshake 403 / 403 403 / 403
Sessions connected, failed 10, 0 10, 0
Frames the client sent vs frames the edge relayed upstream — 15,844 = 15,844
Transcript messages received 120 120
Listen's close codes (omi_listen_ws_close_total) 7 × 1000, 3 × 1006 7 × 1000, 3 × 1006 (matches the edge outcomes: 7 client_closed, 3 client_dropped)

SIGTERM to the edge mid-session:

  • /readyz 503, /healthz 200;
  • the edge exited 0 after 3.7 s;
  • all 10 sessions ended drained;
  • 6,356 frames sent and 6,356 relayed upstream;
  • listen counted exactly 10 client closes with code 1001;
  • listen's active-socket gauge was 0 afterwards;
  • 0 tracebacks in listen's log.

The smoke and the review found these, all fixed and now covered by tests:

  1. Listen keeps its TCP socket open while it finalizes, after the close handshake. The edge now finishes on the close handshake, not on TCP EOF (close_completes_while_upstream_keeps_tcp_open).
  2. A client that drops TCP on the drain close without replying now gives listen a clean close, not a drop (drain_gives_listen_a_clean_close_when_client_vanishes).
  3. From Grok's review: the drain sends listen 1001, not 1012. A client that stops reading no longer stalls the drain (drain_is_bounded_when_client_stops_reading). Handshakes in flight are tracked; hyper's graceful shutdown broke a pending 101 (drain_waits_for_handshakes_in_flight). Load shedding and a header timeout were added (session_cap_sheds_with_503, slow_headers_are_timed_out). Already-buffered upstream frames are relayed before the drain close. The CI toolchain is pinned.

Listen behaviour this PR doesn't change: on a client-initiated close, listen sometimes keeps sending segments ("Listen segment delivery after close") instead of replying to the close at once. When that takes longer than EDGE_CLOSE_TIMEOUT_MS, the edge records the session as close_timeout. A direct client sees the same wait today.

Not verified here: the goldens (#22203) and simulator replay (#22201) through passthrough, and anything on GKE. D1 is not deployed, so those gates belong to D2 and D3.

Tests

  • tests/passthrough.rs:
    • 3,000 mixed text and binary messages, lossless and ordered both ways, with frame and byte counters checked;
    • 32 concurrent sessions do not interleave;
    • upstream-first flood order;
    • close code and reason in both directions;
    • a 403 rejection is mirrored; upstream down returns 502;
    • an upstream drop and a client drop are mirrored;
    • path, query and headers are forwarded;
    • close-handshake timeout and a lingering upstream TCP socket;
    • the session cap returns 503; slow headers are timed out;
    • health, readiness, metrics and routing.
  • tests/drain.rs:
    • 16 streaming sessions plus one accepted during the ready delay: each client gets 1012, upstream receives exactly frames 0..sent in order and then 1001, and the listener is closed afterwards;
    • a client that vanishes still gives listen 1001;
    • a client that stops reading does not stall the drain, and listen gets 1001;
    • a handshake in flight when the listener closes is waited for and drained.
  • Unit tests:
    • config validation;
    • the metric label enums and series budget;
    • drain jitter;
    • header filtering.

UI evidence

UI-Evidence: none -- backend Rust crate, no UI

Failure class (fixes)

Failure-Class: none

What D2 needs

  • Shadow mirror. Listen mirrors raw frames of a uid-hash cohort to the edge (EDGE_SHADOW_PERCENT). Decode (opus first) and Silero VAD then run in the edge, with VAD agreement and gate-timing metrics against listen. There are no provider legs and no vendor spend.
  • Container image. A listen-edge image built in B's train with OMI_RELEASE_SHA.
  • Pod drain settings. The pod spec needs terminationGracePeriodSeconds above the 23 s drain deadline, and no preStop hook, because the edge handles SIGTERM itself.
  • Before D3 (edge in the path). Confirm that every released client reconnects promptly on close 1012.

🤖 Generated with Claude Code

Git-on-my-level and others added 2 commits October 21, 2026 02:05
Add backend/edge, the listen-edge Rust crate from plan D (realtime gateway),
in passthrough mode only: it accepts /v4/listen, opens the same path and
query on the upstream listen service with the client's headers, and relays
text/binary messages in order with identical payloads both ways. No decode,
no VAD, no provider legs.

- upstream handshake before the client's 101, so listen's rejections
  (e.g. 403) reach the client unchanged; 502/504 when upstream is down/slow
- close codes and reasons relayed both ways; abnormal ends mirrored as drops
- SIGTERM drain: /readyz 503 at once, accept during a deregistration delay,
  then close each session with 1012 over a spread window, relaying every
  frame the client sent before it saw the close; a client that vanishes
  still gives listen a clean 1012 close
- enum-only Prometheus metrics, all series created at startup, with a unit
  test enforcing the label enums and a 120-series budget
- FakeListen harness and integration tests for ordering, close codes,
  drops, rejection, headers, close timeout and drain with frames in flight
- CI: backend-edge.yml runs fmt, build, clippy and test on backend/edge/**
  changes (workflow change named by David on 2026-10-20)

Nothing builds an image or deploys this crate.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- drain sends listen 1001, not the client's 1012: listen treats only
  1000/1001 as ordinary and finalizes desktop conversations only on 1000,
  so 1001 keeps the conversation in progress for the reconnect (verified
  against routers/listen/runtime.py and the real-listen smoke)
- a client that stops reading cannot stall drain: the session starts its
  close deadline from its own drain timer, and every close write is bounded
- connections are tracked from accept, so drain waits for upgrades still in
  their upstream handshake; idle keep-alive sockets are shut down only after
  any in-flight request, since hyper's graceful shutdown breaks a 101
- drain deadline gains slack for the abort close and final flush (23s default)
- load shedding: EDGE_MAX_SESSIONS, EDGE_MAX_PENDING_HANDSHAKES (503 +
  Retry-After) and EDGE_HEADER_READ_TIMEOUT_MS; new handshake result
  "overloaded"
- the upstream pump relays already-buffered upstream frames before the drain
  close
- CI and local toolchain pinned to 1.99.1 (rust-toolchain.toml)
- tests: drain with a client that stops reading, drain with a handshake in
  flight, session cap 503, slow headers; gauge waits no longer race

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level
Git-on-my-level marked this pull request as ready for review October 20, 2026 20:24
@Git-on-my-level
Git-on-my-level merged commit 81de278 into main Oct 20, 2026
62 checks passed
@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-20T20:26:05.943413Z 130b192 Draft marked ready
ℹ️ 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.

@Git-on-my-level
Git-on-my-level deleted the lane/edge-d1 branch October 20, 2026 20:24
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