Skip to content

fix(distributed): make disaggregated serving and router e2e pass - #2700

Merged
inureyes merged 4 commits into
mainfrom
fix/issue-2695-disaggregated-e2e
Oct 28, 2026
Merged

inureyes merged 4 commits into
mainfrom
fix/issue-2695-disaggregated-e2e

Conversation

@inureyes

@inureyes inureyes commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

Fixes the four independent causes behind the failing real-process disaggregated e2e tests. No assertion in either e2e file is weakened; the only change to an existing assertion is the diagnostic one in post_completion (the failure message now carries the router's response body).

Root cause and fix per item

  1. Handshake secret mismatch (test bug). TestClusterSecretFile keyed the in-test client from the 32 random bytes while spawned roles key from the 64 hex characters in the file (ClusterSecret::from_file uses them verbatim). The helper now keys secret() / auth() from the exact bytes it wrote, so the router fixtures (fix(distributed): harden cluster pre-auth admission and rejections (#2674 follow-ups) #2692) can reuse it, and creates the file owner-only (0600) so spawned roles no longer log the permission warning. from_file is unchanged; the to_hex doc now says the hex string is itself the secret.
  2. Router 500 after a prefill node dies. Observed body on unmodified product code (run with MLXCEL_DECODE_TIMEOUT=30 so the handoff timeout fires in 30 s instead of 600 s): {"error":{"message":"timed out waiting for the prefill first token"}}. This matches the inferred cause: ConnectionPool::acquire reused an idle connection whenever peer_addr() succeeded, which stays true in CLOSE_WAIT, so the write "succeeded" into a dead socket and failover never ran. New ProtectedStream::peer_closed does one non-blocking MSG_PEEK of one byte directly on the socket (socket2::SockRef), so it consumes nothing and leaves the AEAD codec alone; the pool drops closed streams and falls through to connect_with_retry, whose refused connect drives the existing failover. I used a direct peek instead of peek().now_or_never() because the reactor path returns None until the runtime has observed the FIN, which makes the check timing-dependent. Unmodified code failed this e2e in 2 of 3 runs (the race depends on which prefill node gets the first post-failure request); with the fix it passed 5 of 5.
  3. Router omits usage.prompt_tokens_details. Router chat and completions responses and usage chunks now report cached_tokens: 0 when config.prompt_cache.is_enabled() and omit the field otherwise, the same predicate single node uses. Completion response and usage-chunk construction moved into completion_response / completion_usage_chunk; chat builders take cache_enabled. No wire change.
  4. Decode node ignores the configured EOS. ingest_handoff_as_active now applies merge_config_stop_tokens before merged_eos_token_ids and RowSampler::new. The new parity test asserts the prefill count plus the decode Done count equals single node's completion_tokens, because the decode Done counts only decode-generated tokens and the router adds both phases.

Byte-fallback finding

Neither MiniCPM "byte_fallback" e2e test reached byte fallback: ▁Café (69435) and ▁café are single vocabulary pieces. Each test now loops over cases: the original prompt is kept (the chat one is the EOS regression, 1 token then </s>), and a new case whose output contains a character no vocabulary piece holds (Ш in " Шарик" for completions, 6 tokens; Ч in "Чай" for chat, 4 tokens). The test asserts that premise against tokenizer.json before the unchanged parity assertions.

Verification (GB10, --profile test-fast, MLXCEL_REQUIRE_MODELS=1, MLXCEL_SDPA_DETERMINISTIC=1, under gpu-lock)

Failing first (fix absent): test_secret_file_auth_matches_server_resolution, acquire_discards_idle_connection_whose_peer_closed, send_to_peer_that_closed_its_pooled_connection_fails, router_usage_reports_zero_cached_tokens_when_prompt_cache_enabled, and serving_handoff_parity_stops_on_config_eos_minicpm (decode ids [69435, 2, 1345, ...] vs reference [69435]) all failed.

With the fix (final acceptance re-run by the orchestrator at head 86e0a89, same results as the developer run):

  • disaggregated_serving_e2e --include-ignored: 2 passed
  • disaggregated_router_e2e --include-ignored: 7 passed (46 s), no soft-skips
  • disaggregated_e2e: 51 passed
  • lib distributed::connection_pool distributed::tcp_transport server::router_front: 64 passed
  • lib serving_handoff_parity --include-ignored: 6 passed (qwen3 siblings now find models/mlx/ checkpoints too)
  • cargo clippy --profile test-fast --features cuda -p mlxcel --lib --tests -- -D warnings, cargo fmt --check, cargo check --profile test-fast --features cuda,test-utils -p mlxcel --tests

Out of scope, noticed: router chat content for the "café" case is " Café" while single node returns "Café" (leading space); the chat test does not compare content.

Closes #2695

The real-process disaggregated e2e tests failed on main for four independent reasons; each is fixed with a regression test that fails before the fix.

- Test secret helper: TestClusterSecretFile keyed its in-test client from the raw random bytes while spawned roles use the hex file contents verbatim, so the serving e2e handshake failed with "secret mismatch". The helper now keys from the exact bytes it wrote and exposes secret() for reuse; the to_hex doc says the hex string is itself the secret.
- Router failover after node death: ConnectionPool::acquire treated an idle connection as alive when peer_addr() succeeded, which stays true in CLOSE_WAIT, so the first request after a prefill node died was written into a dead socket and timed out with HTTP 500 "timed out waiting for the prefill first token". ProtectedStream::peer_closed does one non-blocking MSG_PEEK (no bytes consumed, codec untouched) and the pool drops closed streams, so the refused reconnect drives the existing failover.
- Router usage: chat and completions responses and usage chunks now carry prompt_tokens_details.cached_tokens = 0 when the prompt cache is enabled, matching single node; response construction moved into small testable helpers.
- Decode node EOS: ingest_handoff_as_active merges the checkpoint's configured EOS into the request stop tokens like single-node intake and the prefill handoff, so MiniCPM-2B (llama format) stops at </s>.

The MiniCPM byte-fallback e2e tests never reached byte fallback ("Café" is one vocabulary piece); each now also runs a case whose output needs <0xXX> pieces and proves it against the vocabulary.

Closes #2695
@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:high High priority area:router Continuum router routing, config, and integration labels Oct 28, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Make the disaggregated serving and router e2e suites pass by fixing the test secret helper, stale pooled connections, router prompt_tokens_details, and the decode node's configured EOS, without weakening any parity assertion.

Findings Addressed

No CRITICAL or HIGH findings; no fix commits were needed.

Remaining Items

  • peer_closed treats a socket with unread bytes as alive, so a peer that wrote data and then exited is still reused. Only rpc_call responses (used by distributed::bench, never read back from the pool) can leave such bytes; the router path sends nothing back on pooled connections. (LOW, informational)
  • TestClusterSecretFile writes the secret with the default 0644 mode, so every spawned role logs the chmod 600 warning. Behavior predates this PR; worth setting 0600 when fix(distributed): harden cluster pre-auth admission and rejections (#2674 follow-ups) #2692 reuses the helper. (LOW)
  • Router chat returns " Café" where single node returns "Café" (leading space), already noted in the PR body as out of scope. Needs a follow-up issue. (MEDIUM, out of scope)

Review notes

  • peer_closed: one MSG_PEEK of one byte on the non-blocking fd. It cannot consume bytes or block, and it leaves tokio's readiness and the AEAD codec untouched. WouldBlock and EINTR mean alive; EOF and errors mean closed. In acquire, a dead stream is popped and dropped without touching active, so pool accounting stays correct.
  • prompt_tokens_details: config.prompt_cache.is_enabled() is the predicate single node uses to build its store, so state.prompt_cache.is_some() matches it. All four builders (chat and completions, stream and non-stream) are covered by tests.
  • e2e diff (whitespace-insensitive): every parity assertion is kept; changes are the per-case loops, the post_completion body, and byte-fallback cases checked against tokenizer.json.

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass: clippy -D warnings, cargo fmt --check, cargo check with cuda,test-utils; lib distributed::connection_pool, distributed::tcp_transport, distributed::tcp_frame, server::router_front: 64 passed. The three new socket tests passed 25 of 25 repeats; with acquire reverted to peer_addr().is_ok(), both pool and transport regression tests fail. Real-model e2e suites were not rerun here.

TestClusterSecretFile wrote the secret with the default 0644 mode, so every spawned mlxcel-server role logged the `chmod 600` warning from ClusterSecret::from_file. The helper now creates the file with create_new and mode 0600 on unix, so it is never group- or world-readable and the warning is gone. The helper's API is unchanged; #2692 reuses it for router auth fixtures.

Validated with cargo check (cuda,test-utils, --tests), clippy -D warnings, fmt, the connection_pool, tcp_transport, and router_front lib modules, and test_secret_file_auth_matches_server_resolution.

Refs #2695
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review (head af4723d)

No CRITICAL, HIGH, or MEDIUM findings. One requested LOW fix pushed in 86e0a89.

  • ProtectedStream::peer_closed: no unsafe; SockRef borrows tokio's fd without owning or closing it. The socket is non-blocking, so the one-byte MSG_PEEK returns WouldBlock instead of waiting, consumes nothing, and leaves the codec and its sequence numbers alone. A stream whose sealer advanced but whose write failed or was cancelled is dropped on the ? path and never returns to the pool, so the pool cannot hold a connection with out-of-step AEAD state. A half-closed peer (SHUT_WR) peeks as 0 bytes and is discarded. Cost is one non-blocking recv per acquire, under the pool mutex, next to the write and AEAD seal that follow; acceptable.
  • ConnectionPool::acquire: the reuse loop pops one idle stream per iteration (at most max_connections_per_peer), dropped idle streams were never counted in active, and the fall-through reuses the existing bounded connect_with_retry. No spin and no new accounting leak.
  • Router prompt_tokens_details and decode-side merge_config_stop_tokens: no panic paths. The usage object only reveals whether the prompt cache is enabled, as single node already does. The merge is linear in the wire stop list times the config EOS list (a few ids).
  • Fixed (LOW): TestClusterSecretFile now creates the secret file with create_new and mode 0600 on unix, so spawned roles stop logging the chmod 600 warning. API unchanged.

Not fixed, pre-existing, out of scope:

  • tcp_transport writes an RPC response on the accepted connection, and nothing reads pooled outbound streams. Unread response bytes make peer_closed report "alive" even after a FIN, so detection only covers drained connections (the disaggregated handoff path).
  • active leaks when send errors after acquire because the stream is dropped without release. It only feeds stats().

Validation: cargo check --profile test-fast --features cuda,test-utils -p mlxcel --tests, clippy -D warnings, cargo fmt --check, lib modules distributed::connection_pool (7), distributed::tcp_transport (25), server::router_front (32), and test_secret_file_auth_matches_server_resolution all pass.

@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 03:45
@inureyes
inureyes merged commit 768baf5 into main Oct 28, 2026
1 check passed
@inureyes
inureyes deleted the fix/issue-2695-disaggregated-e2e branch October 28, 2026 03:45
inureyes added a commit that referenced this pull request Oct 28, 2026
… (#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.
inureyes added a commit that referenced this pull request Oct 28, 2026
…2719)

## Summary

- **Non-stream chat content parity.** The single-node no-tools shaping (`clean_structural_tokens`, answer wrapper, unclosed primed thinking, `--reasoning-format` placement, reasoning extraction) is now `routes::chat::shape_plain_chat_reply`. Single node calls it, and the router's non-stream branch accumulates the raw handoff text and shapes it with the same helper, so `" Café"` becomes `"Café"` on both. `--skip-chat-parsing` still returns raw text, and streaming is unchanged (neither side trims a stream).
- **Llama3 EOS ids.** `llama3::ModelArgs` reads `eos_token_id` (int or list). `eos_token_ids()` returns the declared ids, deduplicated, and appends 128001/128009 only for vocab 128256. It never invents ids. `Llama3Model` stores the result and gains `set_eos_token_ids`. MiniCPM-2B now reports `[2]`. The #2695 regression asserts `[2]`, then sets `[128001, 128009]` so the decode-intake premise still holds.
- **`prompt_tokens_details` follows the worker.** `ResultFrame.prompt_cache_enabled: Option<bool>` (`serde(default)`) is set on the prefill node's successful first-token frame from `BatchScheduler::has_prompt_cache_store()`. Error and decode frames carry `None`. `HandoffOutcome` carries it, and all four usage builders use `prompt_cache_enabled.unwrap_or(router flag)`. Docs: `docs/CONTINUOUS_BATCHING.md` (no Korean counterpart exists).

## Failing-first evidence (main 752db4f, new tests written before the fix)

- `disaggregated_router_chat_usage_matches_single_node_byte_fallback`: `router non-stream content diverges from single-node`, `left: String(" Café")`, `right: String("Café")`.
- `router_front_tests::router_non_stream_chat_content_is_shaped_like_single_node` (a fake prefill peer sends `[" Café"]`): `left: String(" Café")`, `right: String("Café")`.
- `prompt_tokens_details_omitted_when_the_worker_cache_is_off`: chat usage still had `{"cached_tokens":0}` (`left: Some(..)`, `right: None`). `prompt_tokens_details_present_when_the_worker_cache_is_on`: `left: None`.
- MiniCPM handoff parity with the new assertion: `left: [128001, 128009]`, `right: [2]`.
- Pass on main by design: the `None` fallback test (it pins the unchanged behavior for older nodes) and the qwen3 non-stream thinking comparison (both sides return `content: ""` and the same reasoning at 32 tokens). The `llama3_tests` EOS cases, `shape_router_chat_reply_matches_the_single_node_shaping`, and the `serving_protocol` missing-key case test new API, so they cannot compile on main.

## Test plan

All with `MLXCEL_REQUIRE_MODELS=1 MLXCEL_SDPA_DETERMINISTIC=1` under `gpu-lock run --tag issue-2715`, `--profile test-fast`, built outside the lock first.

- [x] `cargo fmt --check`. `cargo clippy --profile test-fast --features cuda -p mlxcel --lib --tests -- -D warnings` is clean.
- [x] Lib tests (`--features cuda`, `--test-threads=1`): `server::router_front` 40/40, `server::routes::chat` 73/73, `models::llama3` 34/34, `models::headless_llama` 3/3, `distributed::disaggregated::serving_protocol` 19/19, `serving_handoff_parity --include-ignored` 6/6. Also `models::llama_bidirec` 9/9, `models::helium` 28/28, and `distributed::tensor_parallel::llama_runtime` 35 passed, 4 ignored.
- [x] `--features cuda,test-utils --test disaggregated_router_e2e -- --include-ignored --test-threads=1`: 7/7 (49 s), no skips. `--test disaggregated_serving_e2e`: 2/2.
- [x] Real model: a single-node `mlxcel-server` on 127.0.0.1:19701 with `minicpm-2b-sft-4bit-llama-format-mlx`, `max_tokens` 16. "café" returns `"Café"` with `finish_reason: stop` and `completion_tokens: 1`. "Чай" returns `"Чай"` with `stop` and 4 tokens. Both stop at `</s>`.

Out of scope, noted for follow-up: single node's non-stream reply also carries `reasoning_only: true` when the reply is all reasoning. The router does not emit that extension field.

Closes #2715


## Behavior changes

- Router non-stream chat replies under `--reasoning-format none` and `deepseek-legacy` now follow single node's non-stream form instead of mirroring the router's streamed form (#2464), so router stream and non-stream agree only as far as single node's do.
- `Llama3Model` reports the EOS ids its config declares: a Llama 3.1 Instruct checkpoint now also reports 128008 (`<|eom_id|>`); a Llama 3 derivative with a resized vocabulary no longer gets 128001/128009 appended; a llama-format checkpoint with no `eos_token_id` and a non-Llama-3 vocabulary reports none. In-tree generation already merges sidecar EOS ids, so only the llava wrapper and the tensor-parallel runtime see the difference.
- With `prompt_cache_enabled` on `ResultFrame`, the prefill node's setting decides `prompt_tokens_details`; a router talking to an older node falls back to its own flag.
@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:router Continuum router routing, config, and integration priority:high High priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(distributed): disaggregated serving and router e2e tests fail on main

1 participant