Skip to content

fix(server): stop merging consecutive user messages - #980

Open
NVolcz wants to merge 1 commit into
ROCm:mainfrom
NVolcz:separate-merged-messages
Open

NVolcz wants to merge 1 commit into
ROCm:mainfrom
NVolcz:separate-merged-messages

Conversation

@NVolcz

@NVolcz NVolcz commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

normalize_messages merges consecutive user messages into one message and puts nothing between their texts, so the words of two messages run together:

<|turn>user
Hi.What is 2+2?<turn|>

Clients do send such messages. For example, Pi drops a reply the user aborted, which leaves two user messages in a row.

User messages are now passed on as they are, and the chat template decides how to render them, as llama.cpp, vLLM and transformers do. Gemma 4's template renders separate turns:

<|turn>user
Hi.<turn|>
<|turn>user
What is 2+2?<turn|>

Leading system messages are still folded into one, now with a blank line between their texts. The Qwen3.5/3.6/3.8, D3 and MiniCPM-V templates reject a second system message, Gemma 3 only reads the first one, and Hy-MT2 drops the rest, so clients that send a base system prompt plus an injected one keep working.

A template that rejects the messages, such as Gemma 3's "Conversation roles must alternate", now returns a 400 invalid_request_error instead of a 500 that clears the engine context and that clients retry. AutoModel::_render_chat_template converts the template's error; Hy-Memory now renders through it like the other models. test_errors.consecutive_messages covers both cases.

How to reproduce

Send two user messages in a row, then ask about the second one:

curl -s http://localhost:52625/v1/chat/completions -H 'Content-Type: application/json' -d '{
  "model": "gemma4-it:e2b", "temperature": 0, "max_tokens": 20,
  "messages": [
    {"role": "user", "content": "Apples are red."},
    {"role": "user", "content": "Bananas are yellow."},
    {"role": "user", "content": "What is the first word of my second message? Answer with that word only."}
  ]}' | jq -r '.choices[0].message.content'

On main the answer is What: the model sees one message, "Apples are red.Bananas are yellow.What is the first word…". On this branch it is Bananas.

The same request on gemma3:1b returns HTTP 400 with "the chat template rejected the messages: Conversation roles must alternate…" instead of a 500.

I found this while reading the prompts flm renders, with a small debug branch that logs every prompt to a file (log-prompt, FLM_LOG_PROMPT=<file>).

@tawei-amd
tawei-amd requested a review from zaneni6 November 7, 2026 21:54

@zaneni6 zaneni6 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this. Not merging user messages is the right fix for the "Hi.What is 2+2?" problem. Dropping the system merge as well breaks requests that work today, though, so I'd like a few changes before this goes in.

1. Keep merging leading system messages (blocking)

On main, [system, system, user] is folded into a single system message. Several templates we ship depend on that:

  • Qwen3.5 (0.8B/2B/4B/9B), Qwen3.6-35B-A3B, Qwen3.8-27B, all D3 models, MiniCPM-V-4.7: their chat_template.jinja has
    {%- if message.role == "system" %}{%- if not loop.first %}{{- raise_exception('System message must be at the beginning.') }}
    With this PR, the second system message raises an exception and the request fails. Agent and IDE clients that send a base system prompt plus an injected one (project rules, environment info) hit this.
  • Gemma3 / Medgemma / Translategemma: only messages[0] is taken as the system prompt, so a second system message fails the "roles must alternate" check.
  • Hy-MT2: renders only messages[0] as the system prompt and skips other system messages, so the second one is dropped silently.

Please keep folding consecutive leading system messages into one, joined with "\n\n" so their text doesn't run together (the bug this PR fixes for user messages).

2. Template rejections should be a 400, not a 500

The description says alternation-only templates "now reject such a request, as it does on llama.cpp and vLLM". In FLM, though, minja's raise_exception throws a plain std::runtime_error. AutoModel::_render_chat_template doesn't wrap it, so it reaches the catch around insert() in rest_handler.cpp. OpenAIExceptionResponse turns that into {type: server_error, code: 500}, and the handler also clears the engine context and the prompt cache. Clients that retry on 5xx will keep retrying a request that can never succeed.

Wrapping the render in _render_chat_template and rethrowing a template error as ModelRequestError(400, ...) would match what the description promises. A user/user request on Gemma 3 would then get a clear 400.

3. Tidy-up (non-blocking)

With the merge branches removed, the rest of normalize_messages is scaffolding that only the merging needed:

  • messages is taken by value, so the function can edit it in place. The empty() check, the index loop, the per-message copy and the separate normalized array are no longer needed.
  • json::erase(key) does nothing when the key is missing, so the three contains() guards are redundant:
    for (const char* key : {"thinking", "reasoning", "reasoning_content"}) msg.erase(key);
  • The new @return text ("consecutive messages of one role stay separate…") describes what the function no longer does. That fits the commit message better, and in the code it will go stale. A one-line @brief that says what the function does now is enough.

4. Related, out of scope

normalize_template still joins several text parts inside one message with merged_text += ... and no separator, which gives the same run-together text. vLLM joins them with "\n". A follow-up would be welcome.

Note on #981

#981 rewrites the same function and conflicts with this PR. Could you land this one first and rebase #981 on it, or combine the two? Once user messages are no longer merged, #981's doc comment about merging them is out of date.

normalize_messages merged consecutive user messages into one and put nothing between their texts,
so "Hi." followed by "What is 2+2?" reached the model as "Hi.What is 2+2?". Clients send such
messages, for example Pi after dropping a reply the user aborted. User messages now stay separate
and the chat template decides how to render them, as llama.cpp, vLLM and transformers do.

Leading system messages are still folded into one, now with a blank line between their texts:
the Qwen3.5/3.6/3.8, D3 and MiniCPM-V templates reject a second system message, Gemma 3 takes
only the first, and Hy-MT2 drops the rest. normalize_messages edits the messages in place.

A chat template that rejects the messages (raise_exception, e.g. roles that must alternate on
Gemma 3) now gives a 400 invalid_request_error instead of a 500 that clears the engine context
and that clients retry. Hy-Memory renders through _render_chat_template like the other models.
@NVolcz
NVolcz force-pushed the separate-merged-messages branch from 1b1dcac to c23500b Compare November 21, 2026 16:39
@NVolcz NVolcz changed the title fix(server): stop merging consecutive user and system messages fix(server): stop merging consecutive user messages Nov 21, 2026
@NVolcz

NVolcz commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review. Updated and rebased on current main (c23500b):

  1. Leading system messages are folded into one again, joined with a blank line. Only leading ones: a system message later in the conversation stays where it is.
  2. Template rejections are a 400. _render_chat_template turns a std::runtime_error from the template into ModelRequestError(400, …, "invalid_request_error"), so the context and prompt cache are left alone. Hy-Memory called chat_tmpl->apply directly, so it now goes through _render_chat_template too. Checked on gemma3:1b: user/user now gives a 400 with "the chat template rejected the messages: Conversation roles must alternate…", and the next request works.
  3. Tidy-up: normalize_messages edits the messages in place, erases the reasoning fields in one loop, and has a one-line @brief. original_indices from fix(server): bind parallel tool results to their call IDs for positional OGA templates #1069 keeps its meaning (the folded system message maps to index 0).
  4. Text parts inside one message in normalize_template: agreed, left for a follow-up.

Added test_errors.consecutive_messages (two system messages must work; two user messages must work or get a 400 invalid_request_error). test_errors.py passes on gemma4-it:e2b (13 passed, 1 skipped), and the new case passes on gemma3:1b.

I'll rebase #981 on this branch.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants