Skip to content

fix(server): template tags in request text stay text; redraw an empty agent turn - #1029

Merged
davide221 merged 1 commit into
mainfrom
fix/thinking-only-turn
Nov 18, 2026
Merged

davide221 merged 1 commit into
mainfrom
fix/thinking-only-turn

Conversation

@Graffioh

@Graffioh Graffioh commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Why

Qwen3.8-Flash-Next ended two coding-agent trials with a reply that was thinking only: no text, no tool call, finish_reason: "stop". The agent (pi) took it as the final answer, and the task stopped half done.

Both turns stopped where the reasoning had to write the literal text </think>: the tasks were about the server's own think-tag code. The chat codec encoded </think> found in message text (a source file in a tool result, say) as the real end-of-thinking token, so the model never sees that text in plain pieces. Where it needed to write it, it sampled <|im_end|> with its thinking still open. In 896 of 901 Flash-Next turns of the run, the reasoning token count is the thinking's tokens plus one (the </think>); in both failures it is plus zero.

vLLM, SGLang, llama.cpp and Ollama encode the tag the same way. LMDeploy #4960 reports the same failure on Qwen3.8-27B. Hugging Face fixed it on the input side in transformers #47386 (sanitize_control_tokens).

Change

  • Template tags in request text stay text. PromptWriter::data() writes text taken from the request as a data piece (PromptPiece::data). The Qwen codecs write message text, earlier reasoning, tool definitions, call names, parameter names and values this way. RenderedPrompt::tokens() hands each run's data pieces to Tokenizer::encode as spans, with RenderedPrompt::markup, the added tokens the template writes itself (<think>, </think>, <tool_call>, <tool_response> and their closers). A markup token that begins inside a span is encoded alone as plain text, and the text around it splits there, as it would around the token: Hugging Face's semantics. The tags the template writes stay tokens. A user message that is only a wrapped <tool_response>…</tool_response> keeps its outer tags as tokens, since the template reads it as a tool response. DeepSeek writes content and reasoning as data; its tool blocks do not change yet.
  • Only the real tokens switch the thinking. With a codec whose vocabulary has the </think> token (think_close_token()), the emitter opens and closes thinking on the <think>/</think> tokens only (SseEmitter::set_think_tags_are_tokens, emit_token(piece, think_tag), take_think_tag). The same text written in ordinary pieces stays reasoning or content. Turn memory splits a generated turn at the token too (think_close_at, TurnMemory::Turn::think_end), and a response_format grammar engages on the token (OutputConstraint::Options::wait_for_token). A tool call buffered from the reasoning still splits on the text form, as before. Without a codec nothing changes.
  • An empty reply is drawn again. In the tool-checks path (serve_with_tool_checks), a reply that ends its turn with no text and no call (tool_checks::empty_reply) is re-run as the same request, with no note and the same cached conversation, up to twice (kEmptyRedraws). A client-set seed moves on (tool_checks::redraw), so the sample can differ. The log line gains empty=redrawn|kept. This covers what the first change can't prevent: a tag the model writes from memory.
  • A reply that ends inside its thinking says so. finish_details.close_kind is "open" when the reply ended before its thinking closed (it said "natural"), so a client can tell a thinking-only reply apart; "hard" (the budget closed it) is unchanged. The router checks only for "hard". Spec: docs/specs/thinking-budget.md §7.
  • PFlash recall encodes the request text it brings back the way the codec does (RenderedPrompt::encode_data), so a recalled tag stays text, and counts its cost the same way.
  • The turn-memory key hashes request text apart from template text, as it already did for control tokens, and a remembered turn as its token IDs. A prompt that quotes no template tag is byte- and token-identical to before.

Tested

CPU only (ROCm build of test_server_unit, no model on a GPU).

  • test_chat_codec_tags_in_request_text_stay_text: tags quoted in a user message, earlier reasoning, call arguments, a tool result and a tool description stay text, and every template tag count matches the same conversation with nothing quoted; a wrapped tool response's tags are tokens; a generated turn whose thinking spells </think> splits at the token, and its content span is right when the turn is replayed from turn memory; DeepSeek's content keeps quoted tags as text.
  • test_emitter_think_tokens_only_tokens_switch: pieces spelling </think> stay reasoning and <think> in content stays content; the tokens switch modes; a leading <think> token is dropped and a later one kept; a </think> token in content is dropped; a UTF-8 tail before a token; a call drafted in the reasoning gives the same reply as without the mode.
  • test_tool_checks_redraw_empty_reply: an empty reply then an answer sends the answer after one identical redraw; three empty replies stop after two redraws.
  • test_tool_checks: empty_reply and redraw.
  • waits_for_the_end_of_thinking_token: a grammar waiting on the </think> token stays free through the text spelled in pieces. Fails without its fix.
  • test_turn_memory_key_holds_remembered_tokens: two remembered turns with the same text and other tokens key the turns after them apart. Fails without its fix.
  • The codec test also checks encode_data keeps a quoted tag as text.
  • test_close_kind_open_when_reply_ends_in_thinking: "open" for a reply still in its thinking, "natural" after </think>, "hard" when the budget closed it. Fails without the change.
  • Golden corpus with the real Qwen3.8 27B and DeepSeek V4.1 tokenizers, and with the byte-level fixture: all pass. One deliberate token difference is new and listed in known_divergences.json: think_tags_in_content, thinking a client sends inline in an earlier assistant turn's content, now stays text for Qwen3.8 and DeepSeek. Token matches are 25 of 27 for the Qwen3.8 codec and 27 of 29 for V4.1. There is no DeepSeek V4 GGUF here; its entry is listed because its code path is V4.1's.
  • test_server_unit: 1309 passed. One failure, KvflashExactMassFixture::run_workers_thread_spawn_failure_throws_instead_of_terminating, caps the child process's address space and touches nothing here.

