Skip to content

Studio: size a tool result against the room the thread has left - #9563

Merged
danielhanchen merged 55 commits into
mainfrom
studio-tool-result-room
Aug 23, 2026
Merged

danielhanchen merged 55 commits into
mainfrom
studio-tool-result-room

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 23, 2026 •

Copy link
Copy Markdown
Member

The problem

A tool result is capped at a share of the window, and that share never falls as the conversation fills, so the last result before an overflow is allowed exactly as much room as the first. _result_char_budget() returns:

min(_MAX_OUTPUT_CHARS, max(_MIN_PAGE_CHARS, ctx * 4 * _PAGE_CONTEXT_SHARE))
context result cap roughly, as dense tokens share of the window
4096 5,734 chars ~1,911 47%
8192 11,468 chars ~3,822 47%
32768 16,000 chars ~5,333 16%

Reported against unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_XL at a 4096 context: enable code execution, ask for a Flappy Bird saved to game.html, then ask for it back verbatim a few times. Each cat is individually under the cap, and they accumulate until the turn cannot be served. Nothing downstream recovers, because the fit protects the newest turn and so may not drop the very result that does not fit. _page_char_budget() already describes this failure in its own docstring.

The tool loop does already price a result against the room that is left, but only for the conversation search, because the check is gated on accepts_kwarg(execute_tool, "conversation_budget_tokens") and that is the one tool advertising it. Code execution and file reads never reach it.

The change

tool_result_budget() lands in context_window.py beside prompt_budget and retrieval_budget, and the tool loop now computes the spend for every call rather than only for retrievals. A result is sized against prompt_budget * 0.99 minus what the thread already costs.

Against the prompt budget rather than the raw context length: a result sized to fill the physical window leaves the prompt fitting and nothing to answer in, which is the reserve-missing case #9442 already has to rescue. Room for the reply is not room for the result.

Two things the budget has to cover beyond the body, both found by the tests rather than by reading:

  • The _MIN_PAGE_CHARS floor that keeps a result worth reading now yields when the room is smaller than it. Unchanged, it hands back 2,000 characters against 30 tokens of room, which is the overflow the budget exists to prevent.
  • The truncation notice is reserved for rather than appended free. A budget spent entirely on the body overshoots by the notice every single time, and at zero room the notice is the whole message. That alone was still 3,460 tokens against a 3,072-token budget after the main fix was in.

Truncated output is no longer a dead end

The full result is written into the session sandbox and the notice names the command that resumes it:

... (truncated to 3319 chars for the model; showing lines 1-42 of 500, 40000 chars
total. Full output saved to .unsloth_tool_output/ab12ef34.txt -- continue with:
  sed -n '43,84p' .unsloth_tool_output/ab12ef34.txt)

The sandbox persists between calls and the model already has the terminal, so this is reachable rather than advice. The spill lives in a dot-directory, which _snapshot_workdir_files skips, so it never shows up as a file the model created or earns a download card. Spills are pruned to the newest 20.

This follows what the other terminal agents do for the overflow, though none of them size the cap against remaining room: opencode caps at 2000 lines or 50KB and spills to ~/.opencode/data/tool-output/, Oh My Pi at 3000 lines or 50KB with a rolling tail and an artifact:// reference, Pi at 50KB or 2000 lines with a Use offset=N to continue hint, and OpenClaw at 8000 characters. OpenClaw has this same bug open as openclaw/openclaw#16574.

Measured

The reported scenario, three prints of game.html at a 4096 context:

tokens spent 3,072-token budget
before 4,821 over
after 3,051 fits

Tests

studio/backend/tests/test_tool_result_fits_window.py, 17 cases: the budget shrinking as the thread grows, a full thread getting nothing rather than a floor, the reply reserve being kept, the floor yielding to a smaller room, an unpriced call behaving exactly as before, the hint naming a line that really resumes the content, one enormous line still being cut rather than dropped, the spill staying out of the created-files card, and the reported scenario with its control.

Reverting the room awareness fails three of them, including the reported scenario, so they are not vacuous.

451 pass across this file plus test_web_page_cap_fits_window.py, test_context_overflow_truncation.py, test_llama_cpp_tool_loop.py, test_external_tool_truncated_and_budget.py, test_hosted_result_replay.py, test_conversation_recall_injection.py and test_checkpoint_compaction.py.

