ds4 icon indicating copy to clipboard operation
ds4 copied to clipboard

Streaming `/v1/messages`: a second literal think-close tag is emitted as answer text (`ANTH_STREAM_TEXT` has no close-tag handling)

Open kandaman opened this issue 4 months ago • 0 comments

(Formatting note: the think open/close markers are written inside code spans throughout, so chat clients that treat them as control tags render this cleanly.)

Summary

On the streaming Anthropic endpoint, the model frequently writes a second round of reasoning into the answer channel and closes it with a literal `</think>`. That tag, and all the draft text before it, reach the user as ordinary text_delta content. The reader sees ~90% draft, a stray close tag, and then the actual answer.

The reasoning channel itself is correct — thinking blocks are populated normally. This is not a truncation, not a parse failure, and the turn ends with a normal stop_reason; the tool call, when there is one, is delivered fine. Nothing in the response marks it as degraded, which is why it went unnoticed on our side for six weeks.

Measured (production, 2026-06-25 … 2026-08-04)

Two independent datasets from a multi-node fleet behind one proxy:

Rate ~2.2% of turns that produced answer text (harness-internal calls excluded)
Users affected multiple, across independent sessions
Backends every node in the fleet — two different quantisations, both Metal and CUDA
Context correlation 0.28% at 20–50k prompt tokens → 8.43% above 150k
Session distribution bimodal — most sessions 0%, but once it starts it persists (one session: 20 of 31 turns)

Full scan of every raw SSE dump we retain (30 days), same fleet:

Close tag in a text block 95 streams
Close tag in a thinking block 0
Opening think tag anywhere in answer text 0
Tag split across two text_delta events 0 (it is a single vocabulary token)
Streams with ≥2 tags 6
Tag character offset 0 … 86,601
Median share of the answer that precedes the tag 89.2%

Zero opening tags is the diagnostic part: the model is not writing a `<think>` block of its own. It is closing one that it believes is open.

Why it happens

  1. ds4.c — the think markers are special vocabulary tokens, and ds4_chat_append_assistant_prefix() prepends the opening one to the assistant turn. So the model never emits an opening tag; it starts already inside a thinking block.

  2. ds4_server.c:2082-2083 (unchanged in b7e9f00; 2041-2042 in 80ebbc3) — the tool-schema system prompt, injected only when the request carries tool definitions, says:

    If thinking_mode is enabled (triggered by `<think>`), you MUST output your complete reasoning inside `<think>...</think>` BEFORE any tool calls or final response.

    The model complies literally: after the first close tag has switched the stream to the text channel, it writes another reasoning pass and closes it again.

  3. anthropic_sse_stream_update() (ds4_server.c, ~7958 in b7e9f00) — the close tag is only searched for in ANTH_STREAM_THINKING:

    if (st->mode == ANTH_STREAM_THINKING) {
        const char *close = strstr(raw + st->emit_pos, "</think>");
        ...
        if (close) { st->emit_pos = ...; st->mode = ANTH_STREAM_TEXT; }
    }
    
    if (st->mode == ANTH_STREAM_TEXT) {
        const char *tool = r->has_tools ? find_any_tool_start(raw + st->emit_pos) : NULL;
        size_t limit = text_stream_safe_limit(raw, st->emit_pos, raw_len, r->has_tools, final);
        /* no close-tag handling here */
    }
    

    text_stream_safe_limit() guards DSML starts only. Once in ANTH_STREAM_TEXT, any further close tag is forwarded verbatim as a text_delta.

    openai_sse_stream_update() has the same shape (OPENAI_STREAM_TEXT likewise does not look for the tag), so we expect the OpenAI-compatible streaming endpoint to be affected identically — we have not measured that path.

Because the prompt in (2) is only injected when tools are present, this concentrates in tool-heavy, long-context agent sessions.

Reproduction conditions

Not deterministic per request — resampling the same request often produces a clean turn (we replayed one and it came back with a normal thinking + tool_use split). It reproduces as a rate, so it needs a population, not a single run:

  • streaming /v1/messages
  • request carries tool definitions (~26 tools in our sessions)
  • long prompt — the rate rises sharply above 150k tokens
  • thinking enabled

Suggested directions

  1. Stop the contradiction. The server already opens the thinking block itself, so instructing the model to emit the pair is at odds with the harness. Either drop that sentence when the prefix is auto-injected, or word it in terms of "your reasoning ends at the close tag" without asking the model to produce the pair.
  2. Defence in depth in the stream state machine. In ANTH_STREAM_TEXT / OPENAI_STREAM_TEXT, a literal close tag is never legitimate output. At minimum strip it; better, treat the text emitted since the block started as reasoning that escaped and route it accordingly. The hold = strlen("</think>") - 1 carry already used in the THINKING branch is the mechanism needed.

Fix (1) alone would address the cause; (2) makes the symptom impossible regardless of what the model does.

Related issues — we believe this is distinct from all three

  • #509 — same family, but scoped by its author to non-streaming /v1/chat/completions truncated at finish_reason: length, with "streaming is correct" stated explicitly. Here nothing is truncated and the path is streaming.
  • #318 — the close tag is missing, so the tool call is swallowed and the session stalls. Here the tag is present and the tool call is delivered correctly; the damage is that draft text reaches the reader as the answer.
  • #675 — the forced-injection recovery path. In our turns that recovery never fires: the model closes the first block on its own, and the leak is a second block opened afterwards in the text channel.

Environment

  • Build: 80ebbc3 (2026-06-17) on every node. All three mechanism points above were re-checked against b7e9f00 and are unchanged there (the prompt verbatim, the prefix push, and the absence of close-tag handling in ANTH_STREAM_TEXT), and none of the 96 commits in 80ebbc3..b7e9f00 touch the reasoning-channel split. We have not re-measured the rate on b7e9f00 binaries, and we are not assuming it carries over — #675 reports engine-side changes in that range that alter behaviour right at the close tag, so the frequency may well differ even though the code that permits the leak does not.
  • Models: official DeepSeek-V4-Flash GGUFs — both the IQ2XXS mix and a Q4KExperts build. Occurs on both, so it is not quantisation-specific.
  • Hardware: several Apple Silicon nodes (Metal) and one CUDA node. Occurs on all of them.
  • Clients: Claude Code via an Anthropic-shaped proxy.

We can put together a synthetic SSE reproduction if that would help.

kandaman avatar Aug 04 '26 09:08 kandaman