Skip to content

Studio: keep tool screenshots in compacting GGUF chats so the prompt cache stays warm - #18256

Merged
danielhanchen merged 7 commits into
mainfrom
studio-mcp-image-stepped-trim
Nov 18, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
studio-mcp-image-stepped-trim

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Fixes #18231

Problem

Tool screenshots (computer use, view_image, MCP image tools) were capped at the newest 8 pictures. Past the cap, the oldest picture was dropped on every new screenshot. That picture sits near the start of the chain, so every request after the 8th changed the prompt at the first image turn, and llama-server re-evaluated almost the whole conversation on every call. That is the 2 s to 10-30 s jump the report describes.

Fix

Compacting GGUF chats keep every screenshot. Studio's local llama.cpp chats compact by default (auto-compact on, context_overflow: "truncate_oldest"). The tool loop already re-fits the conversation before every request, with images priced. So a picture count adds nothing there except invalidating the prompt cache. With compaction on:

  • the live tool loop no longer drops screenshots, so every request extends the last one and the prompt cache stays warm;
  • once the window fills, the existing fit makes room, dropping old turns in chunks with its usual headroom;
  • the follow-up replay (promote_history), the KV admission estimate and the frontend upload keep every picture too, so a new message after a long chain still hits the cache. The upload stays under the existing 12 MB byte bound.

Everything else keeps a cap, now trimmed in steps. Chats with auto-compact off (context_overflow: "error") and external providers still cap at 8. Gemini, for example, drops pictures past 8, and without compaction nothing else would bound the prompt. Past the cap, pictures now drop 4 at a time instead of 1, so 3 of every 4 calls stay append-only. The kept count depends only on the history's picture count (stepped_keep), so the live loop, the replay and the frontend upload all keep the same pictures.

Replay decode is memoized. Replaying every screenshot would otherwise re-decode and re-encode each one with Pillow on every message, about 17 ms per 1008 px screenshot. A bounded memo (64 MB) of the normalized PNG lets a 40-screenshot replay take 5 ms instead of 669 ms once seen. The live loop decodes through the same function, so the first follow-up after a chain is already warm.

The local safetensors / MLX marker path is unchanged.

Evidence

A real llama-server (b12499, CPU, SmolVLM-256M Q8_0 + mmproj) running a 20-call screenshot chain built with each tree's code, then a follow-up message sent through the frontend bound and the backend replay. The numbers are prompt tokens llama-server had to evaluate (timings.prompt_n):

calls 9-20 evaluated calls that re-read the chain pictures at call 20 follow-up evaluated
main 15692 12 of 12 8 12 of 1543
this PR, compaction on 1964 0 of 12 20 12 of 3295
this PR, compaction off 4077 3 of 12 (calls 9, 13, 17) 8 12 of 1543

The real tool loop (generate_chat_completion_with_tools) over 40 screenshot calls in an 8k window, with compaction on: no errors, and the task message kept in every request. Every request was append-only until the window filled at 15 pictures. After that, the fit dropped old turns in chunks, one prefix break about every 5 calls. With compaction off, the stepped cap held 5 to 8 pictures.

Follow-up consistency, randomized: histories mixing computer and MCP tools, 1 to 8 images per result, about 6% SVG payloads and parallel turns of up to 3 calls. Each is run through the live loop's append_image_turn, then replayed through promote_history, once from the full history and once from what boundMcpImageEnvelopes uploads. Every case replays exactly the live loop's pictures: 500 of 500 capped and 150 of 150 uncapped, on both paths. On main, 659 of 800 did (results with more than 4 pictures or an SVG already drifted there).

