Skip to content

update(distributed): remote pipeline residuals from #2671, #2680, #2684 - #2708

Merged
inureyes merged 5 commits into
mainfrom
update/issue-2694-pipeline-residuals
Oct 28, 2026
Merged

inureyes merged 5 commits into
mainfrom
update/issue-2694-pipeline-residuals

Conversation

@inureyes

@inureyes inureyes commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

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.

Seven non-security residuals of the remote pipeline work, one PR as the issue asks. Closes #2694.

Frame path: `ProtectedStream::read_frame` interprets the kind byte only after the frame authenticated, so a kind flipped to an invalid value is `FrameRejected` and takes the existing budgeted log path instead of closing silently; an authenticated unknown kind is a distinct error. Messages are encoded straight into their frame buffer (`encode_message_frame`) and sealed in place through the one sealing path (`finish_frame`, `write_prepared_frame`, `MAX_TAG_LEN` with a const assertion), which removes the per-send copy of a 405 KB logits reply.

Pipeline: the forward activation carries the coordinator's `RunEntry` nonce (`ActivationMessage::reply_nonce`), middle stages copy it, and the final stage sends `RunResult` straight to the coordinator, which accepts a `RunResult` only from the last stage (`ExchangeMatch::result_peer`). The reverse relay and `pending_entry_replies` are gone: 3 frames per decoded token instead of 4.

Zero-config: `Activate` / `Abort` follow `Committed` (`ASSIGNMENT_PROTOCOL_VERSION` 2); a peer writes its TOML and starts a stage only on `Activate`, and a commit-phase failure sends `Abort` to every committed peer. The peer TOML header names the assignment flow (`render_peer_assignment_toml`).

Gemma4: `text_prefill_masks` returns `(None, None)` for a stage without a sliding layer, and a `trim_front` parity test covers the `--max-kv-size` path.

