Skip to content
Merged
65 changes: 62 additions & 3 deletions components/src/dynamo/frontend/prepost.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import json
import os
import re
from collections.abc import Awaitable, Callable, Sequence
from concurrent.futures import ThreadPoolExecutor
from copy import deepcopy
Expand Down Expand Up @@ -915,10 +916,53 @@ def _tool_end_markers(self) -> tuple[str, ...]:
)
)

@staticmethod
# A text-grammar reasoning parser can only split the stream if the model's
# content-kind control markers survive detokenisation, which is why
# ParserEngine.adjust_request forces `skip_special_tokens = False`. But nothing
# then removes the markers the parser did NOT consume, so terminal ones leak
# into user-visible content, e.g.:
# content = "<|end_message|>408<|end_message|>"
# As shipped the two settings are mutually exclusive: the default strips the
# markers before the parser can split (reasoning is silently dropped), and
# False leaks them into the answer. Keep the markers for the parser, then strip
# the residue afterwards.
#
# Scope is deliberately narrow: only when a parser is actually active (the only
# case where skip_special_tokens was forced off), and only over the `<|...|>`
# control-token shape. `reasoning` is left untouched -- it is already clean, and
# rewriting it would risk mangling legitimate text the model quoted.
#
# Why a shape rather than `self._control_markers` (this class already collects
# `tokenizer.all_special_tokens` for _is_control_only_content): one of the three
# call sites seeds `delta_message` from the raw `delta_text` *before* tool
# parsing, and its result reaches the `_tool_start_markers()` scan that decides
# whether to buffer for tool extraction. A blanket special-token strip there
# would delete a tool-call marker that is also a special token and silently
# break tool detection. The two are near-identical in practice -- for
# Qwen/Qwen3-0.6B every entry of `all_special_tokens` matches this pattern --
# but the shape cannot reach a marker a parser owns.
_CONTROL_MARKER_RE = re.compile(r"<\|[A-Za-z0-9_]+\|>")
Comment thread
yifjiang marked this conversation as resolved.
Resolved

def _strip_control_markers(self, text: str | None) -> str | None:
if not text:
return text
if self.reasoning_parser is None and self.tool_parser is None:
return text
# A tool parser may own a marker of this shape (`<|tool_call|>` and
# friends). Those belong to its wire format and are consumed downstream, so
# stripping them here would blind the tool-start scan described above.
preserved = self._tool_start_markers() + self._tool_end_markers()
if not preserved:
return self._CONTROL_MARKER_RE.sub("", text)
return self._CONTROL_MARKER_RE.sub(
lambda match: match.group(0) if match.group(0) in preserved else "",
text,
)

