Skip to content

fix(agent): recover Gemma 4 tools, images, and restart cache - #106

Merged
Brooooooklyn merged 6 commits into
mainfrom
agent/fix-gemma4-agent-io
Jul 30, 2026
Merged

Brooooooklyn merged 6 commits into
mainfrom
agent/fix-gemma4-agent-io

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • recover canonical Gemma 4 tool calls when the model emits a valid nested restart inside a malformed outer tool block, while preserving raw output for diagnostics
  • attach standalone local image paths pasted into the interactive TUI as guarded ImageContent
  • make image-bearing paged-cache identity durable with a versioned SHA-256 payload digest, full 256-bit block keys, and explicit key-layout/preprocessing markers
  • persist and exactly restore Gemma 4 sliding-window image sidecars after process restart, then skip the vision tower when the cached prefix covers the complete image span
  • advertise image support from valid Gemma/Qwen vision metadata during model discovery while keeping the loaded native session authoritative
  • expose Gemma 4 thinking with its real minimal/high level map and support selectable thinking, canonical tool schemas, calls, responses, and structured errors in template-less checkpoints
  • seed the Gemma output parser when a post-tool prompt already opened the thought channel so truncated reasoning never leaks into visible text
  • keep audio and mixed-media cold recovery disabled and fail closed on partial, misaligned, changed, reordered, or corrupt media state

Root cause

Gemma 4 could sample a malformed outer tool block followed by a valid nested call:... restart. The parser treated every byte before the first argument brace as the tool name, causing dispatch of the malformed prefix instead of the intended tool.

Pi's clipboard flow stores a pasted image in a temporary file and inserts only its path into the editor. That path reached Gemma as plain text because no input transform upgraded it to an image attachment.

The cold tier could persist image-aware global KV blocks, but Gemma 4 skipped sliding-window sidecar capture for media turns. After restart, global layers could hit SSD while the out-of-pool sliding layers had no faithful state. Replaying expanded image placeholder token IDs cannot reconstruct vision embeddings, so image prefixes previously had to fall back cold.

Agent discovery also hard-coded local models as text-only and marked Gemma as non-reasoning. Template-less E2B checkpoints lacked selectable-thinking and tool-schema rendering. After a tool result, the canonical Gemma prompt continues inside an already-open thought channel; initializing the parser in ordinary message state exposed that reasoning as visible text.

Impact

Malformed Gemma restarts now dispatch the intended tool, including markers split across streamed chunks. Standalone absolute image paths from the interactive TUI become image content only after extension, magic-byte, size, and duplication guards pass.

A repeated Gemma 4 image prompt can reopen native SSD KV state after process restart. The caller still supplies the raw image so mlx-node can verify its digest, preprocessing identity, placeholder expansion, and positions before accepting the cache entry. Missing or malformed vision metadata, changed image bytes/order, incomplete sidecars, and corruption remain cache misses.

mlx agent --list-models now reports thinking and image support for capable Gemma checkpoints before weight loading. Template-less sessions can select thinking, call tools with real schemas, consume canonical tool responses, and keep pre-tool and post-tool reasoning separate from the final answer.

Cache accounting

A cache hit is capped at prompt_tokens - 1 because the final prompt token must be evaluated to produce next-token logits, then rounded down to the 16-token block boundary. Therefore a 786-token prompt reports 784 cached tokens. The real restart trace reported 960 cached out of 961 prompt tokens.

Validation

Combined PR #106 branch after cherry-picking the two PR #107 commits:

  • both transferred commits have patch IDs identical to their PR fix: recover Gemma 4 image cache and agent capabilities #107 source commits
  • parser integration review found the exact union of both PRs' tests: 40 unique tests, none lost or duplicated
  • cargo test -p mlx-core --lib gemma4 — 420 passed, 9 ignored
  • targeted agent model/local-image/run-agent suites — 41 passed
  • cargo fmt --all -- --check
  • git diff --check
  • yarn typecheck
  • yarn lint — passed with pre-existing warnings only
  • native arm64 addon rebuilt successfully in the combined worktree

Source-patch validation before transfer:

  • focused Gemma manual/tool/parser/seeded-truncation tests — 63 passed
  • focused agent discovery/config/stream tests — 64 passed
  • image cache identity tests — 10 passed
  • vision feature cache tests — 13 passed
  • cold cache reopen integration test — passed
  • process-restart gates — 3 passed
  • real release-addon mlx agent --trace image + Bash task across separate writer and restarted reader processes:
    • image OCR and the real Bash call both succeeded
    • sessions recorded high thinking, separate thinking parts, one parsed Bash tool call, and its real result
    • restarted reader reported cacheRead: 960 for a 961-token prompt
    • native trace recorded cold_restore_walk for 60 blocks, state=cold_sidecar, 960 primed tokens, zero replay tokens, and vlm_vision_tower_skip

Note

High Risk
Touches durable KV/sliding cache identity, multimodal prefix restore, Gemma tool/wire-format rendering, and session replay semantics; regressions could cause wrong cache hits, broken image sessions, or mis-routed tools/reasoning.

