Skip to content

Repair malformed tool-call args at the parse boundary so the call reaches the tool (closes #1943) - #1946

Merged
malibio merged 3 commits into
mainfrom
issue-1943-malformed-tool-args
Aug 3, 2026
Merged

malibio merged 3 commits into
mainfrom
issue-1943-malformed-tool-args

Conversation

@malibio

@malibio malibio commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

Closes #1943.

What was wrong

The locked model emits search_nodes filters with two malformations at once — keys carrying literal quotes and a value that swallowed the delimiters introducing the next key:

{"filters":[{"\"operator\"":"equals","\"property\"":"status","\"type\"":"task\",\"value\":"}],"\"node_type\"":"task","query":null}

This parses as valid JSON, so no parse guard fires. It is rejected on its merits instead.

Findings against the acceptance criteria

Where the corruption originates. Not the parser and not transport: llama.cpp's own OAI-compat parser is used, and the arguments string is deserialized exactly once between engine and tool. No double-encoding path exists. The malformation is the model's own output.

One defect or two? One. The reproduction's splice hid that type was "task" all along; with the splice repaired, the run reproduces #1939's production error verbatim — Unknown filter type 'task'. The model puts the node type in the filter's category slot.

Nested-object specific? The previously-untyped value leaf was the leading suspect. Typing it changed nothing — byte-identical output across 3/3 reps — so nesting depth is not the trigger. Recorded in the code so the next person doesn't re-run it.

Four defects fixed

  1. Repairs never reached history. They mutated a local Value, never tc.arguments_json — the string persisted into history and replayed verbatim into the next prompt, where the model copies it (8/8 malformed from malformed, 0/8 from clean). Every attempt was repaired for the tool and re-taught to the model. Repair now runs at the parse boundary.
  2. The spliced value survived every existing repair. repair_spliced_object_values recovers the truncated value from the exact ","<key>": delimiter run. It does not invent the swallowed key's value — that was never emitted.
  3. query: null was rejected though omitted and null mean the same thing here. deny_unknown_fields still rejects misspelled keys.
  4. Category inference deferred to an invalid type. It now falls through on an unrecognised value; an item naming no subject still errors, and the message names the value actually supplied.

Verified on the locked native model

3/3 reps. The retry now reaches the query layer with usable keys, a clean type, and correct category routing.

The honest residue

The model never emits the comparison value, so equals has nothing to match and the query fails for a missing value. Inventing "open" would fabricate the user's query.

So live_model_recovers_from_a_bad_enum_value_without_asking asserts that every retry gets as far as that missing value — repair and routing must carry it that far — rather than asserting execution. Asserting execution would encode a capability this model does not have and leave a permanently red test. This is a deliberate deviation from the issue's stated criterion; flagging it explicitly for review.

Testing

  • test:all — no new failures vs baseline (frontend 171 files / 4108 tests, unchanged)
  • New unit tests: the verbatim reported payload end-to-end, history-carries-repaired-args (verified to fail without the fix), null-query, category fallthrough, and negative cases guarding user data
  • Live: cargo test --release -p nodespace-agent --test live_unset_schema_field live_model_recovers -- --ignored --nocapture --test-threads=1

🤖 Generated with Claude Code

https://claude.ai/code/session_01FELy7rhqnKbDmmG9fuHALT

malibio and others added 2 commits August 3, 2026 22:00
…ches the tool (closes #1943)

The locked model emits `search_nodes` filters with two malformations at once:
keys carrying literal quotes (`"\"property\""`) and a value that swallowed the
delimiters introducing the next key (`"type": "task\",\"value\":"`). The payload
is valid JSON, so no parse guard fires; the filter is rejected instead.

Four distinct defects sat between the model and a working query:

1. Repairs ran on a local copy, never on `tc.arguments_json` — so the malformed
   text was persisted into history and replayed verbatim into the next prompt,
   where the model copies it (measured 8/8 vs 0/8 in toolcall_json_shape.rs).
   Every attempt was repaired for the tool and simultaneously re-taught to the
   model. Repair now runs at the parse boundary, so the record is repaired too.

2. The spliced value survived every existing repair. `repair_spliced_object_values`
   recovers the truncated value (`task`) from the exact `","<key>":` delimiter
   run. It does not invent the swallowed key's value — that was never emitted.

3. `query: null` was rejected (`invalid type: null, expected a string`) though
   omitted and null plainly mean the same thing here. Read as empty now;
   `deny_unknown_fields` still rejects misspelled keys.

4. Filter-category inference deferred to a supplied `type` even when it named no
   category. The model writes the *node* type there while `node_type` carries the
   same value — the production `Unknown filter type 'task'` from #1939, which
   this establishes is the same defect, not a second one. Inference now falls
   through on an unrecognised value; an item naming no subject still errors, and
   the message names the value supplied rather than claiming `type` was omitted.

Verified on the locked native model, 3/3: the retry now reaches the query layer
with usable keys, a clean `type`, and correct category routing.

What remains is not repairable downstream: the model never emits the comparison
value, so `equals` has nothing to match and the query fails for a missing value.
Inventing "open" would fabricate the user's query. Typing the previously-untyped
`value` leaf was tried against this and changed nothing (byte-identical output
3/3); it is kept as a schema correctness fix, not as a claimed remedy.

`live_model_recovers_from_a_bad_enum_value_without_asking` therefore asserts that
every retry gets as far as that missing value — repair and routing must carry it
that far — rather than asserting execution, which would encode a capability this
model does not have and leave a permanently red test.

Co-Authored-By: Claude <[email protected]>
…place

Two follow-ups on the repair introduced for #1943.

`repair_spliced_object_values` rewrites a string *value*, not just a key, so
unlike the two sibling key repairs it can reach user-authored text: create_node
and update_node carry the user's own note in `content` and their chosen field
values in `properties`. The mechanical shape is rare but typeable — a pasted CSV
header fragment (`name","email":`) matches it exactly — and silently truncating
a note is a worse failure than declining to repair a filter. Those subtrees are
now skipped at any depth. Nothing is given up: the malformation is only observed
in filter and schema-definition objects, where every value is a machine-chosen
token and none is free text.

The three repairs were also listed individually at three call sites, so a fourth
would have to be remembered in all three. They now go through one
`repair_parsed_tool_arguments` helper, which is the single place the set is
enumerated.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

Verdict: Approve with one non-blocking follow-up. (Posting as a comment — GitHub rejects self-approval.)

This is a strong change. The investigation is the best part of it: the PR answers all four diagnostic acceptance criteria with measured evidence, and — unusually — records two negative results (typing the value leaf changed nothing, 3/3 byte-identical; the splice is first-emission, not history-propagation) directly in the code rather than letting the next person re-run them. That is exactly the right instinct.

The core insight is genuinely valuable and worth restating: repairs were mutating a local Value and never tc.arguments_json, so every attempt was repaired for the tool and simultaneously re-taught to the model via history replay (8/8 malformed-from-malformed vs 0/8 from clean). Moving repair to the parse boundary is the correct structural fix, not a patch.

I verified the central claims rather than taking them on trust:

  • history_carries_the_repaired_arguments_not_the_malformed_ones genuinely gates the fix. I disabled the parse-boundary repair loop in a scratch copy; the test fails with exactly the reported malformed shape ("\"node_type\"", "type": "task\",\"value\":") and passes with it restored. It is a real regression gate, asserted on session.messages — the channel the defect actually travelled through — which is the right assertion target.
  • Full nodespace-agent lib suite: 461 passed, 0 failed.

Findings

Critical Issues

None.

Suggested Improvements

[Improvement — already fixed in flight] repair_spliced_object_values rewrote user-authored values. This was my main concern and it is worth recording why, since the reasoning outlives this PR.

Unlike the two sibling repairs, this one rewrites values, not keys. That is a real category change. The key repairs are safe because a JSON key carrying its own quote marks cannot be written by the schema path that produced it — the malformation is not expressible as intent. That argument does not transfer to values: a value is frequently the user's own text, where any byte sequence is expressible as intent.

I probed the guard directly (compiled strip_spliced_delimiter_tail standalone). The shape test is tight against syntactic accidents but not against semantic ones — these all match and get silently truncated:

Reviewed the paper","Notes":   => "Reviewed the paper"
done","due date":              => "done"
name","email":                 => "name"     <- pasted CSV header fragment

The key.is_empty() and no-inner-quote guards correctly reject x",": and task","":, and the multi-splice case task","value":"open","limit": correctly returns None (embedded quotes). So the shape test is well-constructed. The gap was never shape — it was reach: the function recursed into content and properties, where user data lives verbatim.

You independently found and fixed this mid-review by skipping content/properties subtrees at any depth, plus spliced_repair_never_touches_user_authored_content. I confirm the fix is correct and the structural slots (filters, fields) remain covered. Treating point 2 as resolved. The scoping is the right one: repair the model's structural slots, never the user's authored ones.

[Improvement] Note the residual containment argument in the doc comment. Even with the subtree skip, the guard is a denylist — a future tool adding a free-text parameter under some name other than content/properties (say body, note, summary) silently re-enters the blast radius. Worth one sentence noting that the safety rests on an enumerated list of user-data keys, so whoever adds such a parameter knows to extend it. An allowlist of structural slots (filters, fields, add_fields) would invert this to fail-safe, but that is a larger change and I would not block on it — the denylist covers every current tool.

On the deliberate deviation from the acceptance criterion

The reasoning is sound and I would accept it. The criterion asked that the retry assert execution; the PR asserts every retry reaches a "missing value" failure instead.

The justification holds up: the model writes the delimiters that should have introduced value as string content, so the comparison value is never generated at all. There is nothing downstream to recover — synthesizing "open" would fabricate the user's query, which is strictly worse than an honest failure. Asserting execution would encode a capability this model does not have and leave a permanently red test. Deferring to a red test as "documentation" is a well-known anti-pattern; this is the right call.

More importantly, the weaker assertion still has teeth. This was the thing worth checking, and it passes:

assert_eq!(executed + missing_value_only, recovered, ...)

missing_value_only increments only on an error containing "Missing value". So it would catch:

  • a repair regression — an unrepaired shape fails as unknown field / Unknown filter type, not "Missing value", so it lands in neither bucket and the assertion fires;
  • a category-inference regression — a filter routed on the mislabelled slot fails as Unknown filter type 'task', likewise failing the assertion;
  • a new malformation appearing — same path.

The one soft spot is that it string-matches "Missing value", so rewording that error message elsewhere silently converts a real failure into an assertion failure. That is noisy-but-safe (fails closed), which is the right direction. Recommend the criterion be marked deviated-with-rationale on #1943 rather than checked off, so the delta stays visible.

On the remaining brief points

Category inference fallthrough (query_ops.rs) — correct, and does not mask user error. category() now falls through when type is not one of the four known categories. I traced the interaction: is_known_category and parse_filter_type enumerate the identical set, so a value that passes the former always parses in the latter — no divergence. Crucially, no previously-correct query changes behavior: a valid category still returns early and takes precedence, so only inputs that previously errored can now succeed. The masking risk is real in principle but bounded well here — inference reads property/relationship_type/node_id, which name the filter's actual subject, and an item naming no subject still errors. The improved error message (naming the supplied value and pointing at node_type) is a genuine upgrade over the old "you omitted type" text shown to a caller who did not omit it. deny_unknown_fields is unaffected — it operates at deserialization, before category() runs.

Nit: is_known_category and parse_filter_type are two enumerations of one set, three lines apart. They cannot drift silently today (the tests would catch it), but is_known_category(s) could be parse_filter_type(s).is_ok() and then there is exactly one authority. The doc comment already anticipates the concern; collapsing it is cheap.

null_as_default on query: String — does not weaken the misspelled-key guard. These are orthogonal mechanisms: deny_unknown_fields rejects unrecognized keys, while null_as_default governs the value of an already-recognized one. null_query_allowance_does_not_admit_unknown_keys pins exactly this and passes. Accepting null where the field is already #[serde(default)] is correct — omitted and null genuinely mean the same thing for a title filter, and rejecting a correct call over its spelling is a real failure mode (measured 3/3). The helper is appropriately scoped and its doc comment explicitly limits it to fields where the two spellings coincide.

Making repair_tool_call_arguments pub — acceptable, and the alternatives are worse. The instinct to flag test-only visibility widening is right, but here the seam is legitimate: the live test drives the inference engine directly with no LocalAgentLoop in the path, so without applying the same repair it would measure a raw call no production path ever executes — a test asserting against fiction. The function is a pure &mut String transform with no invariants to violate, so the exposed surface is genuinely small. The doc comment states why it is public, which is the important part. #[cfg(test)] would not work across a crate boundary (tests/ is a separate compilation unit), and pub(crate) likewise fails for the same reason.

Defense-in-depth vs. redundancy — this was a fair concern, and your in-flight refactor resolves it. As originally written, three repair call sites each listed the same three functions by hand — precisely the drift risk I would have flagged, since a fourth malformation would have to be remembered in three places. Extracting repair_parsed_tool_arguments as the single enumeration reduces this to one list with two callers. The remaining duplication is now genuine defense-in-depth rather than copy-paste: the parse boundary and the execution site have different callers (canonical_args never sees the executed arguments), so removing either leaves a live gap, and the backstop no longer depends on the earlier pass having run. Good call.

Test quality

Strong overall. The suite covers the verbatim reported payload end-to-end, the history-propagation gate (verified to fail without the fix), the null-query pair, category fallthrough in both directions, byte-identical passthrough for clean args, unparseable-args passthrough, and negative cases guarding user data. The negative tests are the ones that matter most for a heuristic like this, and they were present from the start — spliced_repair_leaves_ordinary_strings_untouched and spliced_repair_does_not_invent_the_swallowed_key are exactly the right instincts.

Nit: repair_entry_point_leaves_clean_arguments_byte_identical bundles two distinct properties (clean passthrough, unparseable passthrough). Splitting them would name the failure more precisely, though both assertions are clear enough that this is minor.


Net assessment: a well-investigated fix that addresses a genuine self-sustaining failure loop, with honest documentation of what it cannot fix and why. The one real risk — value rewriting reaching user data — is now contained. Recommend merge once the deviation is recorded on #1943.

@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.

Verdict: APPROVE with one non-blocking follow-up (posting as a comment — GitHub rejects self-approval).

Full review posted above. Summary:

  • No critical issues. The core insight — repairs mutating a local Value while tc.arguments_json stayed malformed and was replayed into the next prompt — is a genuine self-sustaining loop, and moving repair to the parse boundary is the correct structural fix.
  • Verified rather than trusted: disabled the parse-boundary repair in a scratch copy and confirmed history_carries_the_repaired_arguments_not_the_malformed_ones fails with exactly the reported malformed shape and passes when restored. It is a real gate. Full agent lib suite: 461 passed, 0 failed.
  • The acceptance-criterion deviation is sound. The model never emits the comparison value, so execution is genuinely unreachable without fabricating the user's query. The weaker assertion still has teeth: missing_value_only matches only "Missing value", so a repair regression or a category-inference regression fails as unknown field/Unknown filter type and trips the assertion. Recommend marking the criterion deviated-with-rationale on #1943 rather than checked off.
  • Main concern (value rewriting reaching user data) is resolved in flight. repair_spliced_object_values rewrites values, not keys — a category change from its siblings, since a user's text can express any byte sequence as intent. I confirmed by direct probe that Reviewed the paper","Notes": and a pasted CSV header name","email": match the shape exactly. The gap was reach, not shape; the content/properties subtree skip fixes it correctly.
  • Follow-up (non-blocking): that guard is a denylist, so a future free-text parameter named something else (body, note) silently re-enters the blast radius. Worth a sentence in the doc comment so whoever adds one knows to extend the list.
  • Category fallthrough, null_as_default, and the pub seam all check out — details in the comment.

Recommend merge once the deviation is recorded on #1943.

Three non-blocking follow-ups from the PR review. No behaviour changes.

- `is_known_category` deferred to `parse_filter_type(s).is_ok()` instead of
  re-listing the four categories three lines away, so there is one authority on
  the set and the two cannot drift.
- Noted in `repair_spliced_object_values`'s doc comment that its safety rests on
  an enumerated denylist of user-data keys: a tool added later with a free-text
  parameter named something other than `content`/`properties` re-enters the blast
  radius unless the list is extended. Records the inversion to an allowlist as
  the better shape if the list grows.
- Split `repair_entry_point_leaves_clean_arguments_byte_identical`, which bundled
  clean-passthrough and unparseable-passthrough, so a failure names which
  property broke.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed

All four follow-ups from the review are in 580851ac (plus d8c8f654, pushed mid-review). No critical issues were raised; nothing was skipped.

Addressed:

  1. 🟢 Denylist containment noted. repair_spliced_object_values' doc comment now states that its safety rests on an enumerated list of user-data keys, so a tool added later with a free-text parameter named something other than content/properties re-enters the blast radius unless the list is extended — and records the inversion to a structural allowlist as the better shape if the list grows past a couple of entries.
  2. 🟢 Single category authority. is_known_category now defers to parse_filter_type(s).is_ok() rather than re-listing the four categories three lines away. The two can no longer drift.
  3. 🟢 Split the bundled test. repair_entry_point_leaves_clean_arguments_byte_identical covered two distinct properties; unparseable-passthrough is now repair_entry_point_leaves_unparseable_arguments_unchanged, so a failure names which property broke.
  4. 📝 Deviation recorded on Model emits malformed JSON args for search_nodes filters, so the filter never runs #1943 as deviated-with-rationale rather than checked off: Model emits malformed JSON args for search_nodes filters, so the filter never runs #1943 (comment)

Also landed mid-review (d8c8f654): the content/properties scoping the review independently confirmed, and consolidation of the three repair call sites into one repair_parsed_tool_arguments helper — the drift risk raised under point 6.

Verification: test:all green, no new failures vs baseline (frontend 171 files / 4108 tests, unchanged; agent lib 462 passed; query_ops 18 passed). Live model re-run after the refactor is unchanged: recovered=3 executed=0 missing_value_only=3 asked_the_user=0.

A correction to the record: the review reports that the reviewing agent inadvertently reverted my uncommitted work with a git checkout -- and reconstructed it from my description. I diffed what is committed against what I intended — repair_spliced_object_values and its test are semantically equivalent (the reconstruction is in fact slightly stronger, adding a deeper nesting case), and repair_parsed_tool_arguments is my own subsequent work. Nothing in this PR is unverified reconstruction.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: All three code changes are 🟢 suggestions with no behavioural effect — one doc-comment addition, one two-line refactor that routes an existing predicate through the function that already owned the set, and one test split with both assertions preserved verbatim. The substantive change the review cared about (value repair reaching user data) was already reviewed and confirmed in-flight. Full suite green.

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.

Model emits malformed JSON args for search_nodes filters, so the filter never runs

1 participant