Skip to content

fix(provider): decode Gemma tool-call arguments before chat-template rendering (#249) - #250

Merged
Gajesh2007 merged 3 commits into
masterfrom
fix/gemma-toolcall-double-brace
May 29, 2026
Merged

Gajesh2007 merged 3 commits into
masterfrom
fix/gemma-toolcall-double-brace

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented May 29, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes #249 — multi-turn tool calling with Gemma (gemma-4-26b) corrupts
function.arguments after the first turn for every OpenAI-shaped tool-calling
SDK (Claude Code, Codex, AI SDK, OpenAI SDK, …).

OpenAI delivers function.arguments as a JSON string. When the provider
renders a prior assistant tool_calls message into the prompt, that string is
forwarded verbatim into the model's downloaded chat_template.jinja, which
takes the is string branch and dumps it inside its own { … } block →
double brace:

<|tool_call>call:run_terminal{{"command":"ls -la"}}<tool_call|>

The model imitates that double-brace example on the next turn, and the Gemma
output parser then splits the inner object at its first colon, corrupting the
arguments ({"command":"ls -la"} → {"{\"command\"":"\"ls -la\"}"}) and
compounding turn over turn.

Confirmed against the exact template the fleet runs: the prod runtime manifest
pins the gemma4 chat template to hash 2dfbfc7d…, which matches the downloaded
gemma-4-26b-a4b-it-8bit chat_template.jinja (lines 200-203 = the buggy
is string branch). Note the bug is template-family-wide (the 4bit template has
the same branch) — the root cause is ours, not the quant.

Fix

Decode the JSON-string arguments into an object at the translation boundary so
the template takes the is mapping branch (command:<|"|>ls -la<|"|>). The
OpenAI wire contract is unchanged — arguments stays a String to/from
clients; only the template-input shape is normalized. Non-JSON / non-object
arguments fall back to the raw string. The chat template and the output parser
are intentionally left untouched.

Tests

provider-swift/Tests/ProviderCoreTests/ToolCallTemplateArgumentsTests.swift:
asserts templateMessageDict() yields a mapping (double-brace regression guard)
and keeps non-JSON args as a string. swift test green locally; verified with a
negative control (reverting the one-line change makes the test fail with the raw
{"command":"ls -la"} string).

Merge order ⚠️

  1. Merge fix(server): decode OpenAI tool-call arguments before chat-template rendering mlx-swift-lm#33 first.
  2. Then re-point the libs/mlx-swift-lm gitlink here to the merged main SHA
    (this PR currently pins the PR-33 branch commit 2ebc20f so CI can build).
    If Security: Free inference via streaming — billing happens after response delivery #33 is squash-merged, update the submodule pointer before merging this PR.

View with Codesmith Autofix with Codesmith
Need help on this PR? Tag @codesmith with what you need. Autofix is disabled.

…rendering

Fixes #249.

Multi-turn tool calling with Gemma (gemma-4-26b) corrupted function.arguments
after the first turn. Rendering a prior assistant `tool_calls` message fed the
JSON-string `arguments` into the model's downloaded chat_template.jinja, which
took the `is string` branch and emitted a double brace
(`call:run_terminal{{"command":"ls -la"}}`). The model imitated that shape on
the next turn and the Gemma output parser shredded it, corrupting arguments and
compounding turn over turn. Affects every OpenAI-shaped tool-calling SDK.

Provider fix: `templateMessageDict()` — the live chat path that feeds
`applyChatTemplate` — now decodes the JSON-string arguments into an object via
`MLXLMCommon.decodeToolCallArguments`, so the template takes the `is mapping`
branch (`command:<|"|>ls -la<|"|>`). The OpenAI wire contract is unchanged;
non-JSON / non-object arguments fall back to the raw string. The chat template
and the output parser are left untouched.

Bumps the mlx-swift-lm submodule to include the shared `decodeToolCallArguments`
helper and the MLXLMServer mirror fix (Layr-Labs/mlx-swift-lm#33).

Tests: ProviderCoreTests/ToolCallTemplateArgumentsTests asserts
templateMessageDict() yields a mapping (double-brace regression guard) and keeps
non-JSON args as a string. Verified with a negative control (revert -> test
fails with the raw string).
@vercel

vercel Bot commented May 29, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview May 29, 2026 11:15pm
d-inference-console-ui-dev Ready Ready Preview May 29, 2026 11:15pm
d-inference-landing Ready Ready Preview May 29, 2026 11:15pm

Request Review

@github-actions

github-actions Bot commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

This change is security-neutral with respect to the threat model, but introduces a small new attack surface worth noting.


Trust Boundaries Touched

  • TB-002 (Coordinator → Provider WebSocket) — the translation layer sits in the inference path between incoming inference requests and the MLX engine.
  • TB-007 (Provider Inference Engine) — prompt/tool-call data flows through this code before and after decryption.

Threat Assessment

Threat Assessment Notes
T-007 (Provider serves manipulated model outputs) ℹ️ Neutral This change affects how tool call arguments are serialized into the chat template. It does not touch weight hash computation, registry admission, or output signing. No change to tamper-detection posture.

New Attack Surface Not Covered by an Existing Threat

decodeToolCallArguments() — untrusted input deserialization in the inference path

The function decodeToolCallArguments is called at MultiModelBatchSchedulerEngine+Translation.swift line 93 on call.function.arguments, which is a string value sourced from a consumer-controlled inference request. This is not covered by any existing threat pattern.

Two concerns:

  1. Malformed / adversarial JSON in tool call arguments. The diff comment says the intent is to decode the string to an object so the chat template renders correctly. If decodeToolCallArguments uses JSONSerialization or a similar deserializer without a depth/size limit, a deeply nested or very large arguments string could cause excessive memory allocation or stack overflow in the provider process. The consumer (ADV-002) controls this string and can craft pathological inputs. Verify that decodeToolCallArguments bounds the input size and nesting depth, or that a size cap is enforced upstream before this call site.

  2. Decode failure / type confusion leaking into the chat template. If decoding fails and the function returns a fallback (e.g. the raw string, nil, or an empty dict), the chat template may render a malformed tool call that silently truncates or corrupts model context. This is not a direct security issue but could create inconsistent inference outputs in ways that are hard to attribute (adjacent to T-007's output-integrity concern).

The function definition is not included in the diff — it presumably lives in libs/mlx-swift-lm (one of the three files not shown). That file should be reviewed to confirm:

  • Input is validated/capped before deserialization.
  • Decode failure is handled deterministically and does not fall back to an unsafe representation.

Open Findings Resolved

None. This PR does not resolve any existing SEC-* findings.


🔐 Threat model: docs/threat-model.yaml · Updates on each push to this PR

Adds a gated end-to-end test against the real
`mlx-community/gemma-4-26b-a4b-it-8bit` model and its real downloaded
`chat_template.jinja` (rendered by swift-jinja):

- Prompt A/B: rendering a prior assistant tool_call through the real template
  produces a single brace via the fixed translation
  (`call:run_terminal{command:<|"|>ls -la<|"|>}`) but a corrupting double brace
  when arguments are forwarded as the raw JSON string
  (`call:run_terminal{{"command":"ls -la"}}`).
- Generation: with the fixed multi-turn history, the real model emits and the
  server parses a clean `run_terminal(command: "cat hello.txt")` — no
  double-brace, no split-at-colon key corruption.

Gated by DARKBLOOM_LIVE_MLX_TESTS=1 + DARKBLOOM_LIVE_MLX_GEMMA=1 (and a
metallib via MLX_METALLIB_SOURCE/.build); skipped in normal CI.

Refs #249.

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference-console-ui-dev — b8eaf281 Deployed May 29, 2026 by vercel[bot]
Preview – d-inference — b8eaf281 Deployed May 29, 2026 by vercel[bot]
Preview – d-inference-landing — b8eaf281 Deployed May 29, 2026 by vercel[bot]
benchmarks — b8eaf281 Deployed May 29, 2026 by Gajesh2007 via E2E Benchmarks #504
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.

Multi-turn tool calling corrupts Gemma function.arguments (double-brace) — provider passes arguments as a JSON string into the chat template

1 participant