Skip to content

fix: accept system-role turns inside /v1/messages array - #380

Merged
inureyes merged 3 commits into
mainfrom
fix/issue-349-messages-system-role
Jun 21, 2026
Merged

inureyes merged 3 commits into
mainfrom
fix/issue-349-messages-system-role

Conversation

@inureyes

Copy link
Copy Markdown
Member

Summary

/v1/messages rejected every request from Claude Code 2.1.156 and later with HTTP 422 before any generation. Starting with that build, the client interleaves {"role":"system", ...} turns inside the messages array for mid-conversation reminders, and AnthropicRole only modeled user/assistant, so axum's Json extractor failed to deserialize the body. This restores the endpoint for current client builds and guarantees the interleaved system text actually reaches the model.

What changed

  • src/server/types/anthropic_request.rs: add a System variant to AnthropicRole (and to as_str, returning "system") so the request deserializes instead of 422-ing. Updated the role doc comments to explain the non-spec interleaving.
  • src/server/anthropic_translator.rs: map AnthropicRole::System to the internal Role::System in append_message, then add a fold_system_messages pass that relocates any non-head system turn so its text renders under any chat template.

Why folding is required (not just the enum variant)

Adding the variant alone stops the 422 but does not guarantee the system text influences generation. Many production chat templates (Qwen-family, Llama 3) special-case messages[0] for the system block and their {% for message in messages %} loop only handles user/assistant/tool. A bare system turn at messages[1] is silently dropped by such a template, so the reminder would never reach the model. The fold pass moves the text into a turn every template renders.

Merge strategy

  • Leading system turns (before the first user/assistant/tool turn) merge into the single head system block, together with the top-level system field when present, so neither is dropped.
  • A mid-conversation system turn is prepended to the following user turn. Claude Code emits the reminder immediately before a user turn, so this preserves its positional/contextual meaning; folding into an existing turn means we never depend on a template rendering a non-head system role, and no new user turn is created so user/assistant alternation is unchanged.
  • A trailing system turn with no following user turn is appended to the preceding user turn, or merged into the head block as a last resort.
  • Multimodal user turns keep their image parts; the reminder is added as a leading text part.

Test plan

  • cargo test --lib server::anthropic_translator (29 passed, including 7 new cases: deserialization without 422, fold into following user turn, top-level plus mid-array system both surviving, leading-array merge with top-level system, trailing reminder preserved, multimodal fold preserving the image, and the unchanged top-level-system path)
  • cargo test --lib server::types::anthropic_request (10 passed, including a new deserialization regression test for a system-role turn inside messages)
  • cargo clippy --lib --tests -- -D warnings (clean)
  • cargo fmt --check (clean)

The new translator tests render the folded output through a head-only Qwen-style template (system only at messages[0], per-turn loop handles user/assistant only) and assert the reminder text survives, proving it was folded rather than left as an orphan mid-array system turn that such a template would drop.

Follow-up (manual)

Live end-to-end verification with a real Claude Code 2.1.156+ client against /v1/messages could not be run here and is left as a manual check.

Closes #349

Claude Code >= 2.1.156 interleaves `{"role":"system", ...}` turns inside the `messages` array for mid-conversation reminders. `AnthropicRole` only modeled `user`/`assistant`, so axum's `Json` extractor rejected every such request with HTTP 422 before any generation ran. The OpenAI `/v1/chat/completions` path was unaffected.

Add a `System` variant to `AnthropicRole` (and `as_str`) so the request deserializes, then fold each mid-conversation system turn into an adjacent user turn so its text reaches the model regardless of the chat template. Many production templates (Qwen-family, Llama 3) special-case `messages[0]` for the system block and their per-turn loop only handles user/assistant/tool, so a bare `system` turn at `messages[1]` would be silently dropped and never influence generation.

Strategy: leading system turns merge into the single head system block together with the top-level `system` field (neither is dropped); a mid-conversation reminder is prepended to the following user turn, keeping its positional meaning without emitting a second `system` message or creating a new user turn; a trailing reminder with no following user turn is appended to the preceding user turn or merged into the head block.

Tests: deserialization of a system-role turn inside `messages` (no 422), folding into the following user turn, top-level plus mid-array system both surviving, leading-array merge with top-level system, trailing reminder, and a multimodal fold that preserves the image. A head-only Qwen-style template render proves the folded text is not dropped.
@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:high High priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Jun 21, 2026
The mid-array system fold added the reminder as a separate ContentPart::Text on multimodal user turns. MessageContent::text() joins parts with an empty string, so the reminder ran into the user's words ("watch outsee this" instead of "watch out\n\nsee this"). Merge the reminder into the existing text part with the same blank-line separator the text-only path uses, falling back to a fresh part only for image-only turns. Strengthen the multimodal test to assert the exact separated output and add a consecutive mid-array system turns case.
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Accept Claude Code >= 2.1.156 requests that interleave {"role":"system"} turns inside the /v1/messages array (no more HTTP 422) AND guarantee that interleaved system text actually reaches the model under head-only chat templates, without changing top-level system/tools/tool_use/tool_result behavior.