Tests

  • test_llama_cpp_tool_loop.py: a compacting chain through the real loop keeps all 12 pictures and stays append-only; a non-compacting chain still steps 8, 5, 6, 7, 8.
  • test_gguf_admission_token_count.py: a compacting chat prices every replayed picture; a strict one keeps the cap.
  • test_mcp_images.py:
    • uncapped chain and replay;
    • the stepped_keep table, a stepped chain that stays append-only between drops, and replay that matches the loop;
    • parallel turns, result tails, SVG entries;
    • the PNG memo hit and its budget.
  • mcp-images.test.ts: an uncapped upload of every picture, the byte bound under uncapped, steppedKeep parity with the backend, a stepped upload that recounts to the loop's cut, parallel turns, and the non-raster sniff. The existing spare and byte-bound tests pass unchanged.

@danielhanchen danielhanchen self-assigned this Nov 18, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-18T16:42:01.703867Z 0fe9b3a Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: 0c2e992b79

ℹ️ 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 on lines +285 to +286
if images:
total += min(MAX_MODEL_IMAGES, sum(1 for image in images if _mime_is_bounded(image)))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Count live-admitted images when computing the replay step

When a parallel tool batch returns more than eight pictures, this per-result sum counts pictures that the live loop never admitted. For example, three parallel MCP results containing three valid images each produce eight images through append_image_turn, because _decoded_urls_per_result caps the whole batch at eight. This recount instead returns nine, so stepped_keep(9, 8) reduces the follow-up replay to five images. Consequently, a follow-up unnecessarily loses three previously visible screenshots and invalidates the GGUF prompt prefix that this change is intended to preserve. The replay count needs to reflect the live loop's batch-level admission limit, rather than only its per-result quota.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 73a4ba4: the replay count now caps each parallel turn at the cap (as the live batch admission does), and the frontend counts per turn and uploads exactly the pictures the loop admitted. A randomized check over 600 mixed histories (parallel turns, 1 to 5 images per result) replays the loop's pictures in every case.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 73a4ba44f7

ℹ️ 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".

messages, local = local, budget = max(0, MAX_TOTAL_MODEL_IMAGES - _reserved)
messages,
local = local,
budget = _budget if local else stepped_keep(_total, _budget),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Select surviving tails before applying the stepped replay budget

When replaying full, unbounded tool history, the smaller stepped budget can select different pictures from the live loop even when every image decodes successfully. For example, three successive MCP results containing 1, 4, and 8 images admit nine pictures live and retain five: the fourth image of the middle result plus the first four of the newest result. With the new budget of five, eligible_replay_images spends all four decode spares on the newest result, then admits only the first image of the middle result. Replay therefore substitutes an older screenshot and invalidates the prompt prefix. Selection needs to preserve the surviving tail of each admitted result rather than treating the stepped survivor count as a prefix-selection budget.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 12436f9: replay admission keeps the full budget and admits each result's whole window (up to 4), and only the final oldest-first trim applies the stepped count, as the live loop does. Regression test for the 1, 4, 8 case added; a randomized check over 800 histories with up to 8 images per result now replays the live loop's pictures in every case, from the full history and from the frontend upload.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Nov 18, 2026

@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: 12436f9748

ℹ️ 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".

if parsed is not None:
parsed[position] = images
if images:
batch += min(MAX_MODEL_IMAGES, sum(1 for image in images if _mime_is_bounded(image)))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Exclude sniff-rejected images from the stepped replay count

When an MCP result contains an unsupported image such as SVG, this MIME-length-only count includes it even though the live decoder admits no picture. For example, eight successive valid screenshots followed by one SVG leave eight pictures live, but replay now counts nine and trims the valid screenshots to five; the parent commit retained all eight. This unnecessarily removes usable visual context and breaks the prompt prefix even for entries that probably_decodable already identifies as unsupported, rather than only corrupt rasters that pass the sniff. Exclude those identifiable failures from the stepped count and mirror that accounting in the frontend planner, which currently also charges them.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 9eadaf3: the replay count skips images whose header plainly is not a raster (the same prefix list as probably_decodable), and the frontend planner mirrors that sniff. Eight screenshots followed by an SVG result now replay all eight; regression tests on both sides.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 2d944aaf89