Scope and a known limit

Tools with no sandbox of their own, MCP, web_search, edit_file, render_html and the two search tools, get the room-aware cap but no spill file and so no paging. That needs a server-side handle and is deliberately not in this change.

Only python and terminal page, and only they need to: they are the pair that prints a file back verbatim, which is the reported case. Paging also needs a sandbox the chat has to itself. A project's chats share one, and every sibling chat's model has a terminal in it, so a spill there would be output one chat never showed the next: in a project, and for a call with no session of its own, a large result is truncated with a notice and no continuation.

With no tokenizer available the room is still converted to characters at the four-per-token English rate, so genuinely dense output can overspend by about a third. Every local GGUF path has a tokenizer, which _exact_prefix_chars already consults, so this only affects paths that do not. test_without_a_tokenizer_the_estimate_alone_is_optimistic records it rather than leaving it to be discovered.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 23, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
danielhanchen and others added 9 commits August 23, 2026 16:44
When the rename into a detached name fails, the rmtree that stands in for it
removes just as much of the tree, and returned without dropping the record.
Every chat deleted down that path left its record behind for good, which is
the leak the record deletion was added to stop.
The stamp is taken a moment before the content is read, and this runs in the
sandbox's own directory: in between, tool code can put a symlink at the name,
or a FIFO, or a device. A plain open follows the first and blocks forever on
the others, and both callers, the prune and chat deletion, run synchronously
with no timeout above them.

The digest now opens O_NOFOLLOW and O_NONBLOCK, checks S_ISREG through the
descriptor it will read, and refuses anything that is not the size the record
remembers, so a file swapped for an enormous one is rejected rather than
hashed. Reverting the change does not fail the new tests, it hangs them.
…ted tool calls

The spill prune moved a recorded file to a private name before deleting it, so the
inode it verified is the inode it deletes. A sandbox process that replaced the name
with a directory first had that directory moved instead, and os.link cannot put a
directory back, stranding the user's data under a hidden name. Nothing but the
regular file the record remembers is moved now, checked through a descriptor, and
the restore falls back to reversing the rename when the name is free again.

A tool call rejected by the safety analyzer returned before it reached _truncate.
The analyzer names every occurrence it found, so 400 repetitions of one flagged
construct returned 10,875 characters whole, which is the overflow the budget exists
to prevent. The rejection paths and the exception returns are capped like any other
result.
…nothing could measure

tool_result_budget held back _RESULT_NOTICE_RESERVE before the result's size was
known, but a result that fits carries no notice. Near the limit that cut results
that would have fitted whole and spent more of the window doing it: 200 tokens of
room and a 100-token result left 72 for the body and appended ~70 tokens of notice
about the 28 that were dropped. The reserve is charged by _truncate at the point a
cut is certain, which also retires the per-result reserve the batch callers passed.

_dense_char_limit applied the unmeasured margin only when no counter was exposed,
not when the counter could not measure. A backend whose probe returns nothing left
_exact_prefix_chars on the four-characters-per-token estimate, so base64 or minified
JSON could spend the room twice over. _text_token_cost had the same shape, swallowing
a None as an exception and then pricing at the English rate.
The native loop charged every user and assistant turn the English four characters
per token and doubled only the tool results. Measured with Qwen3 over 16-20k
character samples: base64 1.35 characters per token, hex 1.13, minified JSON 2.75,
against prose at 3.27 and Python source at 4.38. A pasted blob was priced at about a
third of what it costs, and this path has no exact count and no rolling fit, so the
overstated room went straight into the next result.

estimate_messages_tokens_conservative charges unbroken runs of 64 or more non-space
ASCII characters at two per token and leaves everything else alone. Per run, so a
blob pasted into a sentence is priced as a blob; 64 because base64 is wrapped at 76;
two rather than one so no turn is priced above what it measured.
The spill path encoded the whole result to hash it and encoded it again to cut it,
keeping at most _SPILL_MAX_BYTES of the second. This runs on the output that did not
fit, so a large one is the ordinary case: a cat of a file the model just wrote put
two more full copies through memory at the point the result was already in hand.