def _compose_delta_message(
reasoning: str | None, content: str | None
self, reasoning: str | None, content: str | None
) -> DeltaMessage | None:
content = self._strip_control_markers(content)
delta_message = DeltaMessage(reasoning=reasoning, content=content)
if not delta_message.reasoning and not delta_message.content:
return None
Expand Down Expand Up @@ -1045,6 +1089,17 @@ def _emit_tool_calls_choice(self, output: Any) -> dict[str, Any]:
def _build_choice(self, output: Any, delta: dict[str, Any]) -> dict[str, Any]:
if delta.get("tool_calls"):
self._tool_call_choices_emitted.add(output.index)
# _compose_delta_message covers the parser paths, but _build_choice has
# several call sites and some seed `delta["content"]` directly, so a leading
# marker survives a strip applied only at the composer. This is the last
# point every choice passes through, so the invariant "no control markers
# reach the client" is enforced here once rather than at each producer.
if isinstance(delta.get("content"), str):
stripped = self._strip_control_markers(delta["content"])
if stripped:
delta["content"] = stripped
else:
delta.pop("content", None)
return {
"index": output.index,
"delta": delta,
Expand Down Expand Up @@ -1124,7 +1179,11 @@ def process_output(self, output: Any) -> dict[str, Any] | None:
current_text = self.previous_text + delta_text
current_token_ids = self.previous_token_ids + delta_token_ids

delta_message: DeltaMessage | None = DeltaMessage(content=delta_text)
# Seeds the delta directly rather than through _compose_delta_message, so it
# needs the same control-marker strip.
delta_message: DeltaMessage | None = DeltaMessage(
Comment thread
yifjiang marked this conversation as resolved.
Resolved
content=self._strip_control_markers(delta_text)
)

# ------------------------------------------------------------------
# Drain the tool-text buffer (populated when </think> and <tool_call>
Expand Down
160 changes: 160 additions & 0 deletions components/src/dynamo/frontend/tests/test_vllm_processor_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -1708,6 +1708,166 @@ async def test_root_thinking_suppresses_deployment_default(self, tokenizer):
assert "thinking_mode" not in result.chat_template_kwargs


class _MarkerOwningToolParser:
"""A tool parser whose own marker happens to match the control-token shape."""

tool_call_start_token = "<|tool_call|>"
tool_call_end_token = "<|tool_call_end|>"

def __init__(self, tokenizer=None, tools=None):
del tokenizer, tools


class TestControlMarkerStrip:
Comment thread
yifjiang marked this conversation as resolved.
Resolved
"""Unconsumed `<|...|>` control markers must not reach the client.

A text-grammar reasoning parser can only split the stream if the model's
content-kind markers survive detokenisation, which is why
ParserEngine.adjust_request forces skip_special_tokens=False. Nothing then
removes the markers the parser did not consume, so terminal ones leak into
visible content: content = "<|end_message|>408<|end_message|>".
"""

@staticmethod
def _post(tokenizer, *, tool_parser=None, reasoning_parser_class=None):
request = json.loads(json.dumps(TOOL_REQUEST))
request.pop("tools", None)
request, _, _, _, _ = _prepare_request(
request, tokenizer=tokenizer, tool_parser_class=None
)
return StreamingPostProcessor(
tokenizer=tokenizer,
request_for_sampling=request,
sampling_params=SamplingParams(),
prompt_token_ids=[],
tool_parser=tool_parser,
reasoning_parser_class=reasoning_parser_class,
chat_template_kwargs={},
stream_response=True,
)

def _active(self, tokenizer):
"""A postprocessor with a parser active, which is the only gated case."""
return self._post(tokenizer, tool_parser=_FakeGrammarToolParser())

# -- the strip itself -------------------------------------------------

@pytest.mark.parametrize(
"text, expected",
[
# The reported leak: terminal markers around the real answer.
("<|end_message|>408<|end_message|>", "408"),
("<|content_text|>hello", "hello"),
("mid<|end_message|>stream", "midstream"),
("no markers here", "no markers here"),
("", ""),
(None, None),
# Anchored on both delimiters, so ordinary prose is untouched.
("a <| b |> c", "a <| b |> c"),
# `-` is not in the character class.
("<|end-message|>", "<|end-message|>"),
],
)
def test_strip_cases(self, tokenizer, text, expected):
assert self._active(tokenizer)._strip_control_markers(text) == expected

def test_no_parser_active_leaves_text_untouched(self, tokenizer):
"""The gate: models that never had markers stripped are unaffected."""
post = self._post(tokenizer)
assert post.tool_parser is None and post.reasoning_parser is None
assert (
post._strip_control_markers("<|end_message|>408")
== "<|end_message|>408"
)

def test_a_parsers_own_markers_survive(self, tokenizer):
"""A tool marker of this shape belongs to the parser's wire format.

The seed site strips before tool parsing, and its result feeds the
_tool_start_markers() scan that decides whether to buffer for tool
extraction. Stripping the parser's own marker there would silently break
tool detection.
"""
post = self._post(tokenizer, tool_parser=_MarkerOwningToolParser())
assert (
post._strip_control_markers("<|tool_call|>{}<|tool_call_end|>")
== "<|tool_call|>{}<|tool_call_end|>"
)
# Markers it does not own are still stripped.
assert (
post._strip_control_markers("<|end_message|>x<|tool_call|>")
== "x<|tool_call|>"
)

# -- the funnel -------------------------------------------------------

def test_build_choice_strips_content_seeded_directly(self, tokenizer):
"""_build_choice has several call sites that bypass the composer.

A strip applied only at _compose_delta_message still let a leading marker
through; enforcing the invariant at the funnel is what closed it.
"""
post = self._active(tokenizer)
choice = post._build_choice(
SimpleNamespace(index=0, finish_reason=None, logprobs=None),
{"role": "assistant", "content": "<|end_message|>408"},
)
assert choice["delta"]["content"] == "408"

def test_build_choice_drops_content_that_was_only_markers(self, tokenizer):
"""An all-marker delta must lose the key, not carry an empty string."""
post = self._active(tokenizer)
choice = post._build_choice(
SimpleNamespace(index=0, finish_reason=None, logprobs=None),
{"role": "assistant", "content": "<|end_message|>"},
)
assert "content" not in choice["delta"]

def test_compose_delta_message_strips_content_and_keeps_reasoning(
self, tokenizer
):
"""`reasoning` is deliberately left alone -- it is already clean, and
rewriting it would risk mangling text the model quoted."""
post = self._active(tokenizer)
delta = post._compose_delta_message(
"thought about <|end_message|>", "<|end_message|>408"
)
assert delta is not None
assert delta.content == "408"
assert delta.reasoning == "thought about <|end_message|>"

def test_process_output_strips_the_directly_seeded_delta(self, tokenizer):
"""End to end through process_output, the third strip site."""
post = self._active(tokenizer)
choice = post.process_output(
SimpleNamespace(
index=0,
text="<|end_message|>408<|end_message|>",
token_ids=[],
finish_reason="stop",
logprobs=None,
)
)
assert choice is not None
assert "<|" not in (choice["delta"].get("content") or "")
assert choice["delta"].get("content") == "408"

def test_plain_text_path_is_untouched(self, tokenizer):
"""No parser => the fast plain-text path must not be rewritten."""
post = self._post(tokenizer)
choice = post.process_output(
SimpleNamespace(
index=0,
text="<|end_message|>408",
token_ids=[],
finish_reason="stop",
logprobs=None,
)
)
assert choice is not None
assert choice["delta"]["content"] == "<|end_message|>408"


class TestToolCallGuidedDecoding:
def _request(self, tokenizer, **overrides):
raw_request = {**TOOL_REQUEST, "tool_choice": "auto", **overrides}
Expand Down
Loading