MTPLX icon indicating copy to clipboard operation
MTPLX copied to clipboard

Tool calls for Qwen3.6 are emitted as malformed / unterminated JSON (blocks writing source files)

Open jeffwood-lab opened this issue 4 months ago • 7 comments

mtplx doctor --json

Environment

MTPLX version: 2.3.0 Model: Qwen3.6-27B-MTPLX-Optimized-Speed-FP16 (also seen on Qwen3.6-35B-A3B-...) Launch command / flags: <fill in — e.g. --reasoning-parser, --tool-prompt-mode, --chat-template-profile> Bridge: OpenAI-compatible /v1 (also reproduced on Anthropic /v1/messages) Client: opencode via @ai-sdk/openai-compatible

Summary When the model calls a tool whose arguments contain a large or heavily-escaped string (e.g. a write with file content full of " { } < > \n), MTPLX emits the tool call as invalid or unterminated JSON, or leaks it into the assistant text channel instead of a structured tool_call. Small prose writes succeed; code/markup writes fail — pointing at JSON string-escaping of the arguments.

Observed behavior

Hard error on a write of an HTML/CSS file:

error: { "name": "UnknownError", "data": { "message": "malformed tool_call: unterminated stream" } }

Earlier instance — a bash tool call with a broken escape (timeout":), never validly closed, spilling into free text:

{"name": "bash", "arguments": {"command": "cat design/spec.md", "tool": "bash", "timeout": 10000}Let me get the full spec content via bash. ...

That response then ran to finish: "length" with output: 32000 tokens (a runaway, downstream of the broken tool call).

Expected behavior Tool calls should always be emitted as complete, well-formed, properly-escaped JSON in the structured tool_calls field — or fail cleanly — regardless of payload size or special-character density.

Impact Blocks the core operation of any coding agent: the model cannot reliably write source files (which are escaping-heavy by nature). Prose writes work; code writes do not.

Repro Ask the model to write a ~150+ line file containing HTML/CSS/JS (quotes, braces, angle brackets, newlines) in a single tool call.

Questions / things tried

Does MTPLX_TOOL_CALL_STRICT=1 enforce valid/terminated tool-call JSON? Does --tool-prompt-mode native vs hybrid change the escaping behavior? Is there a max tool-call argument length or streaming buffer limit being hit?

Exact command

<fill in — e.g. --reasoning-parser, --tool-prompt-mode, --chat-template-profile>

Model path or repo id

Qwen3.6-27B-MTPLX-Optimized-Speed-FP16

Chip, RAM, macOS version

M2 MAX 32GB, Tahoe

jeffwood-lab avatar Jul 22 '26 22:07 jeffwood-lab

Bounding datapoint from the #170 verification setup that may narrow this: on 2.3.0 (Qwen3.6-27B-MTPLX-Optimized-Speed, local_qwen36 template, serial scheduler, temp-0, 48 tool-call turns including edit_file calls with structured array args): json_valid 100%, non-truncated 100%, zero malformed emissions. Our payloads were small-to-moderate code snippets, though — nothing like a full HTML/CSS file body with heavy " { } < > \n density.

Taken together with your report, that brackets the failure: structured tool-call emission is clean at small/moderate argument sizes and breaks on large/heavily-escaped string payloads — consistent with your read that it's the JSON string-escaping path for argument content (or a buffer/streaming boundary that only large payloads cross), not the general tool-call serialization 2.3.0 fixed. The "leaks into the assistant text channel" variant is a useful second symptom: that's what a parser does when it gives up mid-capture, which suggests the escaping failure and the channel leak share one code path. Same offer as on #197 — targeted repro on an M5 Max with the standing harness (a write-style tool driven with progressively larger escaped payloads to find the size/content threshold) if that would help bisect.

PhilipJohnBasile avatar Jul 23 '26 19:07 PhilipJohnBasile

Follow-up with a minimal, client-free repro on 2.3.0 that narrows this substantially — and partially clears the string-escaping theory.

Setup: Youssofal/Qwen3.6-35B-A3B-MTPLX-Optimized-Speed (one of the models this issue names), mtplx 2.3.0, default serve flags, plain non-streaming /v1/chat/completions via stdlib HTTP — no opencode, no ai-sdk — temperature: 0, two tools (write_file, edit_file with edits: [{search, replace}]).

1. Large heavily-escaped payloads are clean when non-streaming: 6/6. A ~60-line HTML+CSS write_file (dense " { } < > \n) serialized as valid JSON six out of six runs at a 4000-token budget. (At a 1200-token budget it starved with finish: length and the partial call was silently swallowed — worth knowing, but that's budget, not escaping.) So in the non-streaming path, argument-content escaping alone doesn't reproduce it — if your failures are streaming-relay-side, that's now the prime suspect for the escaping variant.

2. The reproducible failure is the multi-edit array call, and it's nondeterministic at temp 0. One prompt asking for three edit_file search/replace edits, nine identical requests:

  • 5× valid tool call (finish: tool_calls)
  • 3× completely empty response — no tool call, no content, clean finish: stop
  • 1× your text-channel leak, verbatim symptom: the content channel fills with the model's reasoning narration ("The user wants to make three specific edits... I need to use the edit_file tool...") until finish: length, with no tool call ever emitted.

Two reads from that: the leak content being reasoning prose (not a half-serialized tool call) points at the reasoning-parser/tool-capture interaction rather than JSON escaping — when the model takes a narrate-first path, capture misses entirely (silent-empty) or the narration escapes to content (leak). And identical byte-for-byte requests taking different paths at temp 0 means something upstream of sampling is nondeterministic (speculative accept/reject timing, scheduler state, or cache reuse) — which is why the bug presents as intermittent in agent loops.

Corroborating rate from a 24-turn deterministic suite on the same rig/model: 2/24 turns arrived with empty raw arguments; zero {} empty-object events (the #170 fix holds).

Repro script (three cases × N reps, full raw capture) and both runs' JSON available if useful — happy to rerun cells against a branch.

PhilipJohnBasile avatar Jul 23 '26 19:07 PhilipJohnBasile

Filling the gap @PhilipJohnBasile named in the first comment ("nothing like a full HTML"): same 2.3.0 setup, but STREAMING and with a payload big enough to span many chunks.

Conditions: Youssofal/Qwen3.6-27B-MTPLX-Optimized-Speed (4-bit), --chat-template-profile local_qwen36, --tool-prompt-mode hybrid, serial scheduler, --ssd-session-cache off, temp 0, streaming /v1/chat/completions, ephemeral server on a free port, M5 Max 128 GB, 3 reps. The cell demands one write_file with a complete 60+ line HTML page (style block with nested braces and quoted font stacks, script block with quoted keys and escaped quotes), then 4 edit_file replacements each a multi-line block.

Result: 3/3 clean, argument payloads 5478 / 6479 / 7068 chars, json_valid 100%, non-truncated 100%, zero malformed emissions. So multi-kilobyte escaped arguments serialize correctly over streaming on this quant, which pairs with the 6/6 non-streaming result above.

One mechanism worth ruling out on the reporter's side, because it bit us first: with a 1024 max_tokens budget the SAME cell fails 0/3, and it fails exactly like this issue describes. The model runs out mid-argument, finish_reason comes back length, and what lands in the transcript is either unterminated JSON or the file content sitting in the assistant text channel with no tool call at all. Our first pass measured 81.8% json_valid on that basis, and every single failure disappeared at 4096. If opencode (or the ai-sdk layer) caps completion tokens, a large write is the first thing that would break, and the symptom is indistinguishable from a serializer bug from the client's side.

Cheap check: log finish_reason on the failing calls. length points at the budget, stop points at the engine.

Measured with asiai (open-source bench tool, I build it); the large-payload cell is in the tool-call stress suite, streaming by default.

druide67 avatar Jul 28 '26 22:07 druide67

update: two of the three layers ship in 2.4.0. the server no longer reports finish_reason=tool_calls on length-cut turns (clients see length and continue per protocol), and the think-splitter no longer leaks reasoning into content on bare "function="/"parameter=" strings. the remaining layer is a rare engine-side early stop mid-reasoning, agent-context-only (0 empties in 90 single-turn probes across MTP/AR/template cells), and we're adding request-capture so a failing agent turn can be replayed bit-exact. philip: yes to the standing harness offer, your 9-run grid cracked the first two layers.

youssofal avatar Jul 31 '26 11:07 youssofal

Thanks — that split matches the evidence from the 9-run grid. I’ll keep that grid as the regression harness for the two 2.4.0 fixes and treat the rare engine-side early stop as a separate unresolved layer.

When request-capture/replay lands, I can add a fail-closed replay cell that records the exact request payload, template/rendered prompt, route/mode, sampler, seed, finish reason, emitted token IDs, and stream chunks, then replays the failing agent turn against AR and MTP. That should distinguish an engine stop from client/parser loss without trying to infer it from an empty response.

No new claim from me until there is an actual captured failing turn and a bit-exact replay receipt.

PhilipJohnBasile avatar Jul 31 '26 12:07 PhilipJohnBasile

2.4.2 is live (pip / brew / DMG) and carries the diagnosis kit for the remaining layer:

  • the request log is now on by default: ~/.mtplx/logs/request-log-<port>.jsonl — per-request timings, token counts, prefill/restore behavior, finish reasons, request ids; no prompt/completion content; MTPLX_REQUEST_LOG_JSONL=off disables.
  • the replay half shipped in 2.4.1 and pairs with it: set MTPLX_REQUEST_CAPTURE_DIR=<dir> and every request persists a bit-exact reproduction envelope at dispatch time.

@PhilipJohnBasile — your fail-closed replay cell is exactly the shape we want. run the 9-request grid with capture on; any empty/leak turn hands us the exact artifact to replay against AR and MTP, which finally separates an engine stop from parser loss. notes: https://mtplx.com/releases/notes/v2.4.2

youssofal avatar Aug 02 '26 08:08 youssofal

Closing this together with #197: current builds run this clean. Receipt from today's check on an internal build (Qwen3.6-35B, native settings temp 0.6 / top-p 0.95 / top-k 20): a 3-round tool loop (read, then read with offset/limit, then write) returned valid, terminated JSON arguments every round with no unterminated objects or malformed frames, and a separate 4-trial streaming/non-streaming run produced well-formed tool_calls in every trial. The 2.5.x line shipped several rounds of tool-call hardening since this was filed (bracket-tool rescue, dialect stamps, the native tool prompt).

One related open defect remains: #249, argument values duplicated into delta.content when streaming with tool history. If what you saw matches that symptom, follow there. If the original corruption comes back on 2.5.4 or later, reopen with the transcript and we'll treat it as a regression.

youssofal avatar Aug 11 '26 01:08 youssofal