Skip to content

Repair create_schema JSON keys corrupted by a leaked Gemma quote token (closes #1926) - #1929

Merged
malibio merged 2 commits into
mainfrom
issue-1926-schema-json-corruption
Aug 3, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-1926-schema-json-corruption

Conversation

@malibio

@malibio malibio commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

Summary

Closes #1926. Scenario 8b regressed 3/3 → 0/3 after the history-compaction fix (#1925) — root-caused to a pre-existing, unrelated bug the compaction fix merely exposed: grammar-constrained decoding was observed emitting Gemma 4's literal quote-token text (<|"|>) inside create_schema's fields array, corrupting a key like "type" into "<|"|>type<|"|>". That's syntactically valid JSON with a garbled key, so no parse-failure guard caught it — the tool rejected the call for a missing type field.

What was tried and didn't work (documented for the record)

The obvious fix — the codebase already strips this exact leaked token from plain-text content via strip_gemma_special_tokens — is to apply the same stripping to tool-call arguments at the streaming-delta layer (nlp-engine::emit_oai_delta). This passed unit tests reproducing the exact corrupted string from the issue's daemon-log evidence, but failed live: the token can straddle a delta boundary (one streamed chunk ending <|, the next starting "|>), and a per-delta substring strip can't match a token split across two deltas. Confirmed via a genuinely clean-rebuilt binary — the corruption still appeared verbatim in the daemon log.

The actual fix

repair_leaked_special_token_keys, a sibling to the existing repair_over_quoted_keys (#1876's fix for a related-but-distinct key-corruption shape — the model over-quoting its own keys). Operates on the fully accumulated, already-parsed argument Value — immune to delta boundaries since the corrupted key already exists as one complete string by the time it runs. Wired in alongside repair_over_quoted_keys at both call sites: the real execution path and canonical_args (so a malformed call and its repaired retry share one duplicate-guard identity, same rationale as the existing repair).

Test plan

  • 4 new unit tests: recursion at every nesting depth (verbatim shape from the issue's daemon-log trace), collision/empty-key guards, values never rewritten, duplicate-guard identity via canonical_args. Verified each catches its regression by temporarily reverting the fix.
  • cargo test -p nodespace-agent --lib — 434 passed, 0 failed
  • cargo clippy --all-targets -- -D warnings -D clippy::unused-async — clean
  • bun run quality:fix — clean (0 errors/warnings)
  • Live single-rep sanity check: 8b passes cleanly, args_preview shows the correctly-repaired "type" key, schema persisted
  • Full 3-rep matrix gate (isolated daemon, purged DB per rep, per rule 3 — shared parsing/repair surface): 10, 10, 10 — mean 10.0/12, fully deterministic. Scenario 8b passes all 3 reps with zero JSON corruption across 9 create_schema executions. Remaining failures (scenario 6 — documented model-capability limit; scenario 8c — update_node resolves the correct node but persists no properties on state-change requests (scenario 6 residual gap) #1927) are pre-existing, separately tracked, and unaffected by this change.
  • Pre-push gate (test:all + cargo build --bin nodespaced + test:e2e) passed

Full investigation trail on #1926's comments.

Co-Authored-By: Claude [email protected]

closes #1926)

Grammar-constrained decoding was observed emitting Gemma 4's literal
quote-token text (<|"|>) inside a create_schema call's fields array,
corrupting a key like "type" into "<|"|>type<|"|>" — syntactically
valid JSON with a garbled key, so no parse-failure guard caught it;
the tool rejected the call for a missing "type" field, and scenario
8b regressed from 3/3 to 0/3.

First attempt stripped the leaked token at the streaming-delta layer
in nlp-engine (mirroring how content already handles it), and looked
correct against unit tests reproducing the exact corrupted string —
but failed live: the token can straddle a delta boundary, and a
per-delta substring strip can't match a token split across two
separate deltas. Content has boundary-carry handling for exactly this
reason; tool-call arguments never did.

Fixed instead with repair_leaked_special_token_keys, a sibling to the
existing repair_over_quoted_keys (#1876), operating on the fully
accumulated, already-parsed argument value — immune to delta
boundaries since the corrupted key already exists as one complete
string by the time it runs. Wired in alongside repair_over_quoted_keys
at both call sites: the real execution path and canonical_args, so a
malformed call and its repaired retry share one duplicate-guard
identity.

Validated: 3-rep full matrix gate (isolated daemon, purged DB per rep)
scores 10, 10, 10 — mean 10.0/12, fully deterministic. Scenario 8b
passes all 3 reps with zero JSON corruption in the daemon log across
9 create_schema executions. Remaining failures (scenario 6, 8c) are
pre-existing, separately tracked, and unaffected by this change.

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

malibio commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

Clean, well-scoped bug fix. repair_leaked_special_token_keys is a direct structural sibling of the existing repair_over_quoted_keys (#1876) — same recursion shape, same collision/empty-key guards, wired at the same two call sites (real tool-execution path and canonical_args). Single commit, single file, 138 lines, entirely additive. This is a net positive and I recommend APPROVE.

I independently re-ran the 4 new tests (cargo test -p nodespace-agent --lib leaked_special_token) — all pass — and cargo clippy -p nodespace-agent --all-targets -- -D warnings is clean. cargo fmt --check shows drift only in unrelated pre-existing files (golden_scenario6_sequence.rs, core/src/db/migrations/mod.rs, etc.), never in agent_loop.rs.

Findings

Critical Issues

None.

Suggested Improvements

  • packages/agent/src/local_agent/agent_loop.rs:265-298 — Correctness trace for the two-corrupted-keys-in-one-object case (not covered by an explicit test): I walked through it manually. corrupted is snapshotted once via obj.keys() before any mutation, but the per-key collision check (obj.contains_key(&repaired)) runs against the live, mutating obj on each loop iteration — so if two different corrupted spellings both repair to the same target name (e.g. <|"|>type<|"|> and type<|"|>), the first repair wins and inserts type; the second correctly sees the now-present type key and backs off, leaving its own key untouched rather than silently overwriting. Nested values under a collision-skipped key are still recursed into afterward via the values_mut() loop, so deeper corruption isn't stranded. This is correct, but it's a subtle enough interaction (mutate-while-checking, not check-against-a-frozen-snapshot) that I'd suggest a fifth test asserting it explicitly, e.g. two keys in one object that both repair to the same target — the test suite currently only asserts collision against a pre-existing clean key, not a same-pass collision between two repairs. Nit-level — the manual trace holds, so this is a coverage suggestion, not a blocker.

  • Scope: single token vs. the 11 in strip_gemma_special_tokens (packages/nlp-engine/src/chat/mod.rs:856-870) — repair_leaked_special_token_keys only matches <|"|>, the one token the issue's daemon-log evidence documents leaking into a JSON key position. This is a reasonable, evidence-scoped decision consistent with YAGNI — the other 10 tokens are documented content-stream artifacts with no observed key-corruption case, and hardcoding a const list mirroring all 11 without evidence would be premature generalization. The doc comment on the new function is appropriately scoped in its claims (names the specific token and mechanism, doesn't imply broader coverage). If any of the other 10 tokens are later observed corrupting a key the same way, that's a natural, cheap follow-up (add to a small &[&str] list and iterate) rather than something this PR needs to anticipate now.

Nitpicks

  • Nit: packages/agent/src/local_agent/agent_loop.rs:241-264 — the doc comment on repair_leaked_special_token_keys is unusually long and discursive for this codebase's typical density (24 lines of prose for a ~30-line function). Given the subtlety it's explaining — why a per-delta streaming fix was tried and provably failed, why operating on the parsed Value sidesteps that specific failure mode, and why deletion (not substitution) is correct — the length is earned here; a shorter comment would likely just prompt a future engineer to re-attempt the streaming-layer fix and rediscover the delta-boundary problem the hard way. No change requested.

Verification Notes (independently checked, not just accepted from the PR description)

  • cargo test -p nodespace-agent --lib leaked_special_token → 4/4 passed.
  • Tests are non-tautological: each compares against an independently-constructed expected serde_json::Value, not a mirror of the implementation's own logic.
  • cargo clippy -p nodespace-agent --all-targets -- -D warnings → clean on this file.
  • cargo fmt --check drift confirmed pre-existing and unrelated to this PR's file.
  • Manually traced the collision-guard algorithm against the "two keys collide with each other" edge case (see above) — correct by construction, not just by the guard against pre-existing keys.
  • Confirmed the doc comment's core claim (streaming-delta strip is provably insufficient due to token-boundary splitting) is consistent with the existing strip_gemma_special_tokens helper's per-delta application site and the PR description's account of the reverted earlier attempt. Not re-litigated further per the investigation already on record in create_schema emits corrupted JSON field names under grammar-constrained decoding on retry (scenario 8b regression) #1926.

Recommendation: APPROVE

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

Review recommendation: APPROVE (self-approval blocked by GitHub — same account authored the PR). Full findings posted above. No blockers; net positive, safe to merge.

The review on PR #1929 traced that repair_leaked_special_token_keys's
collision guard checks against the live, mutating object on each loop
iteration rather than a frozen snapshot — correct by construction (the
first-processed corrupted key repairs cleanly, a second key that would
collide with it backs off untouched), but not covered by an explicit
test.

Adds a test with two distinct corrupted keys that both repair to the
same clean name within one object, asserting the first wins and the
second is left in its original form rather than overwritten or
discarded. Verified it actually catches the regression by temporarily
removing the collision guard and confirming the test fails, then
reverting.

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

malibio commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Address review

Addressed the review's one substantive suggestion: repair_leaked_special_token_keys's collision guard (checked live/mutating, not against a frozen snapshot) was correct by construction but had no explicit test for the same-pass two-corrupted-keys-collide case. Added leaked_special_token_repair_resolves_same_pass_collisions_without_data_loss, asserting the first-processed corrupted key repairs cleanly and a second key that would collide with it is left untouched rather than overwriting or discarding data. Verified it actually catches the regression — temporarily removed the guard, confirmed the test failed with the expected data-loss shape, reverted.

The other suggestion (scope: only the one observed leaked token, <|"|>, not all 11 strip_gemma_special_tokens handles) was explicitly marked "no change requested" by the reviewer itself — correctly evidence-scoped, not addressed further.

cargo test -p nodespace-agent --lib — 435 passed, cargo clippy --all-targets -- -D warnings clean. Pushed as 4e24bf49.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: One additive unit test, no production code changed, no logic altered — the fix itself was already reviewed and approved. Low-risk, straightforward addition per the skill's own criteria for skipping re-review.

Ready for merge, pending your go-ahead.

@malibio
malibio merged commit f4d5255 into main Aug 3, 2026
2 checks passed
@malibio
malibio deleted the issue-1926-schema-json-corruption branch August 3, 2026 04:19
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.

create_schema emits corrupted JSON field names under grammar-constrained decoding on retry (scenario 8b regression)

1 participant