_digest_and_head encodes a megabyte at a time, hashes each chunk, counts the bytes
and retains only the first _SPILL_MAX_BYTES of them. UTF-8 encodes one code point at
a time, so the byte stream and the content-addressed name are unchanged.
…gnature

The conservative estimate prices every message it is handed, results included, so
adding a separately priced result total on top charged those messages twice, and text
already at a token per character at two. A thread holding one sizable earlier result
reported no room while it still had plenty. Tool messages come out of the thread
estimate and are priced once, with all of their ASCII at two characters per token
rather than only their unbroken runs: a result is hexdump, ls -l or a stack trace as
often as it is a blob, and those carry spaces.

The rebase also brings main's token counter, which takes a budget as a second
argument, so the fixtures in this file take one too.
@danielhanchen
danielhanchen force-pushed the studio-tool-result-room branch from 96ee554 to fa60a7a Compare August 23, 2026 16:57
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 23, 2026 17:12
A tool result is swept for control markup before it is sent (#7066), and the sweep
costs tokens: a live <|eot_id|> is one special token in the raw text and several
ordinary ones once it has been broken up. The fit measured the raw prefix, so a
result full of markers fit the room here and did not fit the prompt that followed.

The counter sweeps each chunk before rendering it, through the same helper and the
backend's own markup profile, so the measurement and the request cannot disagree.
The prefix lengths it returns still index the raw text.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Two things were added to a result after it had been measured. The loop appends
TOOL_ERROR_NUDGE to a result opening with a TOOL_ERROR_PREFIXES entry, once per
failed call in a batch, and _defuse_sentinels inserts a space into every line
opening with a frontend marker. Either can put an admitted result past the room it
was admitted against.

_appended_by_the_loop reserves the nudge in tokens, and only for the results that
will carry one, since a reserve taken from every result spends room the thread has.
The defusing runs before the fit, so the measured text is the replayed text and the
spill holds what the continuation command will read.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 200648d249

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

Copy link
Copy Markdown
Member Author

Codex is clear at 200648d24, after eight rounds on this branch. Every item was a real one and every one has a regression test that fails with its fix reverted:

  • the prune moved things it could not put back (a directory or FIFO the sandbox left at a recorded name), so it now verifies through a descriptor before it renames anything and reverses the rename when a hard link cannot restore it
  • a tool call rejected by the safety analyzer returned before it reached the cap, and 400 repetitions of one flagged construct measured 10,875 characters
  • the truncation notice was reserved before the result's size was known, so a result that fit was cut and then cost more of the window than it would have whole
  • a counter that could not measure was trusted as though it had, skipping the margin that exists for exactly that case
  • a native turn holding a pasted blob was priced at the English four characters per token; measured with Qwen3, base64 is 1.35 and hex 1.13
  • and then priced twice, once by the thread estimate and again as a result
  • the spill encoded the whole result twice to keep at most 8 MB of it
  • the fit measured the raw text while the request path sweeps control markup into it first
  • the tool-error nudge and the sentinel defusing were both appended after the measurement

Targeted and neighbouring suites: 1321 passed on the last run, and the branch is rebased on current main.

@danielhanchen

Copy link
Copy Markdown
Member Author

What this looks like in the chat, measured on two isolated installs

Both sides are install.sh --local builds: BEFORE is this PR's merge base 15b9102c0, AFTER is the head 200648d24. A UI change only exists in a build made from that tree, so one Studio with a checkout between shots would keep serving the old bundle.

The scene loads a GGUF at a 4096-token window, turns code execution on, and asks for output far larger than the window: base64 /dev/urandom | head -c 120000, 120,000 characters of dense ASCII. Then it reopens the thread, which is when the card stops showing the live stdout stream and falls back to the result the MODEL was actually given.

The notice under the tool card, BEFORE

before notice

... (truncated to 2000 chars for the model; 108894 chars total. The full output is
not retained here; any files the code wrote persist in the working directory.)

Two things are wrong with that, and they are the two things this PR fixes. The size is a share of the WINDOW rather than of what the conversation has left, so it is the same number whatever else is in the thread. And what was cut is simply gone, so the model's only route to the rest is to run the command again.

AFTER, from the same scene on the head install

... (truncated to 2000 chars for the model; showing lines 1-527 of 20001, 108894 chars
total. Full output saved to .unsloth_tool_output/f6351f5ead9a.txt, and any files the code
wrote persist in the working directory -- continue with:
  sed -n '528,1054p' .unsloth_tool_output/f6351f5ead9a.txt)

Measured on the same servers that were photographed, reading each thread's stored messages:

BEFORE (15b9102c0) AFTER (200648d24)
result chars, successive calls 2163, 2163 2294, 2045
sized against a share of the window the room left, so it falls as the thread fills
spill_hint_present false, false true, true
resume_hint_present false, false true, true

Why the wasted call matters

before thread

This is the merge-base install with Qwen3.6-35B-A3B-GGUF:UD-Q4_K_XL at 4096, the model and window from the report. Asked for the last 8 characters of the output, the model runs the command, gets a result cut off with nowhere to go, and re-runs the whole 120,000 character job with print(data[-8:]) to recover 8 characters. On the head build the notice names the file and the exact sed -n that reads the next page, so the second call is a read rather than a re-run.

Honest notes on the pair

  • The AFTER screenshot is still being produced and I will add it here rather than swapping this comment's numbers around. The figures above are from a completed two-install run of the same scene, so both columns are measured on real builds; what is missing is the picture of the right-hand one.
  • The cut BEFORE lands on 2,000 characters rather than the 5,734 a raw window share would give, because the dense-text correction already on main pulls the share down to the floor. Worth knowing if you are checking the arithmetic against the constants.
  • Nothing was refused on either side at this window. Three results of about 2,000 characters are only ~1,500 tokens, so the irreducible turn from the report needs a per-turn result far larger than the merge base admits. This pair shows the sizing and the paging hint, not the refusal.

@danielhanchen

Copy link
Copy Markdown
Member Author

The AFTER side, from the same rig

Same two installs (merge base 15b9102c0 against head 200648d24), same window, same question: 120,000 characters of random base64, then "reply with the LAST 8 characters of its output". Both sides ran at temperature 0 with thinking off and tool approval set to Run automatically, on Qwen3.6-35B-A3B-GGUF:UD-Q4_K_XL at 4096.

before after

Left, merge base. The result comes back cut with nothing to follow, so the model re-runs the whole job to get its 8 characters:

import os, base64
data = base64.b64encode(os.urandom(90000)).decode()[:120000]
print(data[-8:])

That is worse than a wasted call. os.urandom returns different bytes the second time, so 94V9V0G+ is the tail of a blob nobody asked about. The answer looks right and is not.

Right, this PR. The notice names where the output went, and the model reads it instead of regenerating it:

with open('.unsloth_tool_output/1f328232960f.txt', 'r') as f:
    content = f.read()
    print(repr(content[-8:]))

'oC6TpWC\n', which is the tail of the blob it was actually given, and the answer says so.

Numbers from the same servers

BEFORE AFTER
tool results in the thread 4 7
result chars 268, 268, 2163, 9 268, 2315, 8, 109, 268, 12, 12
spill_hint_present false on every result true on the capped ones
resume_hint_present false on every result true
the notice's own tail "The full output is not retained here" "Full output saved to .unsloth_tool_output/1f328232960f.txt ... continue with: tail -c +2001 .unsloth_tool_output/1f328232960f.txt | head -c 2000"

The resume command here is the byte form rather than sed -n, because the cut landed mid-line: a line number would name the NEXT line and skip the remainder of the one the model had already started reading.

Two things about this pair worth stating

  • The first tool result on BOTH sides is 268 characters of bash: fork: retry: Resource temporarily unavailable. The box was under fork pressure while this ran, so the first terminal call failed on each side and each model fell back to python. It is symmetric and it is not this PR, but it is in the picture and I would rather name it than have it read as a difference.
  • The earlier comment predicted the sizes would shrink turn by turn. That is not what this pair shows, because the model made one large call rather than several: what it shows is the cap being applied and the paged file being READ, which is the behaviour the change exists to produce.

@danielhanchen
danielhanchen merged commit 48cdec1 into main Aug 23, 2026
48 checks passed
@danielhanchen
danielhanchen deleted the studio-tool-result-room branch August 23, 2026 23:53
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