Repository navigation
Studio: size a tool result against the room the thread has left - #9563
Conversation
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.
96ee554 to
fa60a7a
Compare
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.
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.
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Codex is clear at
Targeted and neighbouring suites: 1321 passed on the last run, and the branch is rebased on current main. |
What this looks like in the chat, measured on two isolated installsBoth sides are The scene loads a GGUF at a 4096-token window, turns code execution on, and asks for output far larger than the window: The notice under the tool card, BEFORETwo 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 installMeasured on the same servers that were photographed, reading each thread's stored messages:
Why the wasted call mattersThis is the merge-base install with Honest notes on the pair
|
The AFTER side, from the same rigSame two installs (merge base 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. 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:]))
Numbers from the same servers
The resume command here is the byte form rather than Two things about this pair worth stating
|



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:Reported against
unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_XLat a 4096 context: enable code execution, ask for a Flappy Bird saved togame.html, then ask for it back verbatim a few times. Eachcatis 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 incontext_window.pybesideprompt_budgetandretrieval_budget, and the tool loop now computes the spend for every call rather than only for retrievals. A result is sized againstprompt_budget * 0.99minus 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:
_MIN_PAGE_CHARSfloor 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.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:
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_filesskips, 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 anartifact://reference, Pi at 50KB or 2000 lines with aUse offset=N to continuehint, and OpenClaw at 8000 characters. OpenClaw has this same bug open as openclaw/openclaw#16574.Measured
The reported scenario, three prints of
game.htmlat a 4096 context: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.pyandtest_checkpoint_compaction.py.Scope and a known limit
Tools with no sandbox of their own, MCP,
web_search,edit_file,render_htmland 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
pythonandterminalpage, 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_charsalready consults, so this only affects paths that do not.test_without_a_tokenizer_the_estimate_alone_is_optimisticrecords it rather than leaving it to be discovered.