Overview
This PR hardens multimodal cold-cache identity and Gemma 4 session behavior so image prefixes, tools, and thinking replay correctly across restarts and agent flows.

Paged / image cache (Rust): Image-bearing block keys move from u64 hashes to versioned SHA-256 payload digests, with all four digest words plus placeholder position wired into per-block extra_keys, plus layout and preprocessing semantics markers. Hot lineage still uses a compact combined key; durable keys bind the full identity. Qwen vision cache keys follow the same digest type.

Gemma 4 model: Pure-image turns can capture and restore sliding-window cold sidecars only after global K/V finalize succeeds and only at checkpoints at or after the full image span; restored sidecars must exactly match the effective prefix (no partial install inside an image run). When the cached prefix covers the image span, the vision tower is skipped. Template-less rendering gains <|think|>, canonical tool declarations, in-turn tool responses, and tool-result deltas that resolve the function name from committed history (not opaque call ids). Prompt rendering records whether output starts inside an open thought channel so sync/stream parsers and promotion treat truncated post-tool reasoning as reasoning, not visible text.

Gemma 4 output parser: Supports prompt-seeded open channels and recovers nested call: restarts inside malformed outer tool bodies (stream + offline).

Agent / TS: Tests document media-held sendToolResult replay carrying reasoningContent / thinkingEnabled per historical turn vs current reasoningEffort, plus a local standalone image path input extension (guards, races, size caps). New integration tests assert image-aware KV + sliding objects survive cold-cache reopen and optional OS process restart with trace gates.

Docs: paged-cache.md describes the new image key ABI and stricter image sidecar semantics vs text-only optimization.

Reviewed by Cursor Bugbot for commit da91abc. Bugbot is set up for automated code reviews on this repo. Configure here.

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 50a3040a-dee1-434f-ac0a-a99bfe33cb11

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Brooooooklyn
Brooooooklyn marked this pull request as ready for review July 30, 2026 02:31
@cursor

cursor Bot commented Jul 30, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_d181bb7f-0d04-4e81-a171-9f9e0bb75a6e)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f52e8ea10a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@cursor

cursor Bot commented Jul 30, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_26fa73c6-827f-42b5-a3d1-cd3d88862b0c)

@Brooooooklyn Brooooooklyn changed the title fix(agent): recover Gemma4 tool calls and image inputs fix(agent): recover Gemma 4 tools, images, and restart cache Jul 30, 2026
@Brooooooklyn
Brooooooklyn force-pushed the agent/fix-gemma4-agent-io branch from 32f8f09 to 2f12a7b Compare July 30, 2026 11:25
@cursor

cursor Bot commented Jul 30, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_eb198af5-38b9-4042-8ab6-1627149aefd6)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2f12a7b719

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Brooooooklyn
Brooooooklyn force-pushed the agent/fix-gemma4-agent-io branch from 2f12a7b to cb99ab8 Compare July 30, 2026 12:35
@cursor

cursor Bot commented Jul 30, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_efdedc3f-6aaa-4f84-abf9-ffe1b24eb8d3)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cb99ab8079

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/lm/src/chat-session.ts Resolved
@cursor

cursor Bot commented Jul 30, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_4352c852-ba5b-41ed-9c07-9144e9029d89)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9084e14942

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@cursor

cursor Bot commented Jul 30, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_1a74e5d1-9fb7-43a2-8615-587c7fb453f6)

@Brooooooklyn
Brooooooklyn merged commit e6598c6 into main Jul 30, 2026
7 checks passed
@Brooooooklyn
Brooooooklyn deleted the agent/fix-gemma4-agent-io branch July 30, 2026 14:14
robert-johansson added a commit to robert-johansson/mlx-node that referenced this pull request Jul 30, 2026
…oad, mlx-node#106 Gemma4 tools/images/restart-cache

Merge-forward of mirror/upstream (91f232b) into our patched main.
Upstream delta since mlx-node#103:
  91f232b feat(cli): revision-aware mlx download model (mlx-node#104)
  e6598c6 fix(agent): recover Gemma 4 tools, images, and restart cache (mlx-node#106)

Conflict resolutions:
- packages/agent (3 TS files): kept our genmlx-provider extension + our
  genmlx-only test, added upstream's mlx-local-image-input extension (order:
  mlx-provider, genmlx-provider, mlx-local-image-input, ...); took upstream's
  richer gemma4 FamilyTraits (reasoning + thinkingLevelMap).
- crates/mlx-core auto-merged textually but broke the build: mlx-node#106 migrated the
  VLM image hash u64 -> engine::ImageCacheDigest, while our fork-only
  vlm_prepare_vision_continuation kept &[u64]. Migrated its signature to
  &[engine::ImageCacheDigest] (pure pass-through to vlm_prepare_vision_features;
  sole caller qwen3_5_moe already passes the digest type). Rebuild clean.
- nested mlx-sys/mlx gitlink kept ours (b55ff6e6).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
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