Repository navigation
fix(server): align count routes and message_start with usage - #2415
Merged
Merged
Conversation
Three places where a token count disagreed with what `/v1/messages` and its siblings serve: - Streaming `/v1/messages` filled `message_start.usage.input_tokens` by encoding the rendered placeholder text with `add_special` forced on. A text-only body now uses the local rule `count_prompt_tokens` uses (factored into `count_text_prompt_tokens`), so the event still goes out at once. A body with media holds `message_start` (behind `AnthropicMessageStart`, which sends exactly once) until the worker's first prefill report and uses its `prompt_tokens`, the expanded length that `usage` and `count_tokens` report. On the batch scheduler every prefilling request reports `PrefillStats` before its first token; a backend that does not gets the event before its first token, error, or completion with the best figure on hand. - `render_admitted_chat_prompt`, shared by the three count routes and `/apply-template`, now renders through `reasoning_echo::chat_scope` and `render_request` like the generating routes, so a content-only assistant turn counts the reasoning the generation re-injects. Count routes never call `record_reply`. - `/v1/messages/count_tokens`, `/v1/chat/completions/input_tokens` and `/v1/responses/input_tokens` (and their unprefixed aliases) now refuse first with their generating sibling's 501 envelope under `--embeddings`/`--reranking` or with no chat model loaded. The media-expanding route-test provider now reports a prefill snapshot and one token for a generation, as the scheduler does, and the prompt-count route tests use a byte-per-token stub tokenizer so a text-only count can be held to `usage`. Closes #2337
Review follow-up for #2337. The two dedicated image loops sent their single answer token without a `GenerateEvent::Prefill`, so a streamed Anthropic image request on them fell back to the placeholder count on `message_start`. Both now send the batch scheduler's first-token snapshot, with the run's prompt length, right before the token. Also adds a route test for a backend that streams a token with no prefill report (`message_start` still opens the stream, once), notes in the docs that a held `message_start` leaves only keepalive comments on the wire and that `/apply-template` shows re-injected reasoning, and says in the render comment that an echo hit refreshes the entry's recency. Refs #2337
inureyes
force-pushed
the
fix/2337-anthropic-count-alignment
branch
from
October 16, 2026 01:13
7714d4b to
043063e
Compare
This was referenced Oct 16, 2026
inureyes
added a commit
that referenced
this pull request
Oct 17, 2026
…loop (#2436) Closes #2420 The `xla-iree` serve loop never sent `GenerateEvent::Prefill` and reported the logical (placeholder) prompt length, so a media body's `usage`, `/v1/messages/count_tokens` and the streaming `message_start` that #2415 holds for the prefill report all carried the placeholder count. This makes the loop match the batch scheduler and `docs/llama-server-compat.md`. ## Changes - `ServeState` keeps one count, `effective_prefill_len` (the expanded prepared length for media, the prompt length for text), and a `prefill_reported` flag. `ServeState::report_prefill` sends `PrefillStats { prompt_tokens, cached_tokens: 0, processed, first_token: true, prompt_ms }` once, before the first `Token` or before `Done` when the engine finishes with no token (withheld EOS), and stamps the decode state's first-token instant as `sequence.rs` does. - `Done`, the stop-string finish and the zero-budget media finish report the expanded length. The count route follows, since the XLA worker answers it with a one-token generation. - Every XLA image family goes through `handle_preprocessed`, including the new Molmo (#918) and Youtu-VL (#919) producers, so they are covered too. So are the DeepStack (Qwen3-VL) and Phi4MM audio/image paths. The disaggregated coordinator stays out of scope, as the issue says. - No doc change: `docs/llama-server-compat.md` has no XLA-specific statement, and its general promise now holds on this loop. ## Tests The new and updated tests drive the real `admit`, preprocessing and `dispatch` path with a fake engine: text gets `Prefill(2)`, the image gets `Prefill(5)`, and Phi4MM audio and image each get `Prefill(6)`, every one sent before its `Token`, with `Done` reporting the same length. They also cover zero-budget image and audio, and a bare EOS finish. The fake Phi4MM producer now expands placeholders. Two existing assertions in this module were already failing on main because the error messages had changed (`structured` is now `constrained decoding`, and `refusing text fallback` is now `image resolution cardinality mismatch`). I updated them so the module runs green. - Fix: `server::batch::xla_worker`, 15 passed (`--release --features cuda,xla-iree`, `--test-threads=1`, under gpu-lock). - Revert check: with the production files restored to main, 9 failed. That is the 7 new or updated tests plus the 2 stale assertions. - `cargo clippy --release --features cuda,xla-iree --lib --tests -- -D warnings`, `cargo check --release --features cuda,xla-iree --all-targets`, `cargo fmt --check` and the repository check scripts pass. ## Real checkpoint `~/models/mlx/gemma-3-4b-it-4bit`, `MLXCEL_BACKEND=xla MLXCEL_XLA_DEVICE=cuda MLXCEL_XLA_CONTEXT_CAPACITY=512 mlxcel-server` on the GB10 (the default 256 capacity refuses a Gemma 3 image). I sent one body (`tests/fixtures/test_image.png` plus a short prompt) to `count_tokens`, non-streaming and streaming `/v1/messages`: | Body | Build | count_tokens | usage.input_tokens | message_start.input_tokens | |---|---|---|---|---| | image | main cadc636, XLA | 18 | 18 | 18 | | image | this PR, XLA | 277 | 277 | 277 | | image | this PR, MLX path | 277 | 277 | 277 | | text | both builds, XLA | 17 | 17 | 17 | In every stream `message_start` was the first event, and it was sent once. Phi4MM audio was not run on a real checkpoint (none is present locally), so the fake-producer test covers it.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Three places where a token count disagreed with what
/v1/messagesor its siblings serve. All three are fixed here, with one verification pass at the end.1. Streaming
message_start.usage.input_tokensnow includes media expansionstream_messagesused to fillmessage_startfromstate.tokenizer.encode(&prepared.prompt, true): the placeholder text, withadd_specialforced on and nativeprompt_token_idsignored.count_prompt_tokensis factored intoprompt_inspection::count_text_prompt_tokens(native ids win, otherwiseadd_special = !prompt_carries_bos). A text-only body uses it andmessage_startstill goes out immediately. This also removes the one-token over-count on templates that emit their own BOS (gemma-3 reported 16 against 15 before).PreparedChatRequest::carries_media()) holdsmessage_startuntil the worker's firstPrefillStatsand uses itsprompt_tokens.streaming_anthropic::AnthropicMessageStartholds the event and sends it exactly once; every path that could emit another event callssendfirst with the best figure it has (prefill report, else the local count before a token or an error, else the result's ownprompt_tokenson completion).Ordering guarantee this relies on, checked on the current tree: on the batch scheduler, which serves every regular model including the MLX vision families, the prefill completion step stamps the first token through
step_rows::SequenceStepHooks::resolved->stamp_first_tokenand sendsGenerateEvent::Prefillbefore the token reachesstream_decoded_text. The speculative burst callsmark_first_token_at(prefill_end)beforestream_burst_tokens, and a chunked prefill also sendsreport_prefill_progressevents earlier. All of them carrySequenceInfo::prompt_tokens.len(), the same post-expansion length thattake_generation_resultreports asusageand that the count-only request inadmission.rsanswers. The Florence-2 and Nemotron-Parse image loops did not sendPrefill; they now send the same first-token snapshot (with the run's prompt length) right before their single answer token. Two paths still never send it: thexla-ireeserve loop (src/server/batch/xla_worker.rs, which serves qualified LLaVA and Phi4MM media requests) and the disaggregated coordinator, which drops the event. There the token-first fallback applies andmessage_startcarries the local count, as before this PR. I left them alone because the XLA loop is not compiled by the local gate and the coordinator change belongs with that subsystem; they are listed under Not covered. I did not take the alternative of callingcount_prompt_tokensbefore dispatch, because that would take a second worker slot and repeat the media preparation for every streamed media request. No media is fetched twice either way.During a long media queue wait and prefill the client now receives only SSE keepalive comments (not events) before
message_start, so no event precedes it. With--sse-ping-interval -1nothing is sent until prefill; the docs say so.2. Count routes render with the #2110 reasoning re-echo
render_admitted_chat_prompt(shared by/v1/chat/completions/input_tokens,/v1/responses/input_tokens,/v1/messages/count_tokensand/apply-template) now runsreasoning_echo::chat_scopeandrender_requestafter the video substitution, in the same order aschat_generation.rs,responses.rsandanthropic.rs. Count routes only fill and never callrecord_reply(a hit refreshes the entry's LRU recency, as a generation's would)./apply-templateshares the render, so its prompt now shows the re-injected reasoning too, which is what the generating route would prefill.3. Count routes refuse when the server cannot generate
chat_input_tokensandresponses_input_tokensnow runchat_not_availablefirst, andanthropic_count_tokensruns the newanthropic::chat_unavailable_response(shared withanthropic_messages) first, so each returns its sibling's 501 status and body under--embeddings/--rerankingor with no chat model loaded.docs/llama-server-compat.mddescribes all three.Tests
New tests, each confirmed to fail with its fix reverted (source reverted, tests kept, then restored):
prompt_count_route_tests::anthropic_streaming_image_input_tokens_equal_count_and_usage: image body throughimage_app();message_startmust be the first event, sent once, and equalcount_tokensand non-streamingusage. Reverted:message_start equals usage, left 33, right 1033.prompt_count_route_tests::anthropic_streaming_text_input_tokens_equal_count_and_usage: the text-only agreement check. It passes on the reverted code too, because the stub tokenizer adds no BOS; it guards the text path rather than reproducing the bug.prompt_count_route_tests::{chat,responses,anthropic}_count_includes_the_reasoning_echo: prime the store via the generating route with a scripted reasoning reply, then hold the count of the content-only follow-up to the length of the prompt the follow-up generation is actually handed. Reverted: left 52, right 78 on all three.availability_tests::count_routes_refuse_like_their_generating_siblings: all six count paths against their siblings, with no chat model and under--embeddings. Reverted:/v1/chat/completions/input_tokensanswered 200{"input_tokens":0}.prompt_count_route_tests::anthropic_streaming_media_without_a_prefill_report_still_opens_with_message_start: a scripted backend that streams a token with no prefill report;message_startstill opens the stream, exactly once.streaming_anthropic::tests::message_start_goes_out_once_with_the_first_figure.Test support: the media-expanding route-test provider now sends a
Prefillsnapshot and one token beforeDonefor a generation (not for a count-only request), matching the scheduler, andprompt_count_route_testsusesMlxcelTokenizer::stub_all_byte_fallback()(one token per byte, the fake provider's own rule), so a text-only count can be held tousage.Local gate on this GB10 box (
--features cuda,--profile test-fast,--test-threads=1):server::routes::prompt_inspection28 passed (1 ignored, needs ffmpeg),server::routes::availability_tests6,server::routes::anthropic21,server::streaming_anthropic4,server::reasoning_echo30,server::florence2_worker15,server::nemotron_parse_worker7. The fullserver::routesfilter was not run locally (too large for this shared box); CI covers it.cargo clippy --profile test-fast --features cuda --lib --tests -- -D warningsclean,cargo fmt --all -- --checkcleancheck_llama_compat_manifest.py,check_kernel_dtype_keys.py,check_kernel_port_dispatch.py,check_crate_versions.py,insert_apache_header.py --checkall passReal checkpoint
~/models/mlx/gemma-3-4b-it-4bit,mlxcel-server -m ~/models/mlx/gemma-3-4b-it-4bit(test-fast, CUDA). Each body was sent to/v1/messages/count_tokens, non-streaming/v1/messages, and/v1/messageswith"stream": true. The image body istests/fixtures/test_image.pngas a base64imageblock plus a text block.In both builds
message_startwas the first event of the stream. Items 2 and 3 are covered by the route tests above; the gemma-3 checkpoint has no reasoning channel to re-echo.Not covered
message_starton thexla-ireeserve loop and on the disaggregated coordinator still carries the placeholder count for a media body, because neither forwards a prefill report (see item 1).Changes during review
Report-only implementation and security reviews found no CRITICAL or HIGH issues. Follow-up commit: Florence-2 and Nemotron-Parse now send a prefill report, a route test covers the no-prefill fallback, and the docs note the keepalive-only wait and
/apply-templateshowing re-injected reasoning.Closes #2337