Skip to content

feat(server): add /v1/completions to the disaggregated router - #386

Merged
inureyes merged 3 commits into
mainfrom
feature/issue-200-router-completions
Jun 21, 2026
Merged

inureyes merged 3 commits into
mainfrom
feature/issue-200-router-completions

Conversation

@inureyes

Copy link
Copy Markdown
Member

Summary

Add POST /v1/completions to the disaggregated router (src/server/router_front.rs), which previously served only POST /v1/chat/completions and GET /health. The new path reuses the single-node completion serializers so its output is byte-identical to single-node /v1/completions for the same prompt and sampling. Follow-up from epic #116 / #126.

What changed

  • Factor the shared dispatch body (tokenize -> select_prefill -> send PrefillRequestFrame) out of route_chat into start_handoff(state, prompt, request_id, response_id, opts) -> Result<(prompt_tokens, rx)>. Both the chat and the completion handlers call it. The chat id scheme (chatcmpl-<n>), routing, and tokenization are unchanged, so the existing chat endpoint stays byte-identical to before this PR. start_handoff applies the same add_special rule the worker uses (!prompt.starts_with("<bos>") && !prompt.starts_with("<s>")) and removes the registered pending channel on any pre-send failure.
  • Add router_completions / route_completion. They reuse the EXISTING single-node serializers (no hand-rolled completion shape): non-streaming returns CompletionResponse::new_with_logprobs (object text_completion, choices[index, text, finish_reason, logprobs], usage); streaming emits CompletionChunk::content per token, then CompletionChunk::finish, an optional CompletionChunk::usage chunk when stream_options.include_usage is set, then the [DONE] sentinel, matching routes::completions chunk-for-chunk.
  • finish_reason mirrors the worker exactly: completion_tokens >= max_tokens -> "length" else "stop" (same logic as src/server/model_worker.rs). prompt_tokens for the usage block comes from the router's own tokenization (equal to the worker's count under the shared add_special rule).
  • Per-token logprobs are rejected with a 400 invalid_request_error because the disaggregated ResultFrames carry detokenized text only and cannot reproduce them; n and echo are not in CompletionRequest, so they are silently ignored exactly as the single-node path does.
  • Register POST /v1/completions in create_router_app and update the module / factory docs.
  • Add an integration test disaggregated_router_completions_match_single_node in tests/disaggregated_router_e2e.rs covering both the non-streaming JSON body and the streaming SSE chunk sequence.

Parity notes

  • Byte-identity is structural, not reimplemented: both endpoints serialize the same CompletionResponse / CompletionChunk types, and serde_json is built with preserve_order, so field order matches. The only inherently volatile fields are id (cmpl-<uuid>, same format as single-node) and created (timestamp); the test normalizes just these two before comparing.
  • Pre-existing router limitation (unchanged by this PR, shared with the chat path): the PrefillRequestFrame does not carry stop sequences, so stop is not honored on the disaggregated path. The byte-identity claim holds for requests without stop sequences.

Test plan

  • cargo check -p mlxcel --lib --tests
  • cargo clippy -p mlxcel --lib --tests -- -D warnings
  • cargo fmt --check -p mlxcel
  • cargo test --test disaggregated_router_e2e --release --features metal,accelerate disaggregated_router_completions_match_single_node -- --ignored --nocapture (heavy; spawns four real mlxcel-server processes loading qwen3-0.6b-4bit, run by the orchestrator)

Closes #200