Validation: fmt, clippy, the touched lib modules, `zero_config_cluster_init`, and `pipeline_remote_runtime_*` on real qwen3, llama and gemma checkpoints on GB10. The decode throughput measurement runs separately on the final code.
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:models Model architectures, weights, loading, metadata area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Oct 28, 2026
The final stage sent its RunResult to the configured coordinator address. A coordinator listed with an unspecified IP (`0.0.0.0:19000`, which `--pp-auto` writes when the control address follows `--host 0.0.0.0`, and which a peer reuses when it runs from a copy of the coordinator's TOML) names no host to dial, so on another machine the final stage dialed its own loopback and every decode timed out. The stage now records the authenticated source of the coordinator's latest command (every RunEntry follows a PrepareSequence broadcast) and sends the RunResult there, as every other reply already does; the configured address is only the fallback before any command.

AssignmentPushFailed no longer claims that no stage was activated when the failure was an Activate write: every peer had committed by then, so the other peers run a stage, and the message says to stop them.

New tests: `final_stage_sends_run_result_to_authenticated_coordinator_identity` (fails without the fix: the RunResult never reaches the coordinator) and `push_failure_message_distinguishes_activate_failures`. Lib modules remote_service, stage_assignment, runtime and tcp_frame pass; clippy and fmt are clean.

Refs #2694
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review @ 00bb472

No CRITICAL, HIGH or MEDIUM findings; nothing changed on the branch.

Checked and holding:

  • read_frame: the oversize check still runs on the header before any body read or crypto; on a protected stream the kind byte is not interpreted until open succeeds, so a tampered kind (valid or invalid) is FrameRejected, and the authenticated-unknown-kind error needs a valid tag over the header, i.e. the secret.
  • Seal in place: one sealing path (finish_frame), capacity reserves MAX_TAG_LEN (const-asserted against FrameSuite::ALL), sequence handling unchanged, an exhausted sequence fails before the frame is sent.
  • RunResult routing: accepted only from stage_peers.last() with the fresh random nonce and matching request/micro-batch; a stale or middle-stage frame cannot satisfy an exchange. No per-request state left on the stages.
  • Activate/Abort: the only path to a CommittedAssignment is Activate; every other outcome resets committed; peer wait bounded by commit_timeout, coordinator writes by the push deadline; kept streams drop on every path.
  • Send path: one payload copy instead of two; 3 frames per token.

LOW (not fixed):

  • remote_service.rs:291-292,671-675: coordinator_identity is last-command-wins. With a coordinator configured on an unspecified IP (0.0.0.0:19000), PeerMatcher accepts any authenticated identity on that port (peer_identity.rs:88), so a secret holder listening on that port elsewhere can redirect later logits to itself with any command. Needs the secret and a hand-written config (zero-config peers get a concrete address from localize_cluster). Hardening option: bind the reply identity per request at PrepareSequence.
  • tcp_transport.rs:715-727: an authenticated unknown kind closes the stage connection without a log line, so the version-skew case still goes unnoticed there.
  • stage_assignment.rs:930: the peer logs Abort.detail verbatim; the 1 KiB cap is sender-side only (an authenticated coordinator can send up to 64 KiB).
  • tcp_frame.rs:139,229: write_prepared_frame is pub and finish_frame only debug_assert!s the reserved header; a buffer shorter than 9 bytes panics.

Ran: cargo fmt --check, clippy (--features cuda,test-utils --lib --tests -D warnings), and 141 focused lib tests (tcp_frame, tcp_transport, frame_protection, stage_assignment, pipeline remote_service/runtime/activation_transfer, cluster_init, gemma4 stage), all passing.

A peer logged the coordinator's Abort detail verbatim, so an oversize or multi-line detail could flood or forge log lines. The detail is now cut to MAX_ABORT_DETAIL_BYTES at a character boundary and escaped with escape_debug before it is logged.

finish_frame checked the reserved header with debug_assert! only, so a buffer shorter than FRAME_HEADER_LEN panicked in release. It now returns an error, and write_prepared_frame is narrowed to pub(crate) since nothing outside the crate uses it.

Validation: cargo fmt --check; clippy test-fast cuda,test-utils lib+tests -D warnings clean; distributed::tcp_frame (5) and distributed::stage_assignment (18) pass.

Refs #2694
@inureyes inureyes added status:done Completed and removed status:review Under review labels Oct 28, 2026
@inureyes
inureyes marked this pull request as ready for review October 28, 2026 07:41
@inureyes
inureyes merged commit 752db4f into main Oct 28, 2026
31 of 32 checks passed
@inureyes
inureyes deleted the update/issue-2694-pipeline-residuals branch October 28, 2026 07:42
inureyes added a commit that referenced this pull request Oct 28, 2026
…ups (#2720)

## Summary

Implements the six transport and remote pipeline residuals of #2712 in one PR, each wired into the live path (stage service, coordinator exchange, connection pool, TCP transport, router startup) and each backed by a test that fails on 752db4f.

1. **Stage errors reach the coordinator.** `RemoteStageService::handle_activation` reports an execution failure, or a middle stage's failed downstream forward, as `RemoteStageResponse::Error { nonce, request_id: Some(..), state: Some(..) }` to the coordinator (via `send_run_error`); without a reply nonce it logs one warn and sends nothing. The upstream `nonce: 0` send is gone. `ExchangeMatch` gains `error_peers` (`&self.stage_peers[..]` for `RunEntry`, `from_ref(peer)` otherwise) and requires the `Error` to name the run's `request_id`; `forward_sequence` now fails in well under 1 s instead of after `stage_timeout`.
2. **`ServerAtCapacity` backoff.** `connect_with_retry` retries the at-capacity verdict with the refused-connect backoff and returns it, type preserved in the chain, only when the budget is spent; other handshake failures stay terminal. The warn goes through `handshake_warn_allowed` with the new `AtCapacity` class.
3. **Warning budget.** `HandshakeWarnClass::RouterDrop` (`router-drop`) and `AtCapacity` (`at-capacity`), one window slot per class, `router_front.rs` uses `RouterDrop`; `WarnDecision::previous_window_ended_ago` feeds the summary `N cluster warnings ({class}) were logged at debug during the 60s window that ended Ms ago`.
4. **Unknown authenticated kind is logged.** `tcp_frame::UnknownAuthenticatedKind { kind }` (same `Display` text), returned by `read_frame`, classified as diagnostic by `handshake_warn_class`, and `handle_connection` logs `Closing connection from {peer}: {err} (version skew?)` through the budget.
5. **Pool reuse and accounting.** `ProtectedStream::probe_idle() -> IdleProbe { Idle, PendingData, Closed }` (`peer_closed()` kept); `acquire` reuses only `Idle` and returns a `PooledStream` guard (`Deref`/`DerefMut`, `Arc<AtomicUsize>` per peer, decrement on drop) so failed and cancelled sends release their slot; `PoolConfig::router()` (2 retries from 50 ms, 2 s connect) is used by the router transport in `startup.rs`.
6. **TCP `rpc_call` round-trips.** The response is read on the pooled connection the request went out on; the connection is released only after the matching response and dropped on timeout or error. `rpc_pending` and the `RpcResponse` arm of the accept loop are removed (an `RpcResponse` on an accepted connection is logged at debug).

Docs: `docs/distributed.md` (capacity backoff, four classes, summary wording), `docs/CONTINUOUS_BATCHING.md` (router pool profile), and the module docs of `remote_service`, `connection_pool`, `handshake_warn`, `tcp_frame`, `tcp_transport`, `cluster_handshake`. No env vars changed.

## For #2714

Item 1's addressing goes through two helpers on `RemoteStageService` in `src/distributed/pipeline/remote_service.rs`: `fn reply_target(&self, _request_key: &str) -> String` (today `coordinator_identity` with the `coordinator.configured()` fallback; the `Logits` `RunResult` uses it too) and `async fn send_run_error(&self, nonce: u64, request_key: String, message: String) -> Result<()>`, called from `report_activation_failure`. Switching `reply_target` to the per-sequence owner needs no call-site changes.

## Failing-first evidence

The behavioral tests were committed first (d7fd980) and run against the unchanged code (752db4f plus only the test files): 11 of 13 failed, each with the expected failure mode.

| Test | Failure on 752db4f |
|---|---|
| `remote_service::tests::final_stage_execution_error_goes_to_coordinator` | `stage must answer within 5s`: the coordinator receives nothing (the Error went upstream with nonce 0) |
| `remote_service::tests::final_stage_drops_execution_error_without_reply_nonce` | `expect_silence(upstream)` fails: the upstream received the nonce 0 Error |
| `runtime::correlation_tests::error_from_last_stage_fails_forward_promptly` | elapsed assertion: the exchange waited out the 5 s timeout |
| `runtime::correlation_tests::error_from_last_stage_with_wrong_{nonce,request_id}_is_dropped` | pass on both sides (main drops every non-addressed Error); they guard the new acceptance rule |
| `tcp_transport::tests::robustness::server_at_capacity_is_retried_with_backoff` | `cluster handshake with 127.0.0.1:N failed`: returned at once, no retry |
| `tcp_transport::tests::robustness::server_at_capacity_exhausts_retry_budget` | elapsed under 60 ms: no backoff spent |
| `tcp_transport::tests::robustness::failed_send_releases_active_slot` | `total_active` stayed 1 |
| `tcp_transport::tests::robustness::cancelled_send_releases_active_slot` | `total_active` stayed 1 |
| `tcp_transport::tests::robustness::rpc_call_round_trips_over_authenticated_tcp` | `RPC call timed out` |
| `tcp_transport::tests::robustness::timed_out_rpc_call_drops_its_stream` | `total_idle` was 1: the stream was pooled before the wait |
| `tcp_transport::tests::frame_protection::authenticated_unknown_kind_is_logged_before_close` | zero close lines captured |
| `connection_pool::tests::acquire_drops_idle_connection_with_pending_data` | second `accept` timed out: the idle connection was reused |

Tests that use a new API cannot compile on 752db4f; `git grep` of the symbol on that commit returns nothing, which is the evidence: `handshake_warn::tests::router_drops_do_not_suppress_diagnostic_warnings` and `rollover_summary_reports_the_window_age` (`HandshakeWarnClass::RouterDrop`, `WarnDecision::previous_window_ended_ago`), `classifies_unknown_authenticated_kind_as_diagnostic` and `frame_protection::read_frame_reports_unknown_authenticated_kind_typed` (`UnknownAuthenticatedKind`), `connection_pool::tests::pool_config_router_values` and `router_pool_config_fails_fast` (`PoolConfig::router`), and the `probe_idle` assertions added to `peer_closed_probe_is_non_consuming` (`IdleProbe`). The behavioral side of each is covered by the table above (items 3 and 4) or by `disaggregated_router_e2e` (item 5's failover).

## Verification

GB10 (spark-102), `--profile test-fast --features cuda,test-utils`, built outside the lock and run under `gpu-lock run --tag issue-2712` with `MLXCEL_REQUIRE_MODELS=1 MLXCEL_SDPA_DETERMINISTIC=1 -- --test-threads=1`:

| Command | Result |
|---|---|
| `cargo fmt --check` | clean |
| `cargo clippy --profile test-fast --features cuda,test-utils -p mlxcel --lib --tests -- -D warnings` | clean (one deprecated `TcpStream::set_linger` in a new test was replaced by `socket2::SockRef::set_linger` on the way) |
| `cargo test ... --lib distributed::` | 1513 passed, 0 failed, 4 ignored (42 s) |
| `cargo test ... --lib server::router_front` | 35 passed, 0 failed |
| `cargo test ... --test zero_config_cluster_init -- --include-ignored` | 7 passed, 0 failed |
| `cargo test ... --test pipeline_remote_real_models -- --include-ignored --skip glm_moe_dsa` | 10 passed, 0 failed, 1 filtered (82 s) |
| `cargo test ... --test pipeline_server_remote_real_models -- --include-ignored --skip glm_moe_dsa` | 7 passed, 0 failed, 1 filtered (61 s) |
| `cargo test ... --test pipeline_ci_multi_stage_real_models -- --include-ignored --skip glm_moe_dsa` | 4 passed, 0 failed |
| `cargo test ... --test disaggregated_serving_e2e -- --include-ignored` | 2 passed, 0 failed |
| `cargo test ... --test disaggregated_router_e2e -- --include-ignored` | 7 passed, 0 failed (53 s) |

The new tests (25 selected by name, including the adjusted `full_connection_cap_reports_capacity_to_the_client`, `panicking_rpc_handler_releases_its_connection_slot` and `peer_closed_probe_is_non_consuming`) pass on the branch; greedy parity on the real-model targets is unchanged against #2708.

`glm_moe_dsa` is skipped as the issue allows (418.6 GB checkpoint). `make verify-env-var-docs` not run: no env var added or changed.

Closes #2712
@inureyes inureyes added this to the 0.8 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:inference Generation, sampling, decoding (incl. speculative, DRY) area:models Model architectures, weights, loading, metadata priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

update(distributed): remote pipeline residuals from #2671, #2680, #2684

1 participant