ℹ️ 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".

@danielhanchen danielhanchen changed the title Studio: trim tool screenshots a step at a time so the GGUF prompt cache stays warm Studio: keep tool screenshots in compacting GGUF chats so the prompt cache stays warm Nov 18, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 0fe9b3a38d

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 22cd90b into main Nov 18, 2026
@danielhanchen
danielhanchen deleted the studio-mcp-image-stepped-trim branch November 18, 2026 17:07
danielhanchen added a commit that referenced this pull request Nov 18, 2026
## Summary

Six tests in `tests/saving/test_save_method_lora_routing.py` fail on
main in every Core job (HF default, 4.57.6 and latest):

```
NameError: name '_release_nf4_dequant_cache' is not defined
FAILED test_unsloth_save_model_guards_a_respelled_merged_4bit[merged-4bit]   (and 2 more params)
FAILED test_the_adapter_save_forwards_a_real_safe_serialization
FAILED test_an_adapter_push_survives_a_transformers_that_dropped_the_keywords
FAILED test_an_adapter_push_still_passes_every_keyword_a_transformers_4_accepts
```

Seen on the staging runs for #17742 and #18256, both on current main.

## Cause

#18285 has `unsloth_save_model` call `_release_nf4_dequant_cache()`
first, so a merge gets back the memory the training-time NF4 dequant
cache held. That is correct. The helper is deliberately module-level,
because `unsloth_save_model` forwards its own `locals()`.

This test does not import `unsloth/save.py`. It execs the named
functions into a namespace that `_load()` builds, pre-stubbing the
helpers every save path calls (`_unmerge_flags_on_error`,
`lora_relative_to_original_base`, and so on). The new helper was not in
that namespace.

## Fix

Add `_release_nf4_dequant_cache` as a no-op default in `_load()`, next
to the other always-called save helpers. None of these fixtures has a
dequant cache to free.

## Verification

`tests/saving/` without the model-loading `test_unsloth_save.py`:

| Tree | Result |
|---|---|
| main | 7 failed (the 6 above plus
`test_torchao_remote_code_consent.py::test_compressed_and_gguf_lora_paths_drop_auto_map_trust`)
|
| this branch | 1 failed (the same torchao test) |

The torchao test fails identically on both sides on this host and does
not fail in CI, so it is unrelated. `test_save_method_lora_routing.py`
passes 80 out of 80. ruff is clean.
danielhanchen added a commit that referenced this pull request Nov 18, 2026
…18373)

## Summary


`studio/backend/tests/test_view_image_tool.py::test_invalid_large_and_pixel_bomb_files`
fails on main when it runs after the other tests in its file:

```
assert 'megapixel limit' in 'Opened image.\n__MCP_IMAGES__:[...]'
```

Seen in "(Python 3.13, rest)" on the staging run for #17742, which is on
current main. Run alone, it passes.

## Cause

#18256 memoizes the normalized PNG data URL per payload, so a replayed
screenshot is not re-decoded on every message. Only images that passed
the size checks are stored. `MAX_IMAGE_PIXELS` is a constant in
production, so a memo hit is always within budget. That code is correct.

The test lowers `mcp_images.MAX_IMAGE_PIXELS` at runtime, for the same
`image.png` that earlier tests in the file had already viewed. The memo
returned the earlier result without reaching the pixel check.

## Fix

Test-only: give the budget check an empty memo (`_PNG_MEMO` and
`_png_memo_chars`, restored by monkeypatch), so it exercises the check
rather than the cache.

## Verification

| Tree | `test_view_image_tool.py` in file order |
|---|---|
| main | 1 failed, 30 passed |
| this branch | 31 passed |

The test also passes on its own on this branch. ruff is clean.
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.

[Bug] KV cache invalidation after ~8 computer use calls — MAX_TOTAL_MODEL_IMAGES = 8 in mcp_images.py

1 participant