Skip to content

Constrain Gemma 4 tool-call argument keys and report malformed calls (#3268) - #3463

Merged
malibio merged 3 commits into
mainfrom
issue-3268-gemma-tool-call-args
Oct 1, 2026
Merged

malibio merged 3 commits into
mainfrom
issue-3268-gemma-tool-call-args

Conversation

@malibio

@malibio malibio commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator

Part of #3268. Acceptance criteria 1, 2 and 4 are met. Criterion 3 is partly met and criterion 5 has a scenario but no score yet (see "Not fixed"), so the issue stays open.

What went wrong

"What schemas do we have here?" on gemma-4-E4B failed three ways in one turn:

  1. Mangled arguments. llama.cpp's Gemma 4 tool-call grammar is schema-blind, and its rule for an argument key is [^:}]+ — any text up to the next colon. A kwargs-style call (query="",node_type="schema",limit=50,sorting=[{…) satisfies it and reaches the tool as one JSON key.
  2. Prose inside the arguments. A string argument runs until the model's <|"|> token. Closed with a plain ", it never ends, and swallows the call's close marker and the answer the model writes next.
  3. Only custom types listed. The model answered from the EXISTING SCHEMAS context block, which holds only custom types, without calling a tool.

Changes

nlp-engine

  • constrain_gemma4_argument_keys rewrites the grammar's key rule so a key can only be a name. A warning is logged if llama.cpp's rule is not in the expected shape, and llama-cpp-2 is pinned to =0.1.146 so the rule cannot change under a cargo update.
  • ends_gemma4_tool_call stops generation at <tool_call|> (a turn makes one call).

agent

  • Arguments that parse as JSON but are not an object of named parameters are not dispatched. They are reported to the model as a malformed call and count toward the same two-in-a-row breaker as arguments that do not parse (MAX_CONSECUTIVE_MALFORMED_CALLS, renamed).
  • The reply that replaces an unacknowledged tool failure now says which action failed and why, e.g. "I couldn't run the node search: the tool call was malformed." For a tool's own error it quotes the first sentence only.
  • search_nodes' description says node_type='schema' lists every type and that EXISTING SCHEMAS is not that list. One line changes in stage2_tool_surface.golden.
  • search_nodes results reported every node's type as empty (nodeType is the wire spelling) and a schema node's title as empty (its name is its content). Both are filled in now.
  • The fabricated-id guard read **nodespace://ordered-list** with its closing asterisks, so a correct schema list was replaced by "Could you confirm…". Found while measuring; fixed here.

eval

  • decisions gains outcome-list-types: the reply must name built-in and custom types off a successful search_nodes.

Measured on gemma-4-e4b-q4km

Before After
Retry after a prior call with over-quoted keys (8 trials) 8 malformed 0 malformed
Retry after the reported kwargs call (4 trials) argument ran on to the 512-token cap stops at the close marker
"What schemas do we have here?" calls search_nodes with node_type='schema' 0 of 3 (answered from context) 3 of 3, on each of two test databases

Not fixed

  • The reply does not reliably name every built-in type. The search now returns all of them, but on current main (after the linked-reference format landed) the model enumerates the full list on one test database (3 of 3) and writes "…and several built-in types like text, task, date, etc." on another (1 of 1). Those readings were taken with a description clause ("the answer names each one it returned") that review removed as unmeasured reply policy; they have not been re-taken without it, because another eval run has the GPU. Adding a "this is the complete list" note and a built-in flag to the result made it worse (it mislinked ids), so that was dropped. The new eval scenario scores exactly this and fails on the summarising reply.
  • The new scenario has no eval reading yet. In one rep of eval:decisions its group was excluded, along with three others, because the setup-venue turn declined to re-create a type that already existed. Of the 8 scenarios that were scored, 6 passed; skill-instance-request and declarative-fact-report-resolved failed. There is no baseline rep on main to compare against.
  • The original kwargs call did not recur live in six tries. It is pinned by replaying the reported arguments as the prior turn, and by unit tests on the exact payload.
  • "What types do we have?" still draws one Stage-1 clarifying question; answering it runs the search. Stage-1 routing prose is untouched.
  • "Do we have a schema for people?" ended with an empty model reply after a successful search in 4 of 12 runs across builds, which shows as "• node search completed". Whether this predates the change is not established.
  • Argument values are still unconstrained by the grammar; only keys are narrowed.
  • A user-defined field whose name contains a space or other excluded character can no longer be written through a native tool call by that name.

Tests

  • Unit: the grammar rewrite against the captured grammar and the reported keys; the malformed-argument classifier, loop dispatch and breaker; the failure message; the id guard; the search result row; the eval scorer.
  • The new loop tests fail with the classifier disabled (6 failures), and the over-quoted live test fails with the grammar rewrite disabled (8 of 8).
  • Live (--run-ignored only, needs the E4B GGUF): toolcall_json_shape, 4 of 4 pass. a_retry_cannot_copy_over_quoted_keys_from_the_prior_call replaces retry_copies_the_shape_of_the_prior_call, whose measured outcome this change flips.
  • bun run test:changed and quality:fix on the branch merged with current main.

🤖 Generated with Claude Code

@malibio

malibio commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #3463 (issue #3268)

Review Type: Initial Review (no prior reviews or comments on the PR)

Scope read: git diff origin/main...HEAD (7 files, +1361/−122), the PR description, issue #3268, ADR-064, ADR-056, and llama.cpp's Gemma 4 grammar source in the vendored llama-cpp-sys-2-0.1.146 (common/chat.cpp:1141-1184). Ran the 23 new/affected nodespace-agent lib tests: all pass. No live-model tests or evals were run.

Summary

The change is a net improvement and nothing in it blocks a merge. The grammar rewrite targets the real cause: llama.cpp's rule is p.chars("[^:}]", 1, -1), exactly as the PR says. The narrowed class is valid GBNF. I found no legitimate tool call that is now refused or truncated: every declared parameter name passes the top-level check (pinned by a test over the registry), and search_nodes filters use named operators (lt, gte), not symbol keys. The PR's "Not fixed" list matches the code.

The findings below are five improvements and a few optional ones.

Requirements Check

# Criterion Status Notes
1 Reproduce the arg capture; fix parsing or constrain the grammar; parser test with the exact output ✅ Met through the "constrain the grammar" branch. The exact reported payload is pinned in chat/mod.rs (key class) and agent_loop.rs (classifier and loop). The original call did not recur live (stated in the PR), and the test checks the character class, not llama.cpp's parser. Argument values stay unconstrained (stated).
2 Prose as arguments is detected as malformed, re-prompted, not dispatched ✅ Covered for prose as a key and prose as the whole value. Prose inside a correctly named string parameter ({"query":"I found…"}) is still dispatched; that is not detectable in general.
3 "What schemas/types do we have?" returns every schema partial The steering works (measured 3 of 3 call search_nodes node_type='schema') and the result rows now carry a title. The reply does not reliably name every built-in type, and "What types do we have?" still draws a Stage-1 clarifying question. Both are stated in the PR.
4 Safety-net message says what failed in plain terms ✅ describe_unsurfaced_failures, pinned by exact-string tests.
5 eval:decisions (or a golden) covering "what schemas do we have" partial The outcome-list-types scenario and its scorer tests exist. The scenario has never produced a score: its group was excluded in the one rep, and the PR expects it to fail on the summarising reply.

Code Review Findings

No 🔴 Critical findings.

🟡 Important

1. The engine-side behaviour is pinned only by #[ignore] tests, and the dependency it relies on is not pinned

📁 packages/nlp-engine/src/chat/mod.rs:733-738, 1271-1281; packages/nlp-engine/Cargo.toml:17

let constrained = constrain_gemma4_argument_keys(grammar_str);
if constrained.is_none() && tmpl_result.chat_format == CHAT_FORMAT_PEG_GEMMA4 {
    tracing::warn!( ... "argument keys are not constrained" ...
llama-cpp-2 = { version = ">=0.1.146", optional = true }

The rewrite matches one exact line of llama.cpp-generated text. Deleting the break at line 735, or the constrain_… call at line 1271, leaves every test the merge gate runs green; only the live tests in toolcall_json_shape.rs would notice. ADR-056 says the binding "stays pinned at 0.1.146", but the requirement is >=0.1.146, so only Cargo.lock holds it. A cargo update that reshapes the rule would silently return keys to [^:}]+, with a log warning as the only signal.

Recommendation: change the requirement to =0.1.146 (both entries, lines 17 and 69) so the lock and the ADR agree, and add the two live tests to whatever checklist accompanies a binding bump. Principle: a fix that depends on a third party's generated text needs a failing signal, not a log line.

2. search_result_summary keeps two lookups that cannot match

📁 packages/agent/src/local_agent/tools.rs:621-627

let node_type = ["nodeType", "node_type", "type"]
    .iter()
    .find_map(|key| node.get(*key).and_then(|v| v.as_str()))

Every node wire struct in nodespace-types is rename_all = "camelCase", so nodeType is the only spelling node_to_typed_value produces. The comment itself says the node_type lookup "reported every node's type as empty". node_type and type are the two spellings that caused the bug, kept as fallbacks. Recommendation: read nodeType only. Principle: YAGNI, and the project rule against alternate-shape code.

3. The reply-shaping clause in the search_nodes description sits in the wrong channel and is not backed by a measurement

📁 packages/agent/src/local_agent/tools.rs:656-658 (and the golden)

it returns every type, built-in and custom, and the answer names each one it returned.

ADR-064 rule 2 gives tool descriptions tool selection. "Call this with node_type='schema'" and "EXISTING SCHEMAS is not that list" are selection guidance, and the 0 of 3 → 3 of 3 measurement supports them. "The answer names each one it returned" is reply policy. The PR's own data says the reply still summarises on one database, so this clause has no measured effect. ADR-064 says content returns "only when a specific measurement demands it, one rule at a time". Recommendation: drop the clause, or keep it only with an A/B reading that shows it changes the reply.

4. A call refused as malformed is still replayed verbatim into the next prompt

📁 packages/agent/src/local_agent/agent_loop.rs:526-531, 3384; packages/nlp-engine/src/chat/mod.rs:1062-1066

/// The offending text is deliberately not quoted back:
/// the model copies the shape of what it reads in its own history.

The tool result does not quote it, but the assistant turn pushed at line 3384 carries tc.arguments_json as emitted, and chat_message_to_oai_value replays any arguments that parse as an object. So the kwargs-shaped key reaches the next prompt anyway. Unparseable and non-object arguments are replayed as {}, so the three malformed kinds are treated differently. The live test's own doc comment records the effect: the retry "closes a string with the " it read in the history".

On the native path the grammar now makes the kwargs first call unreachable, so this mostly affects the OpenAI-compatible engine. Recommendation: when a call is classified as malformed, record its arguments in history as {}, the same as the other two kinds, and measure the retry with the existing live test. If that is out of scope, reword the comment so it does not claim more than the code does.

5. The new scenario's score has never been observed

📁 scripts/eval/fixtures/decisions.ts:387-404

The scorer is well tested, but criterion 5 asks for coverage on the default local model, and the one rep excluded the scenario's group. A scenario expected to fail from its first run reports nothing useful when it does. Recommendation: get one reading where the group runs before merging, or record in the issue that the criterion is open. If the expected result is a failure, say so where the fixture's other known-failing scenarios are tracked.

🟢 Suggestions

6. malformed_message is carried beside tool_result instead of in it

📁 packages/agent/src/local_agent/agent_loop.rs:3536-3538, 3745-3760

None => (
    malformed_call_result(malformed_message.unwrap_or_default()),
    true,
),

tool_result == None and malformed_message == Some(..) are always set together, and unwrap_or_default() supplies an empty message for a state that cannot occur. Building the result in the Err(message) arm (Some(Ok(ToolResult { result: malformed_call_result(message), is_error: true, .. }))) removes the mutable sibling and the None arm.

7. The clarify pre-scan can now disagree with the per-call loop

📁 packages/agent/src/local_agent/agent_loop.rs:3446-3453

The comment says the pre-scan "cannot disagree with what that loop decides for the same call". A route_clarify call with a valid question and options plus one extra key that is not a name passes the pre-scan (serde ignores unknown fields) and is then recorded as malformed by the loop, while the turn still ends with the clarification. The outcome is harmless. Either run unusable_arguments in the pre-scan as well or soften the comment.

8. ends_gemma4_tool_call fires on the marker in any position

📁 packages/nlp-engine/src/chat/mod.rs:735, 976-978

A reply that samples the <tool_call|> token with no call open (a model describing its own format) is cut off there. Adding !tool_call_ids.is_empty() to the condition limits the stop to a turn that has started a call, and still covers the unterminated-string case.

9. Record the NodeSpace-side grammar rewrite in nodespace-docs

ADR-056 names "a NodeSpace-side mitigation" for Gemma 4's argument grammar as a re-introduction path for 12B. This PR is the first such mitigation and brings a constraint (a field name with a space or other excluded character is not writable through a native tool call). That belongs in the docs repo, not only in a doc comment.

Nitpicks

  • Nit: agent_loop.rs:1788, 5713 — a truncated tool error ends with an ellipsis followed by a full stop, and the test pins it. Skip the trailing full stop when truncated.
  • Nit: scripts/eval/fixtures/decisions.ts:705 — "listsTypes" in expected discriminates two variants that share decision: "outcome". A distinct tag would let the compiler check a third outcome kind.
  • Nit: several new comments narrate what the code did before rather than what it does: tools.rs:621-623 ("reported every node's type as empty"), decisions.ts:395-397 ("Measured … before search_nodes said…"), agent_loop.rs test docs ("used to be dispatched"), toolcall_json_shape.rs:447-452 ("It now stops"). The measurements are worth keeping; state them as the reason for the present behaviour.
  • Nit: tools.rs:615-619 — the title falls back to content for every node type, so an untitled non-schema node repeats its first 100 characters in title and snippet. The comment only justifies schema nodes.

Checked and found sound

  • GBNF validity of [^:}={\[\]<>(),"' \t\r\n]+: llama.cpp's grammar parser accepts \[, \], \t, \r, \n escapes in a class, and an unescaped " inside one.
  • KV cache on the new break: it exits before batch.add/decode, the same as the EOG break, and cached_prompt already holds only the prompt.
  • No false "keys are not constrained" warning: the template request sets json_schema: None, grammar: None, so a Gemma 4 grammar exists only on a tool turn.
  • {"error": "<code>", "message": …} follows the existing DUPLICATE_ENTITY_ERROR pattern, and nothing else reads result["error"] as prose.
  • The schema wire type has no nodeType or title, as the new comments say.
  • No issue numbers in comments, no lint suppression, no #[allow(dead_code)], no compatibility shims beyond finding 2; scripts/ tests stay DOM-free.

Recommendation

APPROVE — findings 1 to 5 are worth addressing; none blocks the merge.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

@malibio malibio changed the title Constrain Gemma 4 tool-call argument keys and report malformed calls (closes #3268) Constrain Gemma 4 tool-call argument keys and report malformed calls (#3268) Oct 1, 2026
@malibio

malibio commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed (commit cb1e940)

Addressed

# Finding What changed
1 Dependency not pinned llama-cpp-2 is =0.1.146 on both lines, with a comment naming the live tests a bump must re-run. Cargo.lock is unchanged.
2 Dead node_type / type lookups search_result_summary reads nodeType only.
3 Reply-policy clause in the tool description Dropped. Only the selection guidance stays, which is what the 0 of 3 → 3 of 3 reading supports.
4 Malformed call replayed verbatim Comment reworded; behaviour kept. Replaying the call as {} was measured on E4B with two wordings: in 4 of 4 trials each the model apologised and asked the user what they meant, where the verbatim call drew a retry. The comment now records that.
6 malformed_message carried beside the result The dispatch match yields Result<ToolResult, ToolError> directly; the None arm and the mutable sibling are gone.
7 Clarify pre-scan could disagree with the loop The pre-scan applies unusable_arguments after the repair pass, the same as the loop.
9 Docs An ADR-056 addendum (grammar rewrite, close-marker stop, the field-name constraint) is committed to nodespace-docs alongside the merge.
nit "…." A cut-short reason ends in its ellipsis.
nit Past-tense comments The two test docs in agent_loop.rs and the summary comment in tools.rs now describe behaviour.

Not changed

  • 5 — the scenario has no score. Still open. Its group is excluded whenever the setup-venue turn declines to re-create an existing type, which happened in both reps attempted. The PR no longer closes the issue; criteria 3 and 5 are recorded there as open.
  • 8 — gate the close-marker stop on an open call. Not applied. It changes when generation stops, and the only test that exercises the wiring is a live-model one; another eval run has the GPU. The version on the branch is the one the four live tests passed against.
  • nit — distinct tag for the two outcome expectations. Two variants, discriminated in one place; a tag adds more than it saves at this size.
  • nit — title fallback duplicates content for an untitled non-schema node. Harmless: the same text was already in snippet, and an empty title gave the model less.

Verification: bun run test:changed passes (Rust workspace and scripts tiers), quality:fix is clean. The readings in "Not fixed" for the list reply were taken before finding 3 removed the clause and have not been re-taken.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: No critical findings were raised. The changes are a dependency pin, a deleted description clause, a removed dead lookup, comment rewording, and two small, test-covered changes on the malformed-call path (the result plumbing and one extra check in the pre-scan). None adds functionality or changes design.

malibio and others added 3 commits October 1, 2026 21:18
…loses #3268)

"What schemas do we have here?" on gemma-4-E4B produced a call whose whole
kwargs-style argument list arrived as one JSON key, then a call with the
answer inside its arguments, then a reply naming only the custom types.

nlp-engine
- Narrow llama.cpp's Gemma 4 grammar rule for an argument key from "any text
  up to the next colon" to a name, so an argument list, prose, an over-quoted
  key or a leaked quote token can no longer be a key.
- Stop generation at the call's close marker. A string closed with a plain
  quote never ends, and swallowed the marker and the model's answer up to the
  token cap.

agent
- Do not dispatch arguments that parse as JSON but are not an object of named
  parameters; report them to the model as a malformed call, counted by the
  same breaker as arguments that do not parse.
- When a tool failure goes unmentioned in the reply, say which action failed
  and why instead of a generic retry prompt.
- search_nodes' description says node_type='schema' lists every type, and
  that EXISTING SCHEMAS is not that list.
- The fabricated-id guard read a bolded id with its closing asterisks and
  replaced a correct schema list.

eval
- decisions: an outcome scenario for "what schemas do we have", scored on the
  reply naming built-in and custom types off a successful search.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…l error

- search_nodes reported every node's type as empty (nodeType is the wire
  spelling) and a schema node's title as empty (its name is its content), so
  a type listing gave the model ids and nothing to call them.
- The message that replaces a reply ignoring a tool failure quotes the
  tool's first sentence only; the rest is addressed to the model.
- search_nodes' description says a type listing names each type returned.
- Drop a timing figure from a live test's doc comment that was measured
  while another run shared the machine.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…se, tighten the malformed-call path

- Pin llama-cpp-2 to =0.1.146: the grammar rewrite matches one rule of the
  text this version generates, and only Cargo.lock was holding it.
- search_result_summary reads nodeType only; the other two spellings never
  occur on a typed node value.
- Drop "the answer names each one it returned" from search_nodes'
  description: reply policy in a selection channel, with no reading that
  isolates it (ADR-064).
- The dispatch match yields the malformed-call result itself, instead of a
  message carried beside an absent result.
- The clarify pre-scan applies the same malformed-call check as the per-call
  loop, so the two cannot disagree about a call.
- A cut-short tool error ends in its ellipsis, without a full stop after it.
- Comments: say what replaying a malformed call as {} was measured to do,
  and describe behaviour rather than its history.

Skipped, with reasons in the PR comment: gating the close-marker stop on an
open call (needs a live-model run to verify), and a distinct tag for the
eval's two outcome expectations.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@malibio
malibio force-pushed the issue-3268-gemma-tool-call-args branch from a8b7431 to 128202f Compare October 1, 2026 19:18
@malibio
malibio merged commit 79a3f3a into main Oct 1, 2026
@malibio
malibio deleted the issue-3268-gemma-tool-call-args branch October 1, 2026 19:18
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.

1 participant