Repository navigation
feat(distributed): protect every cluster frame with per-connection AEAD - #2684
Conversation
Ignored end-to-end benchmark for the two-stage remote pipeline over loopback TCP: both stages and the coordinator run in one process, every activation crosses an authenticated TcpTransport connection, and the test prints per-repeat and median greedy decode tokens/s for qwen3-0.6b-4bit (128 tokens, 7 repeats plus warm-up, fixed ports 19590-19592). It is the baseline-versus-candidate comparison the per-frame protection decision in #2656 is made against. Refs #2656
The connect-time handshake (#2650) authenticated a connection once and then carried frames in clear text with no MAC, so an on-path attacker on the cluster segment could read activations and commands, alter, inject, replay or reorder frames, or relay a real handshake to obtain an authenticated stream. Every frame after the handshake is now protected under keys derived from that handshake, on every authenticated connection, with nothing new to configure. Design, chosen by the issue's decision rule from loopback measurements on the real transport (round trip / 2 at 8 KiB: unprotected 5.5 us, HMAC-SHA256 12.2 us, AES-256-GCM 7.4 us, ChaCha20-Poly1305 13.8 us): AES-256-GCM with HKDF-SHA256 directional keys (IKM = cluster secret, salt = client nonce || server nonce, info `mlxcel-cluster-frame-v1/{c2s,s2c}`), an implicit per-direction 64-bit sequence as the nonce that never wraps, and the clear `kind || len` header as associated data so an oversize frame is refused before any decryption. A frame that fails to open closes the connection and is logged through the handshake rate limiter without payload bytes. TLS 1.3 was not prototyped: it runs the same AEAD plus record framing and certificates, so it cannot beat candidate 2, which the rule prefers unless 3 is no slower. Module changes: `frame_protection` (suites, key derivation, sealer and opener), `tcp_frame` (`ProtectedStream`, the single protected read and write path, framing moved out of `tcp_transport`), `cluster_handshake` at `PROTOCOL_VERSION` 3 carries the suite byte in both authenticated hellos and returns the session keys to both sides, `connection_pool` stores `ProtectedStream`s with their per-connection state, `TcpTransport` routes `send`, `send_stream`, RPC requests and responses and the inbound reader through it, so the Thunderbolt and RDMA wrappers and the disaggregated roles inherit it through the shared core, and the `--pp-auto` stage assignment channel rides the same codec instead of its own u32 + JSON frames. `TcpTransportConfig::frame_suite` exists only so the benchmark can measure the alternatives; there is no unprotected authenticated mode. Validation: the five proxy acceptance tests (tampered, replayed, reordered, cross-connection splice, clear-text pattern) were written first and all failed against the unmodified transport (the tampered frame arrived as `inuegrity`; replay, reorder and splice were delivered; the pattern was readable), and pass now; `distributed::frame_protection`, `cluster_handshake`, `tcp_transport`, `connection_pool`, `stage_assignment` and `bench_activation` module tests pass; clippy and fmt are clean. Measurement tables and the threat model are in docs/distributed.md. Closes #2656
The coordinator commands, stage responses and activation messages are serde_json documents, and their bulk `Vec<u8>` fields (`RunEntry.input_ids` and `attention_mask`, `RunResult.logits`, the activation message's `tensor_data`, `attention_mask` and `position_ids`) encoded as JSON arrays of numbers, about 3.6 characters per byte. A frame trace of the two-stage qwen3-0.6b-4bit decode bench showed every token crossing the wire twice as a 1.1 MB frame (the final stage returns the logits to the entry stage as a reverse activation, which forwards them to the coordinator), so a 14 ms decode step spent most of its time encoding and parsing JSON number arrays, and the per-frame AEAD of #2656 ran over 2.2 MB per token. `pipeline::wire_bytes` adds two serde `with` modules that write those fields as one base64 string in human-readable formats (1.33 characters per byte) and as raw bytes otherwise. The same decode step now moves two 405 KB frames, and the remote pipeline decodes qwen3-0.6b-4bit at about twice the rate of main on loopback with per-frame protection on. Wire change: a build with this encoding does not read the array form (mixed versions were already unsupported, and the handshake `PROTOCOL_VERSION` moved to 3 in the same release). Validation: round-trip unit tests for both modules and for `RunResult`, `RunEntry` and `ActivationMessage` through serde_json, including the typed error for invalid base64 and the refusal of the old array form; `distributed::pipeline::` tests and the qwen3 and qwen3.5 remote real-model parity tests pass. Refs #2656
Replace the provisional end-to-end numbers and the deviation text with the final interleaved comparison (main 4144ecf and main HEAD unprotected, the branch with the codec disabled, and the final branch), the attribution of the first result (frame trace, in-process AES cost, framing-only variant), the compact tensor encoding wire change, and the clean decision for AES-256-GCM by the issue's rule. Refs #2656
…tion The `--cluster-secret-file` help text still said the secret "does not encrypt traffic", and the disaggregated security section of docs/distributed.md still said the handshake "authenticates connections, not individual frames". Both contradict #2656, which encrypts and authenticates every frame on an authenticated connection, so an operator reading either would underrate what the cluster ports now protect. Also corrects two statements in the new measurement section: ChaCha20-Poly1305 is 1.8 us slower than HMAC at 8 KiB (14.0 vs 12.2 us, the text said 1.6), and `cluster_frame_bench` binds both transports on loopback, so it cannot print a two-node table as the text claimed. The connection pool module comment no longer says RPC replies are read on pooled streams (nothing reads them); it now states the property the pool does rely on, that a failed or cancelled send drops its connection instead of releasing it. Comment and documentation only; `cargo fmt --check` passes. Refs #2656
Implementation Review SummaryIntent
Findings Addressed
Remaining Items
Verification
|
The decode continuation ordering check in router_front still said the role transport authenticates connections "but not individual frames". Since #2656 every frame on an authenticated role connection is encrypted and authenticated under per-connection keys, so the comment now attributes tamper, replay and reorder rejection to the transport and keeps the point that the sequence check is not a defense against a member that holds the secret. Comment-only change; clippy -D warnings and fmt are clean. Refs #2656
Security and performance reviewNo CRITICAL or HIGH findings. One stale claim fixed in ec5fdc9 (router_front comment still said the role transport does not authenticate individual frames). Checked and found sound: nonce uniqueness (sequence advances inside Left (LOW, not fixed):
Verification: fmt, clippy |
Frame keys are now derived with a per-channel HKDF info label (mlxcel-cluster-frame-v1/<channel>/c2s|s2c), with distinct channels for the TCP transport core and the stage assignment channel, so the two never share keys for the same handshake inputs. The handshake gains client_handshake_on and server_handshake_on that take a FrameChannel; client_handshake and server_handshake keep their signatures and use the transport channel. The assignment listener and dialer use the assignment channel. Frames that fail authentication on the assignment channel are logged through the shared handshake rate limiter (warn, then debug), without payload bytes, instead of an unlimited info line. The base64 sequence visitor of the stage protocol no longer trusts size_hint: the preallocation is capped at 64 KiB. Adds tests for the oversize header refusal before any body read or crypto (at the ProtectedStream level and on the transport, which closes the connection) and for key separation between channels. docs/distributed.md documents the channel labels and the pre-tag allocation bound as a residual. Validation: cargo fmt --check, clippy --profile test-fast --features cuda --lib --tests -D warnings, distributed:: lib tests (1433 passed), pipeline_remote_runtime qwen3 and qwen35 real-model parity (passed). Refs #2656
…uster-frame-protection
…uster-frame-protection
… (#2708) Closes #2694. The seven residuals of #2671, #2680 and #2684 in one PR, each with its own test. Reconciled against current main: the handshake `PROTOCOL_VERSION` stays 4 (#2705), the `FrameRejected` call sites keep their `handshake_warn` budget unchanged, and `ProtectedStream::peer_closed` (#2700) is untouched. ## Per item 1. `read_frame` interprets the kind byte after `FrameOpener::open` on a protected stream: a tampered invalid kind is `FrameRejected` through the existing budgeted call sites (no call-site change); an authenticated unknown kind is `unknown message kind {n} from an authenticated peer`. Plain streams and the header-only oversize check are unchanged. 2. `encode_message_frame` reserves the header and `MAX_TAG_LEN` (32, const-asserted against `FrameSuite::ALL`); `finish_frame` is the one sealing path, used by `write_prepared_frame` (`TcpTransport::send`) and by `write_frame(kind, &[u8])`. A buffer shorter than the header is an error, not a panic, and `write_prepared_frame` is `pub(crate)`. `serialize_message` is test-only. 3. `ActivationMessage::reply_nonce` (`serde(default)`) carries the `RunEntry` nonce from the entry stage through middle stages; the final stage sends `RunResult` to the coordinator's authenticated identity (the source of its most recent command, so a coordinator configured on `0.0.0.0` still gets the reply across hosts). A reverse activation, or a nonce-less forward activation on the final stage, is dropped with a warn. `PendingEntryReply`, its map and the `pending_entry_replies` fields are gone. `ExchangeMatch::result_peer` is `stage_peers.last()` for `RunEntry` and the command's peer otherwise; `Ack`, `State`, `Error` keep `peer`. Frames per decoded token: 3 (`RunEntry`, forward activation, `RunResult`) instead of 4. 4. `render_peer_assignment_toml` (shared `render_toml_body`) is what a `--pp-peer` writes; the coordinator renderer and its callers are unchanged. 5. `Activate` / `Abort { detail }` after `Committed`, `ASSIGNMENT_PROTOCOL_VERSION` 2. The peer delivers only on `Activate`; `Abort`, another frame, close or the commit timeout reset `committed` and return it to listening. The coordinator activates all peers after every commit (a failed `Activate` write is an `AssignmentPushFailed` entry whose message says the other peers are running) or aborts every committed peer (detail cut to 1 KiB) when any commit failed. The peer logs a received detail bounded to 1 KiB and escaped to one line. The residual window is in the module docs. 6. `text_prefill_masks` returns `(None, None)` when `sliding_attn` is `None`. 7. `two_stage_split_matches_dense_after_front_trim_bitwise` (12-token prefill, `trim_front(4)` on every `Cache::Standard`, 3-token continuation, one decode step, bitwise against dense). Docs: `docs/distributed.md` (assignment protocol, peer TOML header, reply authorization, 3-frame per-token flow); no Korean counterpart exists for these sections. ## Failing-first evidence Run against the unchanged behaviour before each fix, green after: - Item 1 `protected_stream_rejects_tampered_invalid_kind_as_frame_rejected`: `a tampered invalid kind must surface as FrameRejected, got: unknown message kind: 255`; `protected_stream_reports_authenticated_unknown_kind_distinctly`: `unexpected error: unknown message kind: 255`. - Item 3 `final_stage_sends_run_result_to_coordinator_not_upstream`: `stage must answer within 5s (it may have died): Elapsed(())`; `run_result_from_last_stage_completes_forward`: `remote stage 10.1.1.1:1 timed out after 5s`; `run_result_from_entry_stage_is_dropped_in_multi_stage_pipeline`: `a RunResult from a stage other than the last must not complete the exchange`; `final_stage_sends_run_result_to_authenticated_coordinator_identity` (coordinator configured as `[::]:port`): `Elapsed(())` when the reply went to the configured address. - Item 5 `peer_discards_committed_assignment_on_abort_and_activates_on_the_next`: `the peer delivered an assignment that was never activated`; `coordinator_aborts_committed_peers_when_another_commit_fails`: `the real peer delivered an assignment the coordinator aborted`. - Item 6 `text_prefill_masks_without_sliding_layer_builds_no_mask`: `a stage without a sliding layer must not allocate a sliding mask`. ## Item 7 sensitivity A temporary mutation (never committed, file restored byte for byte, sha256 `de5f8b65…c457036` before and after) gave the stage path an offset-sized global prefill mask (`Some(create_causal_mask(seq_len, first_cache_offset(caches, "full_attention")))` instead of `None`). The trim test then fails with `3-token continuation prefill after trim_front(4): stage logits differ from the dense logits (max abs diff 5.46875e-2)`. It is the only gemma4 stage test whose scenario has `offset != live_len` (12 vs 8). ## Decode throughput `pipeline_remote_decode_bench` (qwen3-0.6b-4bit, 2 stages, loopback, 128 tokens, 7 timed repeats after a warm-up per run), main 433560c (A) and this branch (B) interleaved A B over 5 rounds on a quiet GB10, each run under `gpu-lock`. Both binaries were built with the bench's fixed port moved to 19990 (local only, not committed). Greedy tokens are identical in all 80 repeats. | | per-round medians (tok/s) | median of medians | range | |---|---|---|---| | main | 120.67, 140.70, 131.38, 140.29, 136.73 | 136.73 | 120.67 to 140.70 | | branch | 149.33, 142.75, 159.04, 156.94, 162.01 | 156.94 | 142.75 to 162.01 | The branch is about 15% faster, and its slowest round beats main's fastest. ## Verification (GB10 spark-102, `--profile test-fast --features cuda,test-utils`, test binaries built outside the lock and run under `gpu-lock`, `--test-threads=1`, `MLXCEL_REQUIRE_MODELS=1 MLXCEL_SDPA_DETERMINISTIC=1`, at 7c8d340) - `cargo fmt --check` and `cargo clippy ... --lib --tests -- -D warnings`: clean. - `--lib distributed::`: 1494 passed, 4 ignored. `--lib models::gemma4`: 127 passed, 15 ignored. - `zero_config_cluster_init --include-ignored`: 7/7 (the `zero_config_cli_*` rehearsals drive the real binaries through Activate). - `pipeline_remote_real_models --include-ignored --skip glm_moe_dsa`: 10/10. `pipeline_server_remote_real_models --include-ignored --skip glm_moe_dsa`: 7/7. The skipped `glm_moe_dsa` tests need the 418.6 GB `glm5-4bit` checkpoint, which cannot load on a 128 GB GB10. - `pipeline_ci_multi_stage_real_models --include-ignored`: 4/4, including `pipeline_multi_stage_three_host_real_model_parity` (logits now skip the middle stage) and the two-host smoke. - `disaggregated_serving_e2e` 2/2, `disaggregated_router_e2e` 7/7, `disaggregated_e2e` 51/51 (all `--include-ignored`). ## Compatibility The stage RPC messages change shape (`pending_entry_replies` is gone from `Ack` and `State`, `RunResult` comes from the final stage) while the handshake `PROTOCOL_VERSION` stays 4. A node built from main between #2705 and this PR therefore completes the handshake with a node built from this PR and then fails with exchange timeouts instead of a version error. No tagged release is affected (the latest is v0.8.0-beta.1, before the v3 and v4 handshakes); upgrade all nodes together.
Summary
Every frame on an authenticated cluster connection is now encrypted and authenticated with AES-256-GCM under per-connection keys derived from the handshake (HKDF-SHA256, IKM = cluster secret, salt = client nonce || server nonce, info
mlxcel-cluster-frame-v1/<channel>/{c2s,s2c}, where the channel label separates the transport core from the stage-assignment channel), with an implicit per-direction 64-bit sequence as the nonce (never sent, never wraps) and the clearkind || lenheader as associated data, so an oversize frame is refused before any decryption. A frame that fails to open closes the connection and is logged through the handshake rate limiter without payload bytes. HandshakePROTOCOL_VERSIONis 3 (suite byte in both authenticated hellos; a suite mismatch gets an explicit rejection record). Nothing new to configure: the existing secret sources are the only input and there is no opt-out;TcpTransportConfig::frame_suiteexists only so the benchmark can measure the alternatives.Protected channels: pooled outbound connections,
send,send_stream, RPC requests and responses, the inbound reader (oneProtectedStreampath, no second framing copy), the Thunderbolt and RDMA wrappers and the disaggregated router, prefill and decode roles through the shared TCP core, and the--pp-autostage assignment channel (nowControlframes of the same codec instead of its own u32 + JSON frames). RDMA has no data path that bypasses the TCP core. The assignment channel usesclient_handshake_on/server_handshake_onwithFrameChannel::Assignment, so its keys differ from transport keys even under the same secret;client_handshake/server_handshakekeep their signatures and useFrameChannel::Transport.Residuals: an on-path attacker can still drop or delay frames, and frame lengths, kinds and timing stay visible; a member holding the secret is a full member; a frame within
max_frame_size(256 MiB by default) is allocated and read before its tag is checked, which only an authenticated peer can reach (same allocation as main). Pre-existing on main and unchanged here: the TCPrpc_callreply is written back on the pooled outbound stream, which nothing reads.Measurements (loopback, GB10 spark-102, quiet box, 2026-10-27)
One-way latency = half the round trip of a
TensorDatamessage echoed over a second authenticated connection (both ends' frame work included);cargo test --test cluster_frame_bench -- --ignored --nocapture.Full p95/p99 for every row are in docs/distributed.md. The 1 and 2 MiB rows bracket the JSON-encoded per-token logits reply; there AES-256-GCM is inside loopback noise of the unprotected rows while HMAC-SHA256 adds 0.6 and 1.2 ms per one-way transfer.
Attribution of the first e2e result
The first interleaved run (5 rounds) showed -11 percent (71.3 vs 63.5 tok/s). Attribution with throwaway instrumentation (not committed):
RunEntry, a 7.5 KB forward activation (hidden state, JSON), and two frames of about 1.1 MB each, because the final stage returns the logits to the entry stage as a reverse activation and the entry stage forwards them to the coordinator asRunResult. Both carry 304 KB of f16 logits as a JSON array of numbers (3.6 characters per byte), so 2.2 MB per token were sealed and opened.ProtectedStreamwith a null codec, same handshake and plumbing) interleaved with main and the protected branch, 3 rounds: main 69.1 (65.8 to 73.4), protected 65.6 (56.1 to 66.0), framing-only 63.5 (61.1 to 66.1) tok/s. Framing-only is not faster than protected, so the plumbing costs nothing measurable and the remaining gap beyond the AEAD cost is run-to-run noise on this box (main itself spans 66 to 75 across rounds). A main-HEAD baseline rebuilt with the exact flags produced the orchestrator's binary hash, ruling out a build-flag difference.Final end-to-end decode (qwen3-0.6b-4bit, two stages, 128 tokens, 7 repeats + warm-up, 5 interleaved rounds, quiet GB10)
Against the main baseline the combined change is +94 percent, but most of that gain comes from the compact tensor encoding, not from protection, so the protection-only delta is reported separately: compact unprotected vs compact protected is -4.0 percent of a 7.3 ms step (about 0.3 ms per token for two 405 KB frames), with overlapping spreads. Judged on protection alone that is above 2 percent, but the rule's fallback (HMAC-SHA256) is slower than AES-256-GCM at every payload size, so it would cost more throughput and give up confidentiality; no opt-out was added.
Decision: AES-256-GCM, no opt-out. This deviates from the rule's 2 percent clause read on protection alone (see above), because the rule's fallback is slower at every size. At 8 KiB it is 4.8 us faster than the HMAC candidate and 1.9 us above the unprotected baseline (inside the 20 us / 5 percent clause), it is the cheapest candidate at every payload size (HMAC-SHA256 costs 0.6 and 1.2 ms more per 1 and 2 MiB transfer, ChaCha20-Poly1305 0.8 and 1.4 ms), and end-to-end decode against main improves. Candidate 3 (TLS 1.3 via tokio-rustls with an exporter-bound handshake) was not prototyped: its record layer runs the same AEAD primitives plus 16 KiB record framing, a second handshake per connection and certificate generation, so it cannot be faster than candidate 2, which the rule prefers unless 3 is no slower; it would also make
rcgena runtime dependency.Wire change: compact tensor bytes in the stage protocol (second commit)
pipeline::wire_bytesadds serdewithmodules that encode the bulkVec<u8>fields ofRunEntry(input_ids,attention_mask),RunResult(logits) andActivationMessage(tensor_data,attention_mask,position_ids) as one base64 string in JSON (1.33 characters per byte) and as raw bytes in a non-human-readable format. One encoding path; round-trip unit tests for the modules and for the three message types, including the typed error for invalid base64 and the refusal of the old array form. A build with this encoding does not interoperate with one without it; mixed versions were already unsupported andPROTOCOL_VERSIONmoved to 3 in this PR. Documented in docs/distributed.md.Test-first evidence
The five proxy tests in
src/distributed/tcp_transport_frame_tests.rs(declared fromtcp_transport_tests.rs) use only APIs that exist on main and learn the frame trailer length from a calibration frame, so the same code ran against the unmodified transport first: all five failed (tampered_frame_is_rejected: the frame arrived asinuegrity;replayed_frame_is_rejected,reordered_frames_are_rejected,frame_from_other_connection_is_rejected: the frames reachedrecv();activation_bytes_are_not_visible_on_the_wire: the pattern was readable). They pass on this branch. Two more tests cover the oversize header:protected_stream_refuses_oversize_header_before_bodyandtransport_closes_connection_on_oversize_header(the frame is refused from the header, nothing reachesrecv(), the connection closes).Verification
distributed::lib module on the final head (includesdistributed::pipeline::, thewire_bytestests and the oversize-header tests): 1433 passed, 0 failed, 4 ignored (CUDA,--test-threads=1, gpu-lock).MLXCEL_REQUIRE_MODELS=1 MLXCEL_SDPA_DETERMINISTIC=1, under gpu-lock):pipeline_remote_runtime_qwen3_real_model_parity_and_cleanupandpipeline_remote_runtime_qwen35_real_model_parity_and_cleanuppass. The unit did not run llama/gemma3/gemma4; the pre-merge check below did.cluster_frame_bench::frame_protection_candidates_loopback(ignored, run under gpu-lock); e2e:pipeline_remote_decode_benchinterleaved base/cand, 5 runs each.cargo clippy --profile test-fast --features cuda -p mlxcel --lib --tests -- -D warnings,cargo fmt --check: clean. No env var added.Pre-merge check (main merged in, head 69a32b2)
make verify-fmt,make verify-env-var-docs,cargo clippy --features cuda,test-utils -p mlxcel --lib --tests -- -D warnings: clean.--lib distributed:: server::startup server::router_front: 1560 passed, 0 failed.MLXCEL_REQUIRE_MODELS=1 MLXCEL_SDPA_DETERMINISTIC=1):pipeline_remote_real_modelsllama/gemma3/gemma4/qwen3/qwen35 parity plus llama drain 6/6,pipeline_server_remote_real_models5/5,pipeline_ci_multi_stage_real_modelstwo-host smoke 1/1.--test zero_config_cluster_init --include-ignored: 7/7 (the stage-assignment channel now runs over the frame codec).--test disaggregated_e2e: 51/51.--test disaggregated_serving_e2e(1 failure, client handshake "secret mismatch") and--test disaggregated_router_e2e(4 of 7 fail: node-failure 500, twoprompt_tokens_detailsbody mismatches, one byte-fallback usage count) fail identically on main 5dfbfb3, so they predate this PR and are tracked separately.Changes during review
--cluster-secret-filehelp, the disaggregated trust-model section of docs/distributed.md, and a router comment.FrameChannelin the HKDF info), so a connection redirected between the stage transport listener and the assignment listener cannot reuse keys across them.visit_seqpath inwire_bytescaps its preallocation at 64 KiB instead of trustingsize_hint.Follow-up candidate
The stage protocol still ships the logits twice per token (final stage to entry stage, entry stage to coordinator) and as JSON; a binary frame or a direct final-stage reply would halve the remaining per-token bytes.
Closes #2656