Repository navigation
Repair over-quoted tool-call argument keys so a rejected call can self-correct (closes #1876) - #1901
Conversation
…f-correct (closes #1876) A rejected tool call was retried forever with the identical malformed payload. Measured against gemma-4-e4b-q4km on the real chat path, the cause is not the model's encoding ability: - First attempts encode nested-object-array arguments cleanly, 0/8 malformed — the tool-call grammar makes an over-quoted key unreachable at generation time. - A retry copies whatever shape the prior assistant turn holds. Seed a malformed prior call and 8/8 retries are malformed; seed a well-formed one under otherwise identical conditions and 0/8 are. A flat-argument control stays clean throughout. So the malformed call poisons the conversation it lives in, and every retry faithfully reproduces what it reads. No existing guard breaks the loop: the arguments are valid JSON (only the keys are wrong), so the parse-failure counter never increments, and alternating create_schema with update_schema defeats the duplicate-call guard. The turn burns its budget and ends with nothing persisted and nothing said. Repair the keys in the agent loop, ahead of both the tool executor and the duplicate guards. The malformation is mechanical — the intended key is the same string minus a wrapping quote pair — so the rewrite is unambiguous, and it applies only when the trimmed name carries no quote of its own and collides with no genuine key. Values are never touched, so user data containing quotes survives intact. Repairing generically rather than in create_schema's validator covers any tool taking an array of objects, and keeps the poisoned shape from re-entering history. Answers the acceptance criteria: the fault is general to nested-object array arguments rather than specific to fields/add_fields; retries are independently regenerated copies of the malformed shape rather than a stuck generation; and a call with this malformation now self-corrects. Adds live characterisation tests recording the measurement the fix rests on, so a later template, grammar, or model change can be rechecked against evidence rather than a remembered claim. They are #[ignore]d — each needs the E4B GGUF and GPU time — alongside fast unit tests covering the repair and its ambiguity and collision guards. Co-Authored-By: Claude <[email protected]>
Pragmatic Code Review — PR #1901Review Type: Initial Review SummaryThis is a well-diagnosed fix. The headline value is not the ~50 lines of repair code — it's the measurement that overturned the issue's own hypothesis. #1876 guessed at a "model-side encoding quirk in nested-object-array arguments"; the evidence shows first attempts are clean 0/8 and the malformation propagates by history imitation (8/8 malformed-in → malformed-out, 0/8 clean-in → clean-out). That reframing is what makes a generic repair the right shape of fix instead of a I verified the risk areas rather than taking them on faith — compiling the repair function standalone and running adversarial inputs through it. The two scariest hypotheses turned out to be non-issues, and I want to record why so they don't get re-litigated:
All 5 new tests pass locally (0.04s). Standards are clean: no lint suppressions, no The findings below are one Important design-hazard question and some polish. Nothing here is a blocker. Requirements Check (issue #1876)
All three met by code I verified, not merely claimed in the PR body. Code Review Findings🟡 Important1. The recursive repair reaches free-form user data, diverging from the 📁
/// Only the top level: a nested `properties` blob is the user's own data, where
/// a key named `node_id` means whatever the user's schema says and must not be
/// renamed.
I confirmed the blob is genuinely free-form: Weighing it honestly, I think the current choice is defensible and I'm not asking for it to be reverted:
But the asymmetry deserves to be a recorded decision rather than an implicit one. Recommendation: extend the doc comment on Principle: Principle of Least Astonishment / decision provenance. When two neighbouring functions make opposite choices on the same question, the reasoning must be written down or the inconsistency will read as an oversight and get "fixed" in the wrong direction. 2. 📁 assert_eq!(
malformed,
trials * 2,
"a malformed prior call must reproduce malformed on every retry \
(2 malformed fields per trial); ..."
);To be clear on what's fine here: asserting that the bug still reproduces is a legitimate characterisation test, and the comment explaining that this asserts measured rather than desirable behaviour — with failure as the signal to re-check whether the repair is still load-bearing — is genuinely good practice. It's also correctly The narrow issue is the counter's granularity. This is a live-only, manually-run test, so blast radius is small — hence 🟡 not 🔴. Recommendation: count trials, not fields. Track Principle: Tests should assert the claim, not its incidental side effects. An assertion coupled to details the hypothesis doesn't depend on fails for reasons unrelated to what it's protecting. 🟢 Suggestions3. 📁 let prior_args = std::env::var("PRIOR_ARGS").unwrap_or_else(|_| { ... });This is the switch that runs the clean-prior-call control arm — one of the two arms the whole diagnosis rests on — but nothing in the file or module docs says so. The module header describes "clean in, clean out" as measured, yet a reader has no way to know how to reproduce that arm. Since the point of these tests is to let a future engineer recheck the premise against evidence, the mechanism for running half the experiment should be discoverable. Also, the read sits inside the trial loop, so it's re-read 8 times to produce the same value. Harmless, but it belongs above the loop where it reads as a per-run parameter. Recommendation: hoist the Principle: Reproducibility. A characterisation test's value is proportional to how easily the next person can re-run it. 4. 📁 I checked whether this is redundant. It isn't — both sites are genuinely needed, for different reasons:
So removing either one leaves a consumer reading unrepaired keys. The idempotence that makes double-application safe is easy to confirm: a repaired key no longer starts with On the parent's specific concern — that repairing inside Recommendation: no code change. Optionally add one line at Principle: Comment the non-obvious "why". Apparent duplication that is actually load-bearing needs a note, or someone will helpfully remove it. 5. Nit: 📁
RecommendationAPPROVE — merge once you've considered the two 🟡 items. Net assessment: this clearly improves code health. The diagnosis is the real contribution and it's rigorous — the seeded-prior-call experiment with a flat-argument control is a properly designed A/B, and it disproved the issue's stated hypothesis rather than confirming it, which is the harder and more valuable outcome. All three acceptance criteria are met by verified code. The repair predicate is conservative in the right places: it declines on empty inner names, inner quotes, and collisions, and it never touches values. Neither 🟡 blocks merge. #1 is a documentation gap around an accepted trade-off, not a defect — the behaviour is intentional and reasonable for a zero-user codebase; it just needs the reasoning recorded so it isn't mistaken for an inconsistency later. #2 is a brittle assertion in a manually-run One forward-looking note worth carrying into a future issue rather than this PR: this repair treats a symptom of a more general property — the model copies malformed shapes out of its own conversation history. Over-quoted keys are one instance; the same mechanism will reproduce any other malformation that survives JSON parsing. If a second instance of this class shows up, the more durable fix is likely at the history level (not persisting a rejected call's malformed arguments back into the transcript) rather than adding a second shape-specific repair beside this one. Right call not to build that speculatively now — YAGNI — but the pattern is worth naming. |
malibio
left a comment
There was a problem hiding this comment.
Initial review posted as a PR comment. Verdict: APPROVE — 2 Important (non-blocking) items, 3 suggestions. See the review comment for details.
…cterisation assertion Two non-blocking items from the review of the repair fix. Record why `repair_over_quoted_keys` recurses where the neighbouring `normalize_param_aliases` deliberately does not. The two answer different questions: an alias rewrite guesses at intent and could rename a key the user meant, so it stays top-level; a key carrying its own quote marks is not expressible as a deliberate choice, and the malformation only ever appears nested, so a top-level-only rule would decline every case the repair exists for. Written down so the inconsistency is not later "fixed" in the wrong direction. Decouple the live characterisation assertion from an incidental count. It previously fused "every retry is malformed" with "exactly 2 fields per trial", so a run with identical behaviour but a different field count would fail while pointing at the wrong conclusion — and could prompt removing a repair that is still load-bearing. Now counts trials, and reports field totals separately. Fold the PRIOR_ARGS env switch into an explicit two-arm loop that asserts both outcomes in one run. Holding everything but the prior turn's shape fixed is the actual experiment, so both arms belong in the test rather than one being reachable only by making it fail on purpose. Renamed to retry_copies_the_shape_of_the_prior_call, which is what it measures. Verified live: malformed-prior 8/8, clean-prior 0/8, all three characterisation tests green. Co-Authored-By: Claude <[email protected]>
Review items addressed (97a3fb5)Both 🟡 items fixed. Thanks for the empirical verification on the UTF-8 slicing, cascade-repair ordering, and identity-collision concerns — those were the three I was least sure of, and probing them beat reasoning about them. 🟡 1 — recursion divergence from 🟡 2 — 🟢 3 — undocumented Holding everything but the prior turn's shape fixed is the experiment, so both arms belong in the test — previously the control was only observable by making the test fail on purpose, which is a bad way to store a load-bearing result. Renamed to 🟢 4 / 5 — no change, agreed. The double call is load-bearing in both places as you verified, and the All 3 live characterisation tests green; On the forward-looking note — agreed, and worth stating plainly since it's the more interesting half of this: the repair treats a symptom of a general property, that the model copies malformed shapes out of its own history. The durable fix is at the history level (not persisting a rejected call's malformed arguments back into the transcript). I deliberately didn't build that here — one measured instance doesn't justify reworking transcript persistence, and doing it speculatively would be a much riskier change than this one. If a second shape shows up, that's the signal to do it properly rather than adding a second shape-specific repair. |
`quality:fix` reported 5 type errors in two test files. All were the same root cause: mocks whose types were inferred from a single default return, narrower than the contract they stand in for. The tests passed at runtime throughout — these were type-check-only failures. - daemon-status: the mock stands in for two commands with different return types. The status commands answer with a string and `probe_and_recover_channel` answers with a boolean, but inference from the default narrowed it to `string` and rejected the boolean the probe tests legitimately return. Widened to `Promise<string | boolean>`. - update-status: inference from a default carrying `latest: null` fixed the property to `null`, rejecting tests that resolve a real version. Annotated with the exported `UpdateStatus` interface so the mock is tied to the contract it mirrors rather than to one sample value. The import is type-only, so it is erased before `vi.mock` hoisting. - Both `invoke` and `openUrl` mocks are called with forwarded arguments but were inferred as zero-arity; given rest parameters. Widening the declared types rather than suppressing: each error named a real gap between the mock's type and its use. Frontend suite green (171 files, 4108 tests); svelte-check now reports 0 errors and 0 warnings across 2171 files. Co-Authored-By: Claude <[email protected]>
Closes the last actionable item from the PR review. The reviewer noted that `repair_over_quoted_keys` runs twice per call and verified both are load-bearing, but that nothing at either site says so. Each site already explained its own purpose; neither mentioned the other's existence, so a reader at either one could reasonably conclude it was redundant and delete it. Both now name the other and say what it does not cover: `canonical_args` repairs only the copy taken for the duplicate guards' identity and never touches the arguments handed to the tool, while the execution-path repair is the only one the tool itself and the cross-turn write guard observe. Verified before asserting it — both production callers of `canonical_args` pass `&tc.arguments_json` and discard the parsed value, so it cannot reach the executed arguments. Comment-only; no behaviour change. Deliberately not taking suggestion 5 (an avoidable `to_string()` in the repair loop). It allocates once per malformed key on a path that runs only when a model emitted a broken key, and the borrow it would avoid requires restructuring the remove/insert around the borrow checker for no measurable gain. Worth revisiting only if this ever shows up in a profile. Co-Authored-By: Claude <[email protected]>
Review items — final statusAll 5 findings resolved (0 🔴, 2 🟡, 3 🟢). Commits
On #4 (addressed in this last commit): each call site already explained its own purpose, but neither mentioned the other existed — so a reader at either one could reasonably delete it as redundant. Both now name the other and state what it does not cover. I verified the claim before asserting it in a comment: both production callers of On #5 — skipped, with reasoning: the allocation happens once per malformed key, on a path that only runs when a model emitted a broken key in the first place. Avoiding it means restructuring the remove/insert around the borrow checker for no measurable gain. Revisit only if it ever appears in a profile. Verification: Re-Review DecisionDecision: NO RE-REVIEW NEEDED Rationale: Nothing since the approving review changes production behaviour. The delta is: doc comments in The reviewer's own guidance was "merge once you've considered the two 🟡 items." Both are addressed, and the third 🟢 went further than suggested. One scope note for the merge decision: Ready for merge, pending your call. |
Closes #1876.
What was actually happening
The issue suspected a model-side encoding quirk in how nested-object-array arguments are emitted. Measured against
gemma-4-e4b-q4kmon the real chat path, that turned out not to be it.create_schemafieldsarrayThe tool-call grammar makes an over-quoted key unreachable at generation time, so first attempts are clean. What the model does on a retry is copy the shape it reads in its own conversation history. A rejected call stays in the transcript as an assistant turn, so the malformed payload poisons every subsequent attempt — the retry path is a copy machine, not a repair mechanism.
Nothing in the loop could break this:
consecutive_parse_failuresnever increments.create_schema→update_schemagives a different(tool, args)identity each round, defeating the duplicate-call guard.The turn burns its iteration budget and ends with nothing persisted and nothing said — exactly the reported end state.
The fix
Repair the keys in the agent loop, ahead of both the tool executor and the duplicate guards.
The malformation is mechanical — the intended key is the same string minus a wrapping quote pair — so the rewrite is unambiguous. It applies only when the trimmed name carries no quote of its own and collides with no genuine key already present; anything else is passed through untouched. Values are never rewritten, so user data containing quotes survives intact.
Repairing generically rather than inside
create_schema's validator matters twice over: the propagation mechanism is the conversation, not the tool, so any tool taking an array of objects is reachable the same way; and repairing beforecanonical_argsmeans a malformed call and its repaired retry resolve to one identity instead of two.Acceptance criteria
fields/add_fields, or general? General. The propagating mechanism is history imitation, independent of which tool's arguments carry the shape — hence the generic fix.Tests
#[ignore]d live characterisation tests (packages/nlp-engine/tests/toolcall_json_shape.rs) recording the measurement above, so a later template, grammar, or model change can be rechecked against evidence rather than a remembered claim. Each needs the E4B GGUF and ~20s of GPU time; run with--ignored --nocapture.test:allgreen (frontend 4108/4108, agent 412, core 1105); full pre-push gate passed. The 5svelte-checkerrorsquality:fixreports are pre-existing onmainin test files untouched here (verified against a clean tree).🤖 Generated with Claude Code