Not run yet: a GPU A/B on Flash-Next (the rate of empty turns, and of reasoning leaking into the answer, with the two failing requests resent about 50 times each, before and after).

Review

  • A design review (Fable 5.2) led to: the data flag on the prompt piece instead of separate spans, one Tokenizer::encode overload, one shared think_close_token(), the tag handled before the UTF-8 join in emit_token, more emitter cases in the tests, and finish_details.close_kind: "open" taken out as unrelated; it is back, since a thinking-only reply is what this PR is about.
  • GPT 6.1 Sol found three bugs, all fixed with tests: a response_format grammar engaged on the text </think> the emitter no longer treats as the end of thinking; remembered turns with the same text but different tokens shared a turn-memory key; PFlash recall turned a quoted tag back into the token.
  • A second GPT 6.1 Sol pass over those fixes found recall admission still counting with the old encoding, so a body of quoted tags was undercounted; it now counts with encode_data too. No test of its own: the cost and the emitted tokens now come from the same function.

Limits

  • DeepSeek's tool definitions and call blocks are still written as template text, so a tag quoted in them is still a token.
  • A tag the model writes from memory as a token can still end its thinking early; the redraw is the net for the empty case only.
  • The redraw runs only on the tool-checks path. A request with checks off still gets the empty reply.

🤖 Generated with Claude Code

@Graffioh
Graffioh force-pushed the fix/thinking-only-turn branch from ec7403d to bcbab55 Compare November 17, 2026 16:31
@Graffioh
Graffioh marked this pull request as ready for review November 17, 2026 16:31

@davide221 davide221 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code review

Found 1 issue.

Copy to agent

Use the copy button in the top-right corner of the block, then paste into your agent.

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.

Repository: Luce-Org/lucebox
Reviewed commit: bcbab55442a0c8bb3b1d6f689a25c46e73af8602
Verify the findings against the current code, run relevant checks for any fixes, and explain any findings you reject.

<file name="server/src/server/chat_codec.cpp">

<violation number="1" line="291" end_line="298">
think_close_at returns npos when the vocabulary has the token but the turn spells it in text, so generated_turn rejects 

`think_close_at` (chat_codec.cpp:291) is the single place that decides where a generated turn's thinking closes: with a `` token in the vocabulary it looks *only* for that token id and returns `std::string::npos` when the turn's tokens do not contain it — even when `turn.text` spells `` in ordinary pieces. That is exactly the case this pull request is about ("a tag the model writes from memory"), and it is reachable: the model samples the tag as text instead of the token.

Consequences in the changed callers:

- `QwenCodec::generated_turn` (line 817-822) passes that `npos` to `parse_turn`, which returns false for a `")` found the spelled tag and the turn was remembered.
- `DeepSeekCodec::generated_turn` (line 1350-1352) returns false for a thinking turn with `think_end == npos` for the same reason.

So every generated turn whose close was spelled rather than tokenized loses its turn-memory entry (and the cache continuity it gives) — a regression on the precise path the PR intends to support. If dropping the turn is not intended, `think_close_at` should fall back to `text.find("")` when the token id is absent from `tokens` (matching the `id &lt; 0` branch), so `parse_turn` splits at the spelled tag as it did before.

<suggestion>
size_t think_close_at(const std::string &amp; text, const std::vector&lt;int32_t&gt; &amp; tokens,
                      const Tokenizer &amp; tokenizer) {
    const int32_t id = think_close_token(tokenizer);
    if (id &lt; 0) return text.find("");
    const auto it = std::find(tokens.begin(), tokens.end(), id);
    if (it == tokens.end()) return text.find("");
    return tokenizer.decode(std::vector&lt;int32_t&gt;(tokens.begin(), it)).size();
}
</suggestion>
</violation>

</file>
Issue overview
  1. **think_close_at returns npos when the vocabulary has the token but the turn spells it in text, so generated_turn rejects ** · likely (server/src/server/chat_codec.cpp:291-298)

Reviewed bcbab554 · 1 candidate issue checked, kept at ≥70% confidence · add the code-review label to review again