The disaggregated router (`src/server/router_front.rs`) only served `POST /v1/chat/completions` and `GET /health`; the text-completion endpoint `POST /v1/completions` (served single-node by `routes::completions`) was unreachable through the router. This adds it (issue #200, follow-up from epic #116 / #126).

Factor the shared tokenize -> select_prefill -> send `PrefillRequestFrame` body out of `route_chat` into a new `start_handoff(state, prompt, request_id, response_id, opts) -> Result<(prompt_tokens, rx)>`. Both the chat and the new completion handlers call it; the chat id scheme (`chatcmpl-<n>`) and routing are preserved unchanged, so the existing chat endpoint stays byte-identical to before. `start_handoff` applies the same `add_special` rule the worker uses (`!prompt.starts_with("<bos>") && !prompt.starts_with("<s>")`) and removes the registered `pending` channel on any pre-send failure.

The new `router_completions` / `route_completion` handlers reuse the EXISTING single-node serializers so the output is structurally byte-identical to single-node `/v1/completions` for the same prompt and sampling: non-streaming builds `CompletionResponse::new_with_logprobs` (object `text_completion`, choices[index, text, finish_reason, logprobs], usage), and streaming emits `CompletionChunk::content` per token, then `CompletionChunk::finish`, an optional `CompletionChunk::usage` chunk when `stream_options.include_usage` is set, and the `[DONE]` sentinel. `finish_reason` mirrors the worker exactly (`completion_tokens >= max_tokens` -> "length" else "stop", per `model_worker.rs`), and `prompt_tokens` comes from the router's own tokenization. Per-token logprobs are rejected with a 400 because the disaggregated result frames carry detokenized text only and cannot reproduce them; `n` and `echo` are silently ignored exactly as the single-node path does. Register `POST /v1/completions` in `create_router_app`.

Add `disaggregated_router_completions_match_single_node` to `tests/disaggregated_router_e2e.rs`: it captures single-node `/v1/completions` output (the baseline is started with `--alias` so its model id matches the router's echoed `model`), then drives the three-process router stack and asserts the non-streaming JSON body and the streaming SSE chunk sequence are byte-identical after normalizing only the volatile `id` / `created` fields. Run with `cargo test --test disaggregated_router_e2e --release --features metal,accelerate disaggregated_router_completions_match_single_node -- --ignored --nocapture`.
@inureyes inureyes added type:enhancement New features, capabilities, or significant additions priority:low Low priority area:architecture Architecture and code structure changes status:review Under review labels Jun 21, 2026
inureyes added 2 commits June 22, 2026 02:08
…age chunk on success

Reject response_format (structured output) and explicit reasoning/thinking budgets on the disaggregated /v1/completions, returning a 400 like the existing logprobs guard. The PrefillRequestFrame carries only sampling and max_tokens, so the worker-side controls these options drive (a structured-output constraint, reasoning-budget enforcement) cannot be reproduced on the router path. Returning 200 with unconstrained or un-budgeted output would silently diverge from single-node and break the byte-identity criterion, so the router rejects the request instead. Requests with no budget alias set are unaffected and the default unbounded path keeps working.

Gate the streaming usage chunk on success: only send the CompletionChunk::usage chunk when include_usage is true and the handoff result is Ok, matching single-node stream_completion which guards on `if include_usage && let Ok(ref r) = result`. The finish chunk and the [DONE] sentinel are left exactly as they were.

Document the byte-fallback completion_tokens limitation: completion_tokens is counted from emitted detokenized text pieces (one on_token call per ResultFrame text entry), which equals the worker's generated-token count for byte-level-BPE tokenizers (e.g. Qwen) but may under-count for byte-fallback tokenizers (e.g. Gemma <0xXX> byte sequences), and can consequently flip finish_reason between length and stop. A precise fix requires the disaggregated wire protocol to carry the worker's token count and is deferred to a follow-up.
Add POST /v1/completions to the router's scope in CONTINUOUS_BATCHING.md,
alongside the pre-existing POST /v1/chat/completions entry. Document the
two wire-protocol limitations specific to the text-completion path: stop
sequences are not forwarded (pre-existing, shared with the chat path), and
completion_tokens is counted from detokenized text frames, which can
under-count for byte-fallback tokenizers (Gemma). Also document the three
unsupported option groups that return HTTP 400 (logprobs, response_format,
reasoning/thinking budgets) and correct the outdated note about the stream
filter, which now actively suppresses structural markers and routes
reasoning_content.
@inureyes

Copy link
Copy Markdown
Member Author

Finalization complete

Documentation (docs/CONTINUOUS_BATCHING.md): updated the "Scope and limitations" section in the disaggregated serving doc to reflect the new POST /v1/completions support on the router. Changes:

  • Added POST /v1/completions next to POST /v1/chat/completions in the supported-endpoints sentence.
  • Documented the three unsupported option groups that return HTTP 400: logprobs, response_format, and explicit reasoning/thinking budgets.
  • Documented the two wire-protocol limitations callers should know: stop sequences are not forwarded (pre-existing, shared with the chat path), and completion_tokens can under-count for byte-fallback tokenizers (a follow-up issue tracks the protocol extension).
  • Corrected the outdated bullet that said the stream filter was not yet applied; it has been active since PR Disaggregated router: apply the chat stream filter to output #198.

Tests: no new unit tests added. The 400-guard conditions reduce to Option::is_some() checks and pick_budget_alias() (which has its own tests); extracting them into separate unit tests adds no coverage beyond what already exists. The byte-identity E2E test (disaggregated_router_completions_match_single_node) is the substantive coverage and has been confirmed passing.

Lint/format: cargo fmt --check passes clean; cargo clippy -p mlxcel --lib --tests -- -D warnings exits with no diagnostics.

Commit: f9b0a459c on feature/issue-200-router-completions.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Jun 21, 2026
@inureyes
inureyes merged commit f54fd96 into main Jun 21, 2026
4 checks passed
@inureyes
inureyes deleted the feature/issue-200-router-completions branch June 21, 2026 17:21
@inureyes inureyes self-assigned this Aug 31, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…#386)

* feat(server): add /v1/completions to the disaggregated router

The disaggregated router (`src/server/router_front.rs`) only served `POST /v1/chat/completions` and `GET /health`; the text-completion endpoint `POST /v1/completions` (served single-node by `routes::completions`) was unreachable through the router. This adds it (issue lablup#200, follow-up from epic lablup#116 / lablup#126).

Factor the shared tokenize -> select_prefill -> send `PrefillRequestFrame` body out of `route_chat` into a new `start_handoff(state, prompt, request_id, response_id, opts) -> Result<(prompt_tokens, rx)>`. Both the chat and the new completion handlers call it; the chat id scheme (`chatcmpl-<n>`) and routing are preserved unchanged, so the existing chat endpoint stays byte-identical to before. `start_handoff` applies the same `add_special` rule the worker uses (`!prompt.starts_with("<bos>") && !prompt.starts_with("<s>")`) and removes the registered `pending` channel on any pre-send failure.

The new `router_completions` / `route_completion` handlers reuse the EXISTING single-node serializers so the output is structurally byte-identical to single-node `/v1/completions` for the same prompt and sampling: non-streaming builds `CompletionResponse::new_with_logprobs` (object `text_completion`, choices[index, text, finish_reason, logprobs], usage), and streaming emits `CompletionChunk::content` per token, then `CompletionChunk::finish`, an optional `CompletionChunk::usage` chunk when `stream_options.include_usage` is set, and the `[DONE]` sentinel. `finish_reason` mirrors the worker exactly (`completion_tokens >= max_tokens` -> "length" else "stop", per `model_worker.rs`), and `prompt_tokens` comes from the router's own tokenization. Per-token logprobs are rejected with a 400 because the disaggregated result frames carry detokenized text only and cannot reproduce them; `n` and `echo` are silently ignored exactly as the single-node path does. Register `POST /v1/completions` in `create_router_app`.

Add `disaggregated_router_completions_match_single_node` to `tests/disaggregated_router_e2e.rs`: it captures single-node `/v1/completions` output (the baseline is started with `--alias` so its model id matches the router's echoed `model`), then drives the three-process router stack and asserts the non-streaming JSON body and the streaming SSE chunk sequence are byte-identical after normalizing only the volatile `id` / `created` fields. Run with `cargo test --test disaggregated_router_e2e --release --features metal,accelerate disaggregated_router_completions_match_single_node -- --ignored --nocapture`.

* fix(server): reject unsupported completion options and gate router usage chunk on success

Reject response_format (structured output) and explicit reasoning/thinking budgets on the disaggregated /v1/completions, returning a 400 like the existing logprobs guard. The PrefillRequestFrame carries only sampling and max_tokens, so the worker-side controls these options drive (a structured-output constraint, reasoning-budget enforcement) cannot be reproduced on the router path. Returning 200 with unconstrained or un-budgeted output would silently diverge from single-node and break the byte-identity criterion, so the router rejects the request instead. Requests with no budget alias set are unaffected and the default unbounded path keeps working.

Gate the streaming usage chunk on success: only send the CompletionChunk::usage chunk when include_usage is true and the handoff result is Ok, matching single-node stream_completion which guards on `if include_usage && let Ok(ref r) = result`. The finish chunk and the [DONE] sentinel are left exactly as they were.

Document the byte-fallback completion_tokens limitation: completion_tokens is counted from emitted detokenized text pieces (one on_token call per ResultFrame text entry), which equals the worker's generated-token count for byte-level-BPE tokenizers (e.g. Qwen) but may under-count for byte-fallback tokenizers (e.g. Gemma <0xXX> byte sequences), and can consequently flip finish_reason between length and stop. A precise fix requires the disaggregated wire protocol to carry the worker's token count and is deferred to a follow-up.

* docs(server): document /v1/completions on the disaggregated router

Add POST /v1/completions to the router's scope in CONTINUOUS_BATCHING.md,
alongside the pre-existing POST /v1/chat/completions entry. Document the
two wire-protocol limitations specific to the text-completion path: stop
sequences are not forwarded (pre-existing, shared with the chat path), and
completion_tokens is counted from detokenized text frames, which can
under-count for byte-fallback tokenizers (Gemma). Also document the three
unsupported option groups that return HTTP 400 (logprobs, response_format,
reasoning/thinking budgets) and correct the outdated note about the stream
filter, which now actively suppresses structural markers and routes
reasoning_content.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:architecture Architecture and code structure changes priority:low Low 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.

Disaggregated router: add the /v1/completions endpoint

1 participant