[GH-ISSUE #4077] [Engine] A bare closing think tag inside the model's own reasoning ends the thinking; the rest of it streams out as the answer #1771

Open
opened 2026-11-04 01:53:55 +07:00 by bsakaguchi · 8 comments
Owner

Originally created by @ackalker on GitHub (Oct 25, 2026).
Original GitHub issue: https://github.com/Niko1221/Strata/issues/4077

Area

[Engine] (speed, kernels, models, the server and API)

Engine (serve/), run from source: serve/server.py started as
python serve/server.py --engine strata --config strata-iq3_s.json.

Desktop app, Terminal or source?

Source (START-HERE.bat, setup.sh or a build)

Reproduction status

Reproduced locally - deterministic at parser level (the attached script
feeds serve.frontend.OutputParser in 7-character deltas, like a real server feed; no model, no
GPU). The symptom was also seen end to end in an agent session on 2026-10-25: the second half of a
model's reasoning appeared as the visible answer.

What happened

A closing think tag that the model writes inside its own reasoning ends the thinking block, and
everything after it is streamed out as ordinary answer content. Half a chain of thought appears in
the answer, with the tag itself visible in the middle of it.

#537 handled the case where the model quotes the tag - _quoted_think_end()
(serve/frontend.py:1093) recognises the form where the closer sits directly after a quote or a
backtick and is followed by non-newline text, and keeps it as reasoning
(serve/frontend.py:1349-1352). Every other position ends the thinking
(serve/frontend.py:1353-1357): the state switches to content and the rest of the reasoning is
delivered as the answer. In particular a closer at the start of a line - which is what a model
writes when it is reasoning about the chat format itself - always ends it.

This is not an unusual thing for these models to reason about: the request's own system text shows
them the call format, tags included (serve/chat_template.jinja:83), and
serve/chat_template.jinja:119 replays earlier turns' reasoning with the tags in place.

It also feeds itself, which is why one bad turn turns into a run of bad turns: the leaked text comes
back as assistant content, and mark_think_literals() deliberately leaves call markup inside an
assistant message exactly as written (serve/frontend.py:362 and :366; the reasoning for that is
the #2026 comment at serve/frontend.py:266-273). So if a leak carries an opening call tag, the
next request hands the model the real call token in an assistant turn, and the next turn drifts
further. The input side is already masked for reasoning (repro.py case 5 shows a literal closer
inside reasoning_content being replaced by its mark), so this is about the output side and about
what the leak then carries.

Two facts that bear on a fix, both reproduced:

  • A quoted closer followed by more reasoning stays reasoning (repro.py case 1) - that is #537
    working, and the case that does not reproduce.
  • A second closer later in the same turn is already plain text: after the parser has switched to
    content, a later closer is emitted inside the answer rather than changing state. So "the closer
    that ends the thinking" is a single decision made at the first bare occurrence.

Expected

Either do not end the reasoning at a bare closer that is followed by more reasoning-shaped text
(the model was quoting the tag, as it does for #537's quoted form, just without the quote mark), or
mask/document it the way the input side does, so a model that talks about its own format does not
leak its reasoning into the answer.

Smallest steps or command that reproduce it

repro.py (attached below) runs every case against a checkout; from the repository root:

python3 repro.py --repo .

Case 1 is the #537 control (stays reasoning, does not reproduce). Case 2 is this problem:
reasoning, a bare closer at the start of a line, more reasoning text, then the answer. The script
prints the reasoning text, the answer text and the counters for each case. In the script the markup
strings are built at runtime from chr(60) / chr(62) and are never written literally in the file,
so reading the script cannot inject markup into a session or an editor buffer.

In prose, case 2's input is: open tag, first part of the reasoning, newline, a bare closer,
second part of the reasoning leaks into the answer, another closer, blank line, the answer.
Observed split: reasoning stops after the first part; the answer is the second part, the visible
closer, and then the answer text.

Strata version

v0.2.4.2-6-g7dd5cf18 (source checkout, git describe), engine 0.1.49.1.

Re-verified against main as fetched on 2026-10-25 (fa663fab, 136 commits newer): git diff 7dd5cf18 fa663fab -- serve/ is empty and case 2 reproduces identically there.

Graphics card, memory and system

RTX 5080 16 GB · 60 GB RAM · Linux (CachyOS, kernel 7.3.0-5), Python 3.13. The parser reproduction
needs no GPU, no model file and no server.

Model, size and settings

Where it was seen end to end: Qwen3.8-Flash-Next GGUF IQ3_XXS and IQ3_S, 131072 context, behind
llama-swap with metadata.reasoning = {format: qwen3.8, levels: [low, medium, xhigh]}, reasoning
replayed (preserve_thinking: true, which is also the template's own default,
serve/chat_template.jinja:119). The parser case needs none of that: thinking=True is enough.

Logs

Nothing is logged when the thinking ends early - the counters (unread, rescued, refused) all
stay 0, and there is no [strata] line for it.

  • #537 (closed, "the quoted-closer form") fixed the quoted spelling; this is the bare
    spelling of the same tag and it is not covered.
  • #1058 (closed) is the mirror-image rule for openers quoted in prose (fences / inline code).
  • #2266 (closed) is about the literal control-token string stopping generation at the engine level,
    a different layer.

Attached: repro.py (self-contained; the markup strings are built at runtime, never literal in the file)

#!/usr/bin/env python3
"""Deterministic parser-level repro of three Strata `serve` defects seen through llama-swap + Pi.

Run:  python3 repro.py [--repo /path/to/Strata] [--old]
      (--old also runs case A against the parser as of 2026-10-20, i.e. before 70f42407.)

This file never contains the markup tags literally: they are built from chr(60)/chr(62) at
runtime. Keep it that way - a session whose context contains them verbatim can corrupt itself
(see README.md, "Why this file is written like this").
"""
import argparse
import importlib.util
import os
import subprocess
import sys

T, G = chr(60), chr(62)
THINK_OPEN, THINK_CLOSE = f"{T}think{G}", f"{T}/think{G}"
CALL_OPEN, CALL_CLOSE = f"{T}tool_call{G}", f"{T}/tool_call{G}"
PARAM_CLOSE, FUNC_CLOSE = f"{T}/parameter{G}", f"{T}/function{G}"


def func(name):
    return f"{T}function={name}{G}"


def param(name):
    return f"{T}parameter={name}{G}"


# flat (Responses spelling): OutputParser.__init__ does {t.get("name"): t for t in tools}
TOOLS = [
    {"name": "bash", "parameters": {"type": "object",
     "properties": {"command": {"type": "string"}}, "required": ["command"]}},
    {"name": "read", "parameters": {"type": "object",
     "properties": {"path": {"type": "string"}}}},
]


def load_parser(repo, old=False):
    """Return (label, OutputParser, needs_extra_kwargs) for the current or the pre-70f42407 parser."""
    sys.path.insert(0, repo)
    if not old:
        from serve.frontend import OutputParser
        return "current HEAD", OutputParser
    src = subprocess.run(["git", "-C", repo, "show", "70f42407^:serve/frontend.py"],
                         capture_output=True, text=True, check=True).stdout
    path = "/tmp/strata_frontend_pre_70f42407.py"
    open(path, "w").write(src)
    spec = importlib.util.spec_from_file_location("strata_frontend_old", path)
    mod = importlib.util.module_from_spec(spec)
    sys.modules["strata_frontend_old"] = mod          # dataclass needs the module registered
    spec.loader.exec_module(mod)
    return "70f42407^ (2026-10-20)", mod.OutputParser


def run(cls, text, tools=TOOLS, declared_only=True, recover=False, chunk=7):
    kw = {}
    try:                                   # pre-70f42407 has no declared_only / recover
        p = cls(thinking=True, tools=tools, stream_tools=False,
                recover=recover, declared_only=declared_only)
    except TypeError:
        p = cls(thinking=True, tools=tools, stream_tools=False)
    evs = []
    for i in range(0, len(text), chunk):   # stream in small deltas, like a real server feed
        evs += p.feed(text[i:i + chunk])
    evs += p.finish("stop")
    return evs, p


def show(title, evs, p, expect, bug=False):
    """expect(calls, content_text, reasoning_text, parser) -> True when the case behaved as claimed.
    bug=True means the claimed behaviour is the defect, so True prints REPRODUCED."""
    calls = [e.call for e in evs if e.kind == "tool_call"]
    text = "".join(e.text for e in evs if e.kind == "content")
    reasoning = "".join(e.text for e in evs if e.kind == "reasoning")
    ok = expect(calls, text, reasoning, p)
    if bug:
        verdict = "REPRODUCED" if ok else "*** DID NOT REPRODUCE ***"
    else:
        verdict = "as intended" if ok else "*** REGRESSION / CHANGED BEHAVIOUR ***"
    print(f"\n=== {title}\n    {verdict}")
    print(f"    reasoning: {reasoning[:70]!r}")
    print(f"    content  : {text[:160]!r}")
    print(f"    calls    : {[(c.name, c.arguments) for c in calls]}")
    print(f"    unread   : {getattr(p, 'unread', 'n/a (pre-70f42407)')} "
          f"{getattr(p, 'unread_names', '')}  rescued={p.rescued} refused={p.refused}")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--repo", default=os.environ.get("STRATA", os.path.expanduser("~/pg/Strata")))
    ap.add_argument("--old", action="store_true", help="also compare against the pre-70f42407 parser")
    a = ap.parse_args()

    label, cls = load_parser(a.repo)
    print(f"Strata repo: {a.repo}   parser: {label}")

    # 0. sanity: a clean, well-formed, declared call parses
    clean = (f"{THINK_OPEN}\nLet me run it.\n{THINK_CLOSE}\n\n"
             f"{CALL_OPEN}\n{func('bash')}\n{param('command')}\nls\n{PARAM_CLOSE}\n{FUNC_CLOSE}\n{CALL_CLOSE}")
    evs, p = run(cls, clean)
    show("0. sanity - clean declared call (must parse as a call)", evs, p,
         lambda c, t, r, p: len(c) == 1 and c[0].name == "bash" and c[0].arguments == {"command": "ls"})

    # 1. CONTROL: a think-close quoted with backticks inside the thinking stays reasoning text (#537)
    quoted = (f"{THINK_OPEN}\nI wrote `{THINK_CLOSE}` inside my reasoning\n"
              f"and kept thinking here\n{THINK_CLOSE}\n\nall done")
    evs, p = run(cls, quoted)
    show("1. control - quoted think-close in thinking (#537 protects this)", evs, p,
         lambda c, t, r, p: "kept thinking" in r and "kept thinking" not in t)

    # 2. DEFECT B: the same tag at line start ends the reasoning block; the rest leaks as content
    leak = (f"{THINK_OPEN}\nfirst part of the reasoning\n{THINK_CLOSE}\n"
            f"second part of the reasoning leaks into the answer\n{THINK_CLOSE}\n\nthe answer")
    evs, p = run(cls, leak)
    show("2. DEFECT B - bare think-close mid-thinking leaks the rest as visible content", evs, p,
         lambda c, t, r, p: "leaks into the answer" in t, bug=True)

    # 3. DEFECT A: a well-formed call for a tool the request did not declare comes back as text
    undeclared = (f"{THINK_OPEN}\nplan\n{THINK_CLOSE}\n\n{CALL_OPEN}\n{func('AskUserQuestion')}\n"
                  f"{param('questions')}\n[]{PARAM_CLOSE}\n{FUNC_CLOSE}\n{CALL_CLOSE}")
    evs, p = run(cls, undeclared)
    show("3. DEFECT A - call for an undeclared name returns as text, loop cannot continue", evs, p,
         lambda c, t, r, p: not c and "AskUserQuestion" in t and p.unread == 1, bug=True)

    # 4. DEFECT C: literal call markup inside a parameter value truncates the call silently
    inner = (f"python3 - <<'EOF'\ntext = '''{CALL_OPEN}\n{func('read')}\n"
             f"{param('path')}\n/tmp/x\n{PARAM_CLOSE}")
    trunc = (f"{THINK_OPEN}\nplan\n{THINK_CLOSE}\n\n{CALL_OPEN}\n{func('bash')}\n{param('command')}\n"
             f"{inner}\n{PARAM_CLOSE}\n{FUNC_CLOSE}\n{CALL_CLOSE}\nok")
    evs, p = run(cls, trunc)
    show("4. DEFECT C - markup in an argument value truncates args silently (unread stays 0)", evs, p,
         lambda c, t, r, p: len(c) == 1 and "EOF" in str(c[0].arguments)
         and not str(c[0].arguments).endswith("EOF'\n") and p.unread == 0, bug=True)

    evs, p = run(cls, trunc, recover=True)
    show("4b. DEFECT C with tool_call_recovery=True (does NOT help)", evs, p,
         lambda c, t, r, p: len(c) == 1 and p.unread == 0, bug=True)

    # 5. Not a defect, but the answer to "is replayed thinking the cause?": think-tags in a replayed
    #    assistant message ARE masked by mark_think_literals; tool-call literals deliberately are not.
    from serve.frontend import mark_think_literals, literal_tags
    def ctrl(name):                       # control tokens are never spelled literally either
        return chr(60) + chr(124) + name + chr(124) + chr(62)
    tags = literal_tags((ctrl("im_start"), ctrl("im_end")))
    msgs = [{"role": "assistant", "content": "answer",
             "reasoning_content": f"I wrote\n{THINK_CLOSE}\nand also {CALL_OPEN} bare in my thinking"}]
    out, _, changed = mark_think_literals(msgs, None, tags)
    rc = out[0]["reasoning_content"]
    print("\n=== 5. input side: mark_think_literals on a replayed assistant message")
    print(f"    changed: {changed}")
    print(f"    think-close masked in reasoning_content : {THINK_CLOSE not in rc}")
    print(f"    tool_call-open masked in assistant msg  : {CALL_OPEN not in rc}"
          "   <- False is intentional (frontend.py:366)")

    if a.old:
        olabel, ocls = load_parser(a.repo, old=True)
        evs, p = run(ocls, undeclared)
        show(f"6. DEFECT A on parser {olabel} - same input, different behaviour", evs, p,
             lambda c, t, r, p: len(c) == 1 and c[0].name == "AskUserQuestion", bug=True)


if __name__ == "__main__":
    main()
Originally created by @ackalker on GitHub (Oct 25, 2026). Original GitHub issue: https://github.com/Niko1221/Strata/issues/4077 ### Area [Engine] (speed, kernels, models, the server and API) Engine (`serve/`), run from source: `serve/server.py` started as `python serve/server.py --engine strata --config strata-iq3_s.json`. ### Desktop app, Terminal or source? Source (START-HERE.bat, setup.sh or a build) ### Reproduction status Reproduced locally - deterministic at parser level (the attached script feeds `serve.frontend.OutputParser` in 7-character deltas, like a real server feed; no model, no GPU). The symptom was also seen end to end in an agent session on 2026-10-25: the second half of a model's reasoning appeared as the visible answer. ### What happened A closing think tag that the model writes *inside* its own reasoning ends the thinking block, and everything after it is streamed out as ordinary answer `content`. Half a chain of thought appears in the answer, with the tag itself visible in the middle of it. `#537` handled the case where the model quotes the tag - `_quoted_think_end()` (`serve/frontend.py:1093`) recognises the form where the closer sits directly after a quote or a backtick and is followed by non-newline text, and keeps it as reasoning (`serve/frontend.py:1349-1352`). Every other position ends the thinking (`serve/frontend.py:1353-1357`): the state switches to `content` and the rest of the reasoning is delivered as the answer. In particular a closer at the start of a line - which is what a model writes when it is reasoning *about the chat format itself* - always ends it. This is not an unusual thing for these models to reason about: the request's own system text shows them the call format, tags included (`serve/chat_template.jinja:83`), and `serve/chat_template.jinja:119` replays earlier turns' reasoning with the tags in place. It also feeds itself, which is why one bad turn turns into a run of bad turns: the leaked text comes back as assistant **content**, and `mark_think_literals()` deliberately leaves call markup inside an assistant message exactly as written (`serve/frontend.py:362` and `:366`; the reasoning for that is the #2026 comment at `serve/frontend.py:266-273`). So if a leak carries an opening call tag, the next request hands the model the real call token in an assistant turn, and the next turn drifts further. The input side is already masked for reasoning (`repro.py` case 5 shows a literal closer inside `reasoning_content` being replaced by its mark), so this is about the output side and about what the leak then carries. Two facts that bear on a fix, both reproduced: - A quoted closer followed by more reasoning stays reasoning (`repro.py` case 1) - that is #537 working, and the case that does not reproduce. - A *second* closer later in the same turn is already plain text: after the parser has switched to `content`, a later closer is emitted inside the answer rather than changing state. So "the closer that ends the thinking" is a single decision made at the first bare occurrence. ### Expected Either do not end the reasoning at a bare closer that is followed by more reasoning-shaped text (the model was quoting the tag, as it does for #537's quoted form, just without the quote mark), or mask/document it the way the input side does, so a model that talks about its own format does not leak its reasoning into the answer. ### Smallest steps or command that reproduce it `repro.py` (attached below) runs every case against a checkout; from the repository root: ```sh python3 repro.py --repo . ``` Case 1 is the #537 control (stays reasoning, does **not** reproduce). Case 2 is this problem: reasoning, a bare closer at the start of a line, more reasoning text, then the answer. The script prints the reasoning text, the answer text and the counters for each case. In the script the markup strings are built at runtime from `chr(60)` / `chr(62)` and are never written literally in the file, so reading the script cannot inject markup into a session or an editor buffer. In prose, case 2's input is: open tag, `first part of the reasoning`, newline, a bare closer, `second part of the reasoning leaks into the answer`, another closer, blank line, `the answer`. Observed split: reasoning stops after the first part; the answer is the second part, the visible closer, and then the answer text. ### Strata version `v0.2.4.2-6-g7dd5cf18` (source checkout, `git describe`), engine 0.1.49.1. Re-verified against `main` as fetched on 2026-10-25 (`fa663fab`, 136 commits newer): `git diff 7dd5cf18 fa663fab -- serve/` is empty and case 2 reproduces identically there. ### Graphics card, memory and system RTX 5080 16 GB · 60 GB RAM · Linux (CachyOS, kernel 7.3.0-5), Python 3.13. The parser reproduction needs no GPU, no model file and no server. ### Model, size and settings Where it was seen end to end: Qwen3.8-Flash-Next GGUF IQ3_XXS and IQ3_S, 131072 context, behind llama-swap with `metadata.reasoning = {format: qwen3.8, levels: [low, medium, xhigh]}`, reasoning replayed (`preserve_thinking: true`, which is also the template's own default, `serve/chat_template.jinja:119`). The parser case needs none of that: `thinking=True` is enough. ### Logs Nothing is logged when the thinking ends early - the counters (`unread`, `rescued`, `refused`) all stay 0, and there is no `[strata]` line for it. ### Related issues - #537 (closed, "the quoted-closer form") fixed the quoted spelling; this is the bare spelling of the same tag and it is not covered. - #1058 (closed) is the mirror-image rule for openers quoted in prose (fences / inline code). - #2266 (closed) is about the literal control-token string stopping generation at the engine level, a different layer. ### Attached: repro.py (self-contained; the markup strings are built at runtime, never literal in the file) ~~~ #!/usr/bin/env python3 """Deterministic parser-level repro of three Strata `serve` defects seen through llama-swap + Pi. Run: python3 repro.py [--repo /path/to/Strata] [--old] (--old also runs case A against the parser as of 2026-10-20, i.e. before 70f42407.) This file never contains the markup tags literally: they are built from chr(60)/chr(62) at runtime. Keep it that way - a session whose context contains them verbatim can corrupt itself (see README.md, "Why this file is written like this"). """ import argparse import importlib.util import os import subprocess import sys T, G = chr(60), chr(62) THINK_OPEN, THINK_CLOSE = f"{T}think{G}", f"{T}/think{G}" CALL_OPEN, CALL_CLOSE = f"{T}tool_call{G}", f"{T}/tool_call{G}" PARAM_CLOSE, FUNC_CLOSE = f"{T}/parameter{G}", f"{T}/function{G}" def func(name): return f"{T}function={name}{G}" def param(name): return f"{T}parameter={name}{G}" # flat (Responses spelling): OutputParser.__init__ does {t.get("name"): t for t in tools} TOOLS = [ {"name": "bash", "parameters": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}}, {"name": "read", "parameters": {"type": "object", "properties": {"path": {"type": "string"}}}}, ] def load_parser(repo, old=False): """Return (label, OutputParser, needs_extra_kwargs) for the current or the pre-70f42407 parser.""" sys.path.insert(0, repo) if not old: from serve.frontend import OutputParser return "current HEAD", OutputParser src = subprocess.run(["git", "-C", repo, "show", "70f42407^:serve/frontend.py"], capture_output=True, text=True, check=True).stdout path = "/tmp/strata_frontend_pre_70f42407.py" open(path, "w").write(src) spec = importlib.util.spec_from_file_location("strata_frontend_old", path) mod = importlib.util.module_from_spec(spec) sys.modules["strata_frontend_old"] = mod # dataclass needs the module registered spec.loader.exec_module(mod) return "70f42407^ (2026-10-20)", mod.OutputParser def run(cls, text, tools=TOOLS, declared_only=True, recover=False, chunk=7): kw = {} try: # pre-70f42407 has no declared_only / recover p = cls(thinking=True, tools=tools, stream_tools=False, recover=recover, declared_only=declared_only) except TypeError: p = cls(thinking=True, tools=tools, stream_tools=False) evs = [] for i in range(0, len(text), chunk): # stream in small deltas, like a real server feed evs += p.feed(text[i:i + chunk]) evs += p.finish("stop") return evs, p def show(title, evs, p, expect, bug=False): """expect(calls, content_text, reasoning_text, parser) -> True when the case behaved as claimed. bug=True means the claimed behaviour is the defect, so True prints REPRODUCED.""" calls = [e.call for e in evs if e.kind == "tool_call"] text = "".join(e.text for e in evs if e.kind == "content") reasoning = "".join(e.text for e in evs if e.kind == "reasoning") ok = expect(calls, text, reasoning, p) if bug: verdict = "REPRODUCED" if ok else "*** DID NOT REPRODUCE ***" else: verdict = "as intended" if ok else "*** REGRESSION / CHANGED BEHAVIOUR ***" print(f"\n=== {title}\n {verdict}") print(f" reasoning: {reasoning[:70]!r}") print(f" content : {text[:160]!r}") print(f" calls : {[(c.name, c.arguments) for c in calls]}") print(f" unread : {getattr(p, 'unread', 'n/a (pre-70f42407)')} " f"{getattr(p, 'unread_names', '')} rescued={p.rescued} refused={p.refused}") def main(): ap = argparse.ArgumentParser() ap.add_argument("--repo", default=os.environ.get("STRATA", os.path.expanduser("~/pg/Strata"))) ap.add_argument("--old", action="store_true", help="also compare against the pre-70f42407 parser") a = ap.parse_args() label, cls = load_parser(a.repo) print(f"Strata repo: {a.repo} parser: {label}") # 0. sanity: a clean, well-formed, declared call parses clean = (f"{THINK_OPEN}\nLet me run it.\n{THINK_CLOSE}\n\n" f"{CALL_OPEN}\n{func('bash')}\n{param('command')}\nls\n{PARAM_CLOSE}\n{FUNC_CLOSE}\n{CALL_CLOSE}") evs, p = run(cls, clean) show("0. sanity - clean declared call (must parse as a call)", evs, p, lambda c, t, r, p: len(c) == 1 and c[0].name == "bash" and c[0].arguments == {"command": "ls"}) # 1. CONTROL: a think-close quoted with backticks inside the thinking stays reasoning text (#537) quoted = (f"{THINK_OPEN}\nI wrote `{THINK_CLOSE}` inside my reasoning\n" f"and kept thinking here\n{THINK_CLOSE}\n\nall done") evs, p = run(cls, quoted) show("1. control - quoted think-close in thinking (#537 protects this)", evs, p, lambda c, t, r, p: "kept thinking" in r and "kept thinking" not in t) # 2. DEFECT B: the same tag at line start ends the reasoning block; the rest leaks as content leak = (f"{THINK_OPEN}\nfirst part of the reasoning\n{THINK_CLOSE}\n" f"second part of the reasoning leaks into the answer\n{THINK_CLOSE}\n\nthe answer") evs, p = run(cls, leak) show("2. DEFECT B - bare think-close mid-thinking leaks the rest as visible content", evs, p, lambda c, t, r, p: "leaks into the answer" in t, bug=True) # 3. DEFECT A: a well-formed call for a tool the request did not declare comes back as text undeclared = (f"{THINK_OPEN}\nplan\n{THINK_CLOSE}\n\n{CALL_OPEN}\n{func('AskUserQuestion')}\n" f"{param('questions')}\n[]{PARAM_CLOSE}\n{FUNC_CLOSE}\n{CALL_CLOSE}") evs, p = run(cls, undeclared) show("3. DEFECT A - call for an undeclared name returns as text, loop cannot continue", evs, p, lambda c, t, r, p: not c and "AskUserQuestion" in t and p.unread == 1, bug=True) # 4. DEFECT C: literal call markup inside a parameter value truncates the call silently inner = (f"python3 - <<'EOF'\ntext = '''{CALL_OPEN}\n{func('read')}\n" f"{param('path')}\n/tmp/x\n{PARAM_CLOSE}") trunc = (f"{THINK_OPEN}\nplan\n{THINK_CLOSE}\n\n{CALL_OPEN}\n{func('bash')}\n{param('command')}\n" f"{inner}\n{PARAM_CLOSE}\n{FUNC_CLOSE}\n{CALL_CLOSE}\nok") evs, p = run(cls, trunc) show("4. DEFECT C - markup in an argument value truncates args silently (unread stays 0)", evs, p, lambda c, t, r, p: len(c) == 1 and "EOF" in str(c[0].arguments) and not str(c[0].arguments).endswith("EOF'\n") and p.unread == 0, bug=True) evs, p = run(cls, trunc, recover=True) show("4b. DEFECT C with tool_call_recovery=True (does NOT help)", evs, p, lambda c, t, r, p: len(c) == 1 and p.unread == 0, bug=True) # 5. Not a defect, but the answer to "is replayed thinking the cause?": think-tags in a replayed # assistant message ARE masked by mark_think_literals; tool-call literals deliberately are not. from serve.frontend import mark_think_literals, literal_tags def ctrl(name): # control tokens are never spelled literally either return chr(60) + chr(124) + name + chr(124) + chr(62) tags = literal_tags((ctrl("im_start"), ctrl("im_end"))) msgs = [{"role": "assistant", "content": "answer", "reasoning_content": f"I wrote\n{THINK_CLOSE}\nand also {CALL_OPEN} bare in my thinking"}] out, _, changed = mark_think_literals(msgs, None, tags) rc = out[0]["reasoning_content"] print("\n=== 5. input side: mark_think_literals on a replayed assistant message") print(f" changed: {changed}") print(f" think-close masked in reasoning_content : {THINK_CLOSE not in rc}") print(f" tool_call-open masked in assistant msg : {CALL_OPEN not in rc}" " <- False is intentional (frontend.py:366)") if a.old: olabel, ocls = load_parser(a.repo, old=True) evs, p = run(ocls, undeclared) show(f"6. DEFECT A on parser {olabel} - same input, different behaviour", evs, p, lambda c, t, r, p: len(c) == 1 and c[0].name == "AskUserQuestion", bug=True) if __name__ == "__main__": main() ~~~
Author
Owner

@github-actions[bot] commented on GitHub (Oct 25, 2026):

Thanks for the issue. To keep the tracker readable, every item needs an area prefix in the title and the parts of the issue form filled in. This one is missing:

  • Fill in "Area".
  • Fill in "Desktop app, Terminal or source?".
  • Fill in "Reproduction status".

Edit the issue (title and description) and this note goes away on its own. If it is still missing parts in 5 days it will be closed, which is not a rejection: fix it and comment /reopen.

Details: CONTRIBUTING.md

<!-- gh-comment-id:6396330924 --> @github-actions[bot] commented on GitHub (Oct 25, 2026): Thanks for the issue. To keep the tracker readable, every item needs an area prefix in the title and the parts of the issue form filled in. This one is missing: - [ ] Fill in "Area". - [ ] Fill in "Desktop app, Terminal or source?". - [ ] Fill in "Reproduction status". Edit the issue (title and description) and this note goes away on its own. If it is still missing parts in 5 days it will be closed, which is not a rejection: fix it and comment `/reopen`. Details: [CONTRIBUTING.md](https://github.com/Niko1221/Strata/blob/main/CONTRIBUTING.md)
Author
Owner

@Tsury commented on GitHub (Oct 25, 2026):

Reproduced on hardware, v0.2.6 build (engine 0.1.51; downstream patches do not touch reasoning parsing), RTX 5090 Laptop GPU, Qwen3.8 Flash-Next IQ3_S, thinking on at LOW effort.

The prompt asked for one write_file call whose content is reasoning sample:\n</think>\nanswer sample. While thinking, the model quoted that text, so a bare </think> line appeared in the reasoning. Reasoning ended there (127–163 characters). The rest of the reasoning, the model's real closing tag and its complete, correct <tool_call> block all arrived as assistant content, so the client got no tool call. Same result on Chat, Chat streaming and streaming Responses (3 of 3; finish stop / completed).

<!-- gh-comment-id:6401204286 --> @Tsury commented on GitHub (Oct 25, 2026): Reproduced on hardware, v0.2.6 build (engine 0.1.51; downstream patches do not touch reasoning parsing), RTX 5090 Laptop GPU, Qwen3.8 Flash-Next IQ3_S, thinking on at LOW effort. The prompt asked for one `write_file` call whose content is `reasoning sample:\n</think>\nanswer sample`. While thinking, the model quoted that text, so a bare `</think>` line appeared in the reasoning. Reasoning ended there (127–163 characters). The rest of the reasoning, the model's real closing tag and its complete, correct `<tool_call>` block all arrived as assistant content, so the client got no tool call. Same result on Chat, Chat streaming and streaming Responses (3 of 3; finish `stop` / `completed`).
Author
Owner

@github-actions[bot] commented on GitHub (Oct 28, 2026):

Thanks, this follows the format now.

<!-- gh-comment-id:6464211024 --> @github-actions[bot] commented on GitHub (Oct 28, 2026): Thanks, this follows the format now.
Author
Owner

@ackalker commented on GitHub (Oct 28, 2026):

Independent parser-level check on the current release, plus where a fix would have to go. My own runs only: no model, no GPU, no live server. Tags below are written as «think», «/think» and so on; the script in #4078's comment builds them at runtime from chr(60) / chr(62) and never contains them literally.

Revision and environment. main at 5e8a4cca (v0.2.7, engine 0.1.52), checkout with no local modifications. Linux (CachyOS, kernel 7.3.0-5), Python 3.14.8, 60 GB RAM.

Passed - the leak reproduces on released v0.2.7. Reasoning, a newline, a bare «/think» at the start of a line, more reasoning text: the reasoning events stop at the closer and everything after it arrives as content, the closer itself visible inside that content. Counters unread, rescued and refused stay 0 and no [strata] line is printed, exactly as the report says. The #537 control still behaves: a closer quoted after a backtick, followed by more text, stays in reasoning.

#4077 leak-as-content: REPRODUCES  reasoning='«think»\nfirst part of the reasoning\n' content='second part leaks into the answer\n«/think»\n\nthe answer' unread=0
#4077 control (quoted, must stay reasoning): ok

Passed - nothing has touched this path since the report. No commit in the repository mentions this issue, and serve/frontend.py changed in fa663fab..5e8a4cca only in fd8d37e9 (#3972 namespaced tool spellings), 11237f83 (#3395 tool-result order) and 805ebe17 (#3796 undeclared-name wording and the collapsed mcp__a__b alias). _quoted_think_end() and the state switch at the bare closer are unchanged.

Passed - PR #4132 does not fix this issue. I ran the same case against that branch (git fetch origin pull/4132/head, 831bb12b): the reasoning still ends at the bare closer and the rest still arrives as content. That matches the note in the PR's own Limits section.

Not run. No model and no GPU, so no end-to-end confirmation from me here; the hardware case is already in a comment above (RTX 5090 Laptop GPU, Qwen3.8 Flash-Next IQ3_S, 3 of 3 routes).

Two things that could shape a fix, both seen in the code rather than measured, so treat them as unconfirmed static analysis:

  • The decision is made once, at the first bare closer: after the parser has switched to content, a later closer in the same turn is emitted inside the answer rather than changing state. So a rule can look at what follows the closer without any lookahead budget across turns.
  • The input side already masks a literal closer inside replayed reasoning_content (mark_think_literals()), but not call markup inside an assistant message (serve/frontend.py around line 366, the #2026 note). A leak that carries an opener therefore comes back in the next request as a real opener, which is the self-feeding part of the report.
<!-- gh-comment-id:6464233530 --> @ackalker commented on GitHub (Oct 28, 2026): Independent parser-level check on the current release, plus where a fix would have to go. My own runs only: no model, no GPU, no live server. Tags below are written as `«think»`, `«/think»` and so on; the script in #4078's comment builds them at runtime from `chr(60)` / `chr(62)` and never contains them literally. **Revision and environment.** `main` at `5e8a4cca` (v0.2.7, engine 0.1.52), checkout with no local modifications. Linux (CachyOS, kernel 7.3.0-5), Python 3.14.8, 60 GB RAM. **Passed - the leak reproduces on released v0.2.7.** Reasoning, a newline, a bare `«/think»` at the start of a line, more reasoning text: the reasoning events stop at the closer and everything after it arrives as `content`, the closer itself visible inside that content. Counters `unread`, `rescued` and `refused` stay 0 and no `[strata]` line is printed, exactly as the report says. The `#537` control still behaves: a closer quoted after a backtick, followed by more text, stays in `reasoning`. ``` #4077 leak-as-content: REPRODUCES reasoning='«think»\nfirst part of the reasoning\n' content='second part leaks into the answer\n«/think»\n\nthe answer' unread=0 #4077 control (quoted, must stay reasoning): ok ``` **Passed - nothing has touched this path since the report.** No commit in the repository mentions this issue, and `serve/frontend.py` changed in `fa663fab..5e8a4cca` only in `fd8d37e9` (#3972 namespaced tool spellings), `11237f83` (#3395 tool-result order) and `805ebe17` (#3796 undeclared-name wording and the collapsed `mcp__a__b` alias). `_quoted_think_end()` and the state switch at the bare closer are unchanged. **Passed - PR #4132 does not fix this issue.** I ran the same case against that branch (`git fetch origin pull/4132/head`, `831bb12b`): the reasoning still ends at the bare closer and the rest still arrives as `content`. That matches the note in the PR's own **Limits** section. **Not run.** No model and no GPU, so no end-to-end confirmation from me here; the hardware case is already in a comment above (RTX 5090 Laptop GPU, Qwen3.8 Flash-Next IQ3_S, 3 of 3 routes). Two things that could shape a fix, both seen in the code rather than measured, so treat them as unconfirmed static analysis: - The decision is made once, at the first bare closer: after the parser has switched to `content`, a later closer in the same turn is emitted inside the answer rather than changing state. So a rule can look at what follows the closer without any lookahead budget across turns. - The input side already masks a literal closer inside replayed `reasoning_content` (`mark_think_literals()`), but not call markup inside an assistant message (`serve/frontend.py` around line 366, the #2026 note). A leak that carries an opener therefore comes back in the next request as a real opener, which is the self-feeding part of the report.
Author
Owner

@shi1090 commented on GitHub (Oct 29, 2026):

Another shape of the same leak: the quoted closer is inside inline code, not at the start of a line. A fix that only covers the line-start case would leave this one.

Environment. main at 46c152a1 (v0.2.7, engine 0.1.52), Linux source checkout, no local modifications. python serve/server.py --engine strata --config strata-iq3_s.json --port 8081 --parallel 1. Qwen3.8-Flash-Next IQ3_S on one RTX 4090, thinking on with thinking.budget_tokens 16384, Anthropic endpoint, OpenCode client.

Seen end to end. The turn's task was to investigate thought/output mixing. The reasoning contained the inline-code example (`<think>...</think>`). The stored message cuts the reasoning at that inner closer and streams the rest as content:

  • reasoning: …the streaming parse for reasoning (`<think>…
  • content: `), the DSML / dsml.py, split.py, … and later the real </think> as visible text.

The server log for the same turn shows the state change: thinking: 62 of budget 16384 then answering: 145 ….

Parser-only reproduction.

from serve.frontend import OutputParser

p = OutputParser(tools=[])
text = "The user asks about the parser (`<think>...</think>`), then the answer.\n</think>\nHere is the answer."
evs = p.feed(text) + p.finish()
print("reasoning:", repr("".join(e.text for e in evs if e.kind == "reasoning")))
print("content:  ", repr("".join(e.text for e in evs if e.kind == "content")))

Output:

reasoning: 'The user asks about the parser (`<think>...'
content:   '`), then the answer.\n</think>\nHere is the answer.'

_quoted_think_end() only checks the character immediately before the closer. Here that character is . (the ellipsis in <think>...), so the closer ends the thinking even though it is inside inline code. Counting the fence/inline-code state up to the closer (the parser already tracks fence, ticks and line for <tool_call>) would cover this and the fenced-code shape in #2794.

Not tested. Release binaries, other models, or non-Anthropic dialects. The parser reproduction is deterministic; the transcript and log are from one turn on the machine above. I can share the stored message JSON if that helps.

<!-- gh-comment-id:6490826177 --> @shi1090 commented on GitHub (Oct 29, 2026): Another shape of the same leak: the quoted closer is inside inline code, not at the start of a line. A fix that only covers the line-start case would leave this one. **Environment.** `main` at `46c152a1` (v0.2.7, engine 0.1.52), Linux source checkout, no local modifications. `python serve/server.py --engine strata --config strata-iq3_s.json --port 8081 --parallel 1`. Qwen3.8-Flash-Next IQ3_S on one RTX 4090, thinking on with `thinking.budget_tokens` 16384, Anthropic endpoint, OpenCode client. **Seen end to end.** The turn's task was to investigate thought/output mixing. The reasoning contained the inline-code example `` (`<think>...</think>`) ``. The stored message cuts the reasoning at that inner closer and streams the rest as content: - reasoning: `` …the streaming parse for reasoning (`<think>… `` - content: `` `), the DSML / dsml.py, split.py, … `` and later the real `</think>` as visible text. The server log for the same turn shows the state change: `thinking: 62 of budget 16384` then `answering: 145 …`. **Parser-only reproduction.** ```python from serve.frontend import OutputParser p = OutputParser(tools=[]) text = "The user asks about the parser (`<think>...</think>`), then the answer.\n</think>\nHere is the answer." evs = p.feed(text) + p.finish() print("reasoning:", repr("".join(e.text for e in evs if e.kind == "reasoning"))) print("content: ", repr("".join(e.text for e in evs if e.kind == "content"))) ``` Output: ``` reasoning: 'The user asks about the parser (`<think>...' content: '`), then the answer.\n</think>\nHere is the answer.' ``` `_quoted_think_end()` only checks the character immediately before the closer. Here that character is `.` (the ellipsis in `<think>...`), so the closer ends the thinking even though it is inside inline code. Counting the fence/inline-code state up to the closer (the parser already tracks `fence`, `ticks` and `line` for `<tool_call>`) would cover this and the fenced-code shape in #2794. **Not tested.** Release binaries, other models, or non-Anthropic dialects. The parser reproduction is deterministic; the transcript and log are from one turn on the machine above. I can share the stored message JSON if that helps.
Author
Owner

@Niko1221 commented on GitHub (Oct 29, 2026):

Partly fixed on our side; the fix ships in the next update (0.2.8). When the reasoning has ended at a closing think tag and another one stands at the start of a line later in the answer, the second is dropped as a stray and the answer's code tracking starts over, so a call after it is no longer mistaken for a quote by a fence the reasoning left open (that is how the call was lost).

Not fixed: the reasoning between the two tags has already been sent as answer text when the second tag shows up, and a stream cannot take it back. A client sees some reasoning as answer text, but no call is lost.

<!-- gh-comment-id:6492072055 --> @Niko1221 commented on GitHub (Oct 29, 2026): Partly fixed on our side; the fix ships in the next update (0.2.8). When the reasoning has ended at a closing think tag and another one stands at the start of a line later in the answer, the second is dropped as a stray and the answer's code tracking starts over, so a call after it is no longer mistaken for a quote by a fence the reasoning left open (that is how the call was lost). Not fixed: the reasoning between the two tags has already been sent as answer text when the second tag shows up, and a stream cannot take it back. A client sees some reasoning as answer text, but no call is lost.
Author
Owner

@ackalker commented on GitHub (Oct 29, 2026):

Thanks for looking into this.

<!-- gh-comment-id:6507593101 --> @ackalker commented on GitHub (Oct 29, 2026): Thanks for looking into this.
Author
Owner

@Niko1221 commented on GitHub (Nov 6, 2026):

0.2.11 fixes part of this: a stray closing think tag, damaged arguments and a missing </function> no longer cost the call. Reasoning text between the tags can still end thinking early, so I'm keeping this open for that part.

<!-- gh-comment-id:6694477216 --> @Niko1221 commented on GitHub (Nov 6, 2026): 0.2.11 fixes part of this: a stray closing think tag, damaged arguments and a missing `</function>` no longer cost the call. Reasoning text between the tags can still end thinking early, so I'm keeping this open for that part.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Niko1221/Strata#1771
No description provided.