Comment on lines +291 to +298
size_t think_close_at(const std::string & text, const std::vector<int32_t> & tokens,
const Tokenizer & tokenizer) {
const int32_t id = think_close_token(tokenizer);
if (id < 0) return text.find("</think>");
const auto it = std::find(tokens.begin(), tokens.end(), id);
if (it == tokens.end()) return std::string::npos;
return tokenizer.decode(std::vector<int32_t>(tokens.begin(), it)).size();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

**think_close_at returns npos when the vocabulary has the token but the turn spells it in text, so generated_turn rejects ** · likely

think_close_at (chat_codec.cpp:291) is the single place that decides where a generated turn's thinking closes: with a token in the vocabulary it looks *only* for that token id and returns `std::string::npos` when the turn's tokens do not contain it — even when `turn.text` spells in ordinary pieces. That is exactly the case this pull request is about ("a tag the model writes from memory"), and it is reachable: the model samples the tag as text instead of the token.

Consequences in the changed callers:

  • QwenCodec::generated_turn (line 817-822) passes that npos to parse_turn, which returns false for a ") found the spelled tag and the turn was remembered.
  • DeepSeekCodec::generated_turn (line 1350-1352) returns false for a thinking turn with think_end == npos for the same reason.

So every generated turn whose close was spelled rather than tokenized loses its turn-memory entry (and the cache continuity it gives) — a regression on the precise path the PR intends to support. If dropping the turn is not intended, think_close_at should fall back to text.find("") when the token id is absent from tokens (matching the id < 0 branch), so parse_turn splits at the spelled tag as it did before.

Checked (85%): think_close_at (chat_codec.cpp:291-298) returns npos when the vocab has the token but the generated tokens spell it as text, and both callers reject that turn: QwenCodec::generated_turn (chat_codec.cpp:817-822) passes npos into parse_turn, which returns false for a turn starting with "\n" (line 837-838), and DeepSeekCodec::generated_turn returns false outright (line 1351) — whereas the pre-PR code used text.find("") and accepted the turn. The spelled-tag case is reachable (it is the very 'tag written from memory' scenario the PR's redraw path exists for), so such turns lose their turn-memory entry and agent-turn cache continuity; only the consequence severity (memory loss, not user-visible failure) keeps this short of full certainty.

Suggested change
size_t think_close_at(const std::string & text, const std::vector<int32_t> & tokens,
const Tokenizer & tokenizer) {
const int32_t id = think_close_token(tokenizer);
if (id < 0) return text.find("</think>");
const auto it = std::find(tokens.begin(), tokens.end(), id);
if (it == tokens.end()) return std::string::npos;
return tokenizer.decode(std::vector<int32_t>(tokens.begin(), it)).size();
}
size_t think_close_at(const std::string & text, const std::vector<int32_t> & tokens,
const Tokenizer & tokenizer) {
const int32_t id = think_close_token(tokenizer);
if (id < 0) return text.find("");
const auto it = std::find(tokens.begin(), tokens.end(), id);
if (it == tokens.end()) return text.find("");
return tokenizer.decode(std::vector<int32_t>(tokens.begin(), it)).size();
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Not a regression, and the suggested fallback would be wrong here. With a </think> token in the vocabulary, the emitter treats a </think> spelled in ordinary pieces as part of the reasoning (that is the change), so the client receives that reply as all reasoning and no content. Turn memory keys a turn by its parsed message (TurnMemory::key(message, context)), and the client sends back what it received. Splitting at the spelled tag would remember reasoning X with content answer while the client sends reasoning X</think>…answer with empty content: an entry that never matches. npos makes the turn one whose thinking never closed, as the emitter sees it. Before this PR, a thinking turn that never closed wasn't remembered either, and on the tool-checks path that empty reply is redrawn.

The comment on think_close_at read like a fallback for this case; it now says that only the token closes the thinking and that npos means it never closed (035f333).

@Graffioh
Graffioh force-pushed the fix/thinking-only-turn branch from bcbab55 to 035f333 Compare November 17, 2026 16:40
… agent turn

Qwen3.8-Flash-Next ended agent turns inside its thinking where its reasoning
had to write the text `</think>`: the codec encoded that text in messages as
the real token, so the model had no plain spelling for it.

Template tags (`<think>`, `</think>`, `<tool_call>`, ...) inside request text
now encode as plain text, Hugging Face style (`PromptPiece::data`,
`Tokenizer::encode` spans). With a codec, only the real tokens open and close
thinking in the emitter, turn memory and a response_format grammar. PFlash
recall encodes request text the same way. The tool-checks path redraws an
empty stop reply up to twice, and finish_details.close_kind is "open" for a
reply that ends inside its thinking.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Graffioh
Graffioh force-pushed the fix/thinking-only-turn branch from 035f333 to d777222 Compare November 17, 2026 16:46
@davide221
davide221 merged commit a4d44ff into main Nov 18, 2026
13 of 15 checks passed
davide221 added a commit that referenced this pull request Nov 18, 2026
Conflict in server/test/unit/test_server_unit.cpp: keep main's new
close_kind test (#1029); the two per-format timing tests stay folded into
the PR's loop over formats.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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