Findings Addressed

  • Multimodal fold concatenated the reminder and the user's text with no separator (MEDIUM). MessageContent::text() joins parts with an empty string, so a mid-array reminder before a multimodal user turn rendered as watch outsee this instead of watch out\n\nsee this. Fixed in combine_user_text by merging the reminder into the existing text part with the same blank-line separator the text-only path uses (falling back to a fresh part only for image-only turns). Independently flagged by the Codex reviewer (P2).

Remaining Items

  • None blocking. Two informational notes (no change required):
    • The literal [user, system, user] shape folds to [user, user] (two consecutive user turns). This adjacency is inherent to the input (two real user turns separated by a system turn) and is not introduced by the fold; the alternative (a bare mid-array system turn) is strictly worse since head-only templates drop it. Qwen-family templates (the issue's target) tolerate consecutive user turns.
    • A mid-array reminder followed only by an assistant/tool turn (no later user) is relocated to the head system block as a documented last resort. Text is preserved; positioning shifts from mid-conversation to global.

Verification

  • All stated requirements implemented (System variant deserializes; fold pass routes the text into a turn every template renders; head-only Qwen-style render tests prove the reminder reaches the prompt)
  • No placeholder/mock code remaining
  • Integrated into project code flow (anthropic_request_to_chat calls fold_system_messages; append_message maps AnthropicRole::System)
  • Project conventions followed (no unwrap/expect in new paths, inline format args, clippy clean)
  • Existing modules reused where applicable (internal Role::System, MessageContent, image plumbing)
  • No unintended structural changes (fold pass early-returns for the common top-level-system / no-system / tools / tool_use / tool_result paths)
  • No dropped system reminder or lost user/assistant/tool turn; user/assistant ordering preserved (verified by trace over leading / mid / trailing / consecutive / only-system / assistant-follows / tool-interaction cases, corroborated by the Codex reviewer)
  • Tests pass (cargo test --lib server::anthropic_translator: 30 passed; cargo clippy --lib --tests -- -D warnings clean; cargo fmt --check clean)

Edge-case tests added: exact-separator assertion on the multimodal fold and a consecutive-mid-array-system-turns case.

@inureyes

Copy link
Copy Markdown
Member Author

PR Finalization Complete

Tests

30 tests in server::anthropic_translator pass (all pre-existing; no gaps found that warranted new cases given the existing coverage of happy path, consecutive system turns, multimodal fold, leading/trailing edge cases, and head-only template render proof).

Documentation

Added an [Unreleased] section to CHANGELOG.md (commit 3d5c2be) recording the HTTP 422 fix and the fold_system_messages strategy. No dedicated Anthropic /v1/messages endpoint doc page exists in docs/, so no new file was created.

Lint / Format

cargo fmt -- --check: clean. cargo clippy --lib --tests -- -D warnings: clean (17.6s, 0 warnings).

All checks pass. Ready for merge.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Jun 21, 2026
@inureyes
inureyes merged commit 1b4a9d3 into main Jun 21, 2026
4 checks passed
@inureyes
inureyes deleted the fix/issue-349-messages-system-role branch June 21, 2026 11:07
@inureyes inureyes added this to the 0.3 milestone Jun 21, 2026
@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
* fix(server): accept system-role turns inside /v1/messages array

Claude Code >= 2.1.156 interleaves `{"role":"system", ...}` turns inside the `messages` array for mid-conversation reminders. `AnthropicRole` only modeled `user`/`assistant`, so axum's `Json` extractor rejected every such request with HTTP 422 before any generation ran. The OpenAI `/v1/chat/completions` path was unaffected.

Add a `System` variant to `AnthropicRole` (and `as_str`) so the request deserializes, then fold each mid-conversation system turn into an adjacent user turn so its text reaches the model regardless of the chat template. Many production templates (Qwen-family, Llama 3) special-case `messages[0]` for the system block and their per-turn loop only handles user/assistant/tool, so a bare `system` turn at `messages[1]` would be silently dropped and never influence generation.

Strategy: leading system turns merge into the single head system block together with the top-level `system` field (neither is dropped); a mid-conversation reminder is prepended to the following user turn, keeping its positional meaning without emitting a second `system` message or creating a new user turn; a trailing reminder with no following user turn is appended to the preceding user turn or merged into the head block.

Tests: deserialization of a system-role turn inside `messages` (no 422), folding into the following user turn, top-level plus mid-array system both surviving, leading-array merge with top-level system, trailing reminder, and a multimodal fold that preserves the image. A head-only Qwen-style template render proves the folded text is not dropped.

* fix(server): separate folded system reminder from multimodal user text

The mid-array system fold added the reminder as a separate ContentPart::Text on multimodal user turns. MessageContent::text() joins parts with an empty string, so the reminder ran into the user's words ("watch outsee this" instead of "watch out\n\nsee this"). Merge the reminder into the existing text part with the same blank-line separator the text-only path uses, falling back to a fresh part only for image-only turns. Strengthen the multimodal test to assert the exact separated output and add a consecutive mid-array system turns case.

* docs(changelog): add Unreleased entry for lablup#380 system-role fix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) 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(server): /v1/messages returns HTTP 422 for Claude Code >= 2.1.156 (system-role turns inside the messages array)

1 participant