Skip to content

fix(server): align count routes and message_start with usage - #2415

Merged
inureyes merged 3 commits into
mainfrom
fix/2337-anthropic-count-alignment
Oct 16, 2026
Merged

inureyes merged 3 commits into
mainfrom
fix/2337-anthropic-count-alignment

Conversation

@inureyes

@inureyes inureyes commented Oct 16, 2026 •

Copy link
Copy Markdown
Member

Summary

Three places where a token count disagreed with what /v1/messages or its siblings serve. All three are fixed here, with one verification pass at the end.

1. Streaming message_start.usage.input_tokens now includes media expansion

stream_messages used to fill message_start from state.tokenizer.encode(&prepared.prompt, true): the placeholder text, with add_special forced on and native prompt_token_ids ignored.

  • The text-only rule from count_prompt_tokens is factored into prompt_inspection::count_text_prompt_tokens (native ids win, otherwise add_special = !prompt_carries_bos). A text-only body uses it and message_start still 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).
  • A body with media (PreparedChatRequest::carries_media()) holds message_start until the worker's first PrefillStats and uses its prompt_tokens. streaming_anthropic::AnthropicMessageStart holds the event and sends it exactly once; every path that could emit another event calls send first with the best figure it has (prefill report, else the local count before a token or an error, else the result's own prompt_tokens on 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_token and sends GenerateEvent::Prefill before the token reaches stream_decoded_text. The speculative burst calls mark_first_token_at(prefill_end) before stream_burst_tokens, and a chunked prefill also sends report_prefill_progress events earlier. All of them carry SequenceInfo::prompt_tokens.len(), the same post-expansion length that take_generation_result reports as usage and that the count-only request in admission.rs answers. The Florence-2 and Nemotron-Parse image loops did not send Prefill; 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: the xla-iree serve 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 and message_start carries 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 calling count_prompt_tokens before 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 -1 nothing 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_tokens and /apply-template) now runs reasoning_echo::chat_scope and render_request after the video substitution, in the same order as chat_generation.rs, responses.rs and anthropic.rs. Count routes only fill and never call record_reply (a hit refreshes the entry's LRU recency, as a generation's would). /apply-template shares 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_tokens and responses_input_tokens now run chat_not_available first, and anthropic_count_tokens runs the new anthropic::chat_unavailable_response (shared with anthropic_messages) first, so each returns its sibling's 501 status and body under --embeddings / --reranking or with no chat model loaded.

docs/llama-server-compat.md describes 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 through image_app(); message_start must be the first event, sent once, and equal count_tokens and non-streaming usage. 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_tokens answered 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_start still 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 Prefill snapshot and one token before Done for a generation (not for a count-only request), matching the scheduler, and prompt_count_route_tests uses MlxcelTokenizer::stub_all_byte_fallback() (one token per byte, the fake provider's own rule), so a text-only count can be held to usage.

Local gate on this GB10 box (--features cuda, --profile test-fast, --test-threads=1):

  • server::routes::prompt_inspection 28 passed (1 ignored, needs ffmpeg), server::routes::availability_tests 6, server::routes::anthropic 21, server::streaming_anthropic 4, server::reasoning_echo 30, server::florence2_worker 15, server::nemotron_parse_worker 7. The full server::routes filter was not run locally (too large for this shared box); CI covers it.
  • cargo clippy --profile test-fast --features cuda --lib --tests -- -D warnings clean, cargo fmt --all -- --check clean
  • check_llama_compat_manifest.py, check_kernel_dtype_keys.py, check_kernel_port_dispatch.py, check_crate_versions.py, insert_apache_header.py --check all pass

Real 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/messages with "stream": true. The image body is tests/fixtures/test_image.png as a base64 image block plus a text block.

Body Build count_tokens usage.input_tokens message_start.usage.input_tokens
image main 93e5ef7 275 275 17
image this PR 275 275 275
text only main 93e5ef7 15 15 16
text only this PR 15 15 15

In both builds message_start was 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_start on the xla-iree serve loop and on the disaggregated coordinator still carries the placeholder count for a media body, because neither forwards a prefill report (see item 1).
  • The text-only BOS over-count fix (16 to 15 on gemma-3) is shown on the real checkpoint only; the route-test stub tokenizer adds no BOS, so the text-only route test does not reproduce it.

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-template showing re-injected reasoning.

Closes #2337

@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:low Low priority area:inference Generation, sampling, decoding (incl. speculative, DRY) status:done Completed and removed status:review Under review labels Oct 16, 2026
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
inureyes force-pushed the fix/2337-anthropic-count-alignment branch from 7714d4b to 043063e Compare October 16, 2026 01:13
@inureyes
inureyes merged commit 9c17d84 into main Oct 16, 2026
27 checks passed
@inureyes
inureyes deleted the fix/2337-anthropic-count-alignment branch October 16, 2026 02:38
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.
@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) priority:low Low 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: align Anthropic token counts and count_tokens gating with /v1/messages

1 participant