Repository navigation
Studio: measure a dense tool result instead of estimating it, and never raise a configured cap - #9421
Conversation
|
Codex Review: Didn't find any major issues. 🎉 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 Review: Didn't find any major issues. You're on a roll. 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". |
|
Confirmed both paths are still live on main: tools.py:11705 raises a configured UNSLOTH_TOOL_RESULT_MAX_CHARS above what the install asked for, and the flat ASCII rate in _dense_prefix_chars lets base64 and hexdump output exceed its promised share. Will get this reviewed. |
… a configured cap
The exact-fit loop measured three prefixes and then returned a fourth nobody priced. Proportional shrinking assumes the retained prefix keeps the average density of the whole, which is false for the input this change exists for: with a dense head and a sparse tail every cut removes only cheap prose, so the retained prefix gets denser and each pass gains less than it asked for. Measured with the real tokenizer on 2500 characters of base64 followed by English, in a 5120 window with a 1792 token share: the three passes land at 2570, 2221 and 2066 tokens and the function returns 3497 characters costing 1978 tokens, 110 percent of the share. That is the irreducible overflow this change was meant to prevent, recreated. Every returned value is now a measured fit, the caller's estimate when nothing could be measured, or the floor. So that the floor stays a rare fallback rather than the usual answer, the shrink step also takes a secant step off the last two measurements, which prices the tail that was CUT rather than the whole prefix, and takes the min with the proportional step so it only ever shrinks faster. Strict progress is forced, so the loop still terminates, and the readable floor is never breached. Same input now returns 2331 characters at 1696 tokens, 95 percent of the share. The cost is up to two more counter round trips, and only for results still over budget after three passes. English returns on the first pass as before.
The result-budget probe priced a standalone tool message, which the bundled Gemma-4 templates skip entirely (gemma-4.jinja:232), so on that model family the exact count returned template framing and the whole estimated prefix was returned unmeasured: 7,168 characters of base64 at 5,201 real tokens against a 1,792-token share. Price a user turn instead, the one role every template checked renders, and refuse a count that does not grow with the chunk.
f1feacd to
abb286c
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: abb286c3a1
ℹ️ 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".
| # count that is not the chunk. Left IN the total rather than subtracted -- 8 tokens on | ||
| # Qwen3 and 11 on the Gemma-4 templates, under 1% of a 1,792-token share, and the real | ||
| # tool turn pays its own framing anyway, so counting it errs toward a smaller result. | ||
| framing = _rendered("") or 0 |
There was a problem hiding this comment.
Stop probing after the framing count fails
When llama-server is loaded but its counting endpoints are stalled or unavailable, _rendered("") can already consume the full HTTP timeout and return None, but coercing that failure to 0 causes _count to repeat the same request for the payload. Since count_chat_tokens may wait 10 seconds on both /apply-template and its /tokenize fallback (llama_cpp.py:25858-25941), truncating one completed tool result can add roughly 40 seconds before falling back to the estimate. Preserve the framing failure and make the returned counter fail immediately instead of retrying the unavailable service.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed the mechanism, rejecting on impact. framing = _rendered("") or 0 (tools.py:11839) does coerce the failure to 0, _count then calls _rendered(chunk) again, and count_chat_tokens at strict = False returns 0 rather than raising (llama_cpp.py:25936-25939), so nothing carries the first failure forward. The cost is worse than stated too: httpx.Client(timeout = 10) is per-operation, not a total budget, and a non-strict call falls through /apply-template to the /tokenize fallback, so one failed count is ~20s and the pair is ~40s. Verified the call count directly against the module: a counter that returns 0 and one that raises both produce exactly 2 invocations, with content lengths [0, 7168].
Not changing it. On this path both failures land on return chars, the caller's own estimate, so the tool result is byte-identical either way: nothing is mis-truncated, dropped or corrupted, and there is no crash. It does not hang anything either, since execute_tool runs on a worker thread (tool_stream_exec.py:171-176) with heartbeats every TOOL_HEARTBEAT_INTERVAL_S = 10.0s, so the event loop is free and the SSE stream cannot idle out. And the condition is a server whose counting endpoints are stalled, which is a session that is already failing: the generation request that consumes this result runs _fit_with_instruction_pins against the same endpoints. The same blocking non-strict counter is already handed to execute_tool on main at llama_cpp.py:25281, so this is not something the change introduces.
Making the framing probe lazy is a fair optimization and would remove the second probe, but that is a performance change on a healthy server, not a correctness fix, so it does not belong in this PR.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: abb286c3a1
ℹ️ 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 spent is None: | ||
| return chars # nothing to measure with; the estimate stands, as before |
There was a problem hiding this comment.
Avoid returning an unverified shrink after counting fails
If the first pass successfully measures an oversized prefix and a later llama-server request transiently returns no count, chars is no longer the caller's estimate—it is an unverified proportional/secant shrink. For mixed output such as a dense prefix followed by prose, the preceding comments and test document that this shrink can still exceed token_budget; returning it here can therefore recreate the irreducible newest-turn overflow this function is intended to prevent. Only use the original estimate when no measurement has succeeded; after a successful over-budget measurement, fall back to a conservative verified value or the floor when a subsequent count fails.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The mechanics are right and the severity is nil, so no change. chars only ever decreases (tools.py:11914, chars = min(fitted, chars - 1)), so whatever line 11897 returns on pass 2 or later is strictly SMALLER than the plain estimate the same line returns on pass 1 -- and that estimate is what main returns unconditionally. Measured over this PR's own mixed shape (2,500 chars of base64 at 1.376 chars/token then prose at 4.2, ctx 5120, share 1,792 tokens), failing at each pass in turn:
fail after 0 good passes: 7168 chars -> 2928 tok (163.4%) the plain estimate, == main
fail after 1 good pass: 4370 chars -> 2262 tok (126.2%) the case you describe
fail after 2 good passes: 2350 chars -> 1707 tok ( 95.3%) converged
floor (_MIN_PAGE_CHARS): 2000 chars -> 1453 tok ( 81.1%)
Monotonically non-increasing in successful passes and always at or below the estimate, so the function cannot recreate anything main did not already produce. It can only stop improving early, which is a conservatism gap rather than a correctness defect. The return _MIN_PAGE_CHARS paths cannot raise the caller's answer either, since min(max_chars, max(_MIN_PAGE_CHARS, fitted)) at 11942 would have done the same regardless.
Reachability is the strongest part of the claim and it does hold: it needs pass 1 to succeed and pass 2+ to fail, and the realistic trigger is a model unload or swap between passes, because count_chat_tokens returns 0 immediately for non-strict when not loaded (llama_cpp.py:25810-25814). A merely stalled server fails pass 1 too and yields main's behaviour.
The fix you describe, tracking measured and returning _MIN_PAGE_CHARS if measured else chars, was considered and deliberately not applied: it never touches the healthy path, but it trades 'sometimes returns 126% of the share' for 'sometimes collapses to the 81% floor', so one transient blip after a single good pass would cut a 4,370-character result to 2,000. That is more aggressive truncation of real model-visible content, bought to close a gap that never regresses anything.
Conceded: the comment at 11890-11892 calling 1,978 tokens against a 1,792-token share 'the irreducible overflow this budget exists to prevent' is loose in the same direction, since 110% of a SHARE is not irreducible. Our wording invited the reading.
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! 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". |
The comment claimed about a megabyte on the grounds that no prefix exceeds _MAX_PAGE_CHARS. That is only true of a fetched page. A tool result's prefix is bounded by min(UNSLOTH_TOOL_RESULT_MAX_CHARS, ctx * 4 * _PAGE_CONTEXT_SHARE), and _env_int accepts any positive integer, so a large configured cap on a large window makes a single prefix enormous and 64 entries multiply it. Measured on this path: a 1,000,000-character cap on a 262k window caches 733,971 characters from ONE result, and eight results held 5,871,768 characters, nearly six megabytes of ASCII and up to four times that for non-ASCII. The bound is now enforced rather than asserted, and an oversized prefix is skipped rather than stored. The baseline is zero characters, so the entry that earns the most is never the one squeezed out. Kept the keys as the measured prefixes rather than switching to a digest. A digest would make the bound trivial but would make output identity probabilistic instead of provable, and provable is this change's whole claim. Re-fuzzed against the modified insert path: 1,230 generated tool results through both this code and unslothai#9421's merge commit, zero differences with the cache live, with it disabled, and with the bound cut to 3,000 characters and 3 entries so most inserts are refused. The answer never depends on what was cached. Also trimmed the comments this PR added, keeping the reasoning that is load bearing and cutting the restatements.
…e per result (unslothai#9541) * Pay for the tool result framing probe once per model, not once per result The probe unslothai#9421 added is eager and uncached: the framing baseline is priced before the count that would decide whether it is needed, and every measurement is thrown away as soon as it is read. Each count_chat_tokens is two llama-server calls, /apply-template then /tokenize, over a fresh connection. Three round trips that cannot change an answer, removed: - An estimate already at or below the readable floor is the answer whatever the tokenizer says, because _dense_char_limit clamps with max(_MIN_PAGE_CHARS, ...) and nothing _exact_prefix_chars can return from there is above the floor. That is the small-window case, and it was measured anyway. - The baseline only decides whether a count that came in OVER budget is a real measurement. A result that fits on its first count never reaches that question, and every English result fits on its first count. - The baseline is the same number for every result the process truncates, and a measured count is a pure function of model, template, window and chunk. Both are now cached per model, keyed on the GGUF's resolved path, inode and size plus the template override, so a reload cannot read back the previous model's numbers. A backend that can name neither its model nor its GGUF is not cached. Output is unchanged. 1,230 generated tool results across 11 tokenizer shapes, 10 windows and 8 failure modes were run through both this code and the merge base's in one process: zero differences in _dense_char_limit or in the full _truncate string, with the cache live and with it disabled. * Key the probe cache on the resident llama-server, not on the managed fields The managed fields cannot describe the effective chat template. User extra args are appended verbatim after Studio's own flags and llama.cpp is last-wins, so an install running --chat-template or --chat-template-file in its extra args renders through a template _chat_template_override never sees. Reload the same GGUF into the same window with only those args changed and model_identifier, _gguf_load_identity, _chat_template_override and the window all still match while the rendering does not, so a prefix could be priced by a template that is no longer serving it: an oversized tool result accepted, or a fine one over-truncated. Key on the process instead. is_loaded is 'self._process is not None and self._healthy' and args reach llama-server only on its command line, so any change to them is a new process by construction and nothing survives a reload, including flags nobody has enumerated yet. The extra args join the key as well, so the gap is closed directly and not only as a consequence, and the content fields still have to agree in case a pid is recycled. No process is no cache. An unhashable identity field now disables the cache rather than raising. Re-fuzzed against the modified code: 1,230 generated tool results through both this code and unslothai#9421's merge commit, zero differences in _dense_char_limit or the full _truncate string, with the cache live and with it disabled. Round trips unchanged. Four tests added, each failing on the previous key. * Bound the probe cache by characters held, not only by entry count The comment claimed about a megabyte on the grounds that no prefix exceeds _MAX_PAGE_CHARS. That is only true of a fetched page. A tool result's prefix is bounded by min(UNSLOTH_TOOL_RESULT_MAX_CHARS, ctx * 4 * _PAGE_CONTEXT_SHARE), and _env_int accepts any positive integer, so a large configured cap on a large window makes a single prefix enormous and 64 entries multiply it. Measured on this path: a 1,000,000-character cap on a 262k window caches 733,971 characters from ONE result, and eight results held 5,871,768 characters, nearly six megabytes of ASCII and up to four times that for non-ASCII. The bound is now enforced rather than asserted, and an oversized prefix is skipped rather than stored. The baseline is zero characters, so the entry that earns the most is never the one squeezed out. Kept the keys as the measured prefixes rather than switching to a digest. A digest would make the bound trivial but would make output identity probabilistic instead of provable, and provable is this change's whole claim. Re-fuzzed against the modified insert path: 1,230 generated tool results through both this code and unslothai#9421's merge commit, zero differences with the cache live, with it disabled, and with the bound cut to 3,000 characters and 3 entries so most inserts are refused. The answer never depends on what was cached. Also trimmed the comments this PR added, keeping the reasoning that is load bearing and cutting the restatements. * Retain only template-rendered counts, and evict rather than refuse Two ways the cache was worse than it looked. A plain-text fallback was retained as if it were a measurement. With strict=False a failed /apply-template still returns a tokenized count, but one that drops role markers and special tokens, so it prices a prompt the model will never be sent. The count is still USED, exactly as before: it tokenizes the real bytes, which is what catches dense ASCII, and the estimate it would otherwise fall back to undercharges base64 several fold. It is simply not kept, because like a failure it is a property of the moment rather than of the text. The strict attempt is made at most once per result, and not at all when nothing would be retained anyway. A template that will not render is not going to start mid-result, so asking again would spend round trips on a settled question. A template outage costs one extra attempt for the first probe rather than one for every probe: measured 3 calls at the merge base, 6 with a naive per-probe strict, 4 as written. A healthy template pays nothing, since strict and non-strict are the same two llama-server calls when /apply-template works, and a server that is down entirely is unchanged at 2. A full cache refused every later entry instead of evicting. Most tool results are one-offs, so the first 64 distinct prefixes froze the cache on text nothing would ask about again. Worse, the baseline is only priced when a count comes in OVER budget, so a process that handled 64 results that FIT first locked it out for good: measured, every later dense result then paid 4 counter calls and 8 HTTP again, exactly the merge base's cost, for the life of the process. Now least-recently-used entries are evicted and the baseline is pinned, so the same sequence settles at 3 calls. Re-fuzzed against the modified code, with the corpus extended by two degraded template modes so the fallback path is actually exercised: 0 mismatches with the cache live, with it disabled, and with the bound cut to 3,000 characters and 3 entries so eviction runs on nearly every insert. * Synchronise the shared probe cache Tool calls run in worker threads -- tool_stream_exec.stream_tool_execution runs each invocation in one -- so concurrent chats reach this process-global cache at the same time. A bare dict assignment is atomic under the GIL, which is all the cache did until the LRU landed, but the LRU touch and the eviction loop are read-then-mutate sequences and are not. Reproduced through the real _dense_char_limit path, 24 threads over a 3-entry cache with an aggressive switch interval: 69 exceptions out of 12,000 truncations. KeyError from popping a key another thread had just evicted, KeyError from deleting a victim already taken, and RuntimeError on a dictionary changing size during iteration while choosing a victim. None of them are caught on the way out of _truncate, so this was a crash in the tool result path, not a degradation. It was mine, introduced with the eviction in the previous commit. A lock now covers the lookup, the LRU touch, and the evict-and-insert. It is NOT held across a count_chat_tokens call: serialising the round trips themselves would trade a shared cache for a shared queue, which is the opposite of the point. Two threads may therefore measure the same chunk at once and both store it, which costs one duplicate measurement and cannot change a value, since the count is the same either way. The victim scan iterates a list copy and deletes with pop(..., None), so the invariant holds even if the lock is ever widened or narrowed later. Re-fuzzed against the modified code: 0 mismatches with the cache live, with it disabled, and with the bound cut to 3,000 characters and 3 entries so eviction fires on nearly every insert. Round trips unchanged. The new test fails on the previous head on every run and asserts three things: no exception, every thread agreeing on every answer, and both bounds still holding under concurrent insertion.
Follow-up to #9384, which sized a large tool result to the window the model is running with, and corrected the character budget for dense non-ASCII. Two things it got wrong, both found reviewing it.
1. Dense ASCII still overflows the window
_dense_prefix_charscharges every non-ASCII character and every percent-escape a token, and every ASCII character a flat0.25. That second rate is an English rate, and it is wrong in the same direction for the ASCII the code tools print most.On a 5,120-token window the character cap admits 7,168 characters against a promised 1,792-token share. Measured with Qwen3-4B-Instruct-2507 and Llama-3.2-1B-Instruct, plus tiktoken for corroboration:
base64 payload.binhexdump -Csha256sum *End to end through the real
fit_rolling_contextwith the real Qwen3 chat template, on a four-message thread whose user turn is 8 tokens:That is the exact failure #9384 exists to prevent, reproduced after it, on
base64 payload.bin. The repo already knew:tools.py:10313andllama_cpp.py:24200both say code, JSON, hashes and command output "run nearer two or three characters per token than four".No character rule fixes this. I measured a word-structure heuristic (plain-word vs mixed-class, 4 vs 2.5 chars/token): it still undercharges base64 by ~2x while overcharging English by 39%, which would shrink every page the PR promises to leave untouched. A 76-character base64 line really costs 57 Qwen3 tokens; nothing character-based reaches that without wrecking prose.
So when a tokenizer is already serving the request, ask it.
_exact_prefix_charsshrinks the prefix until it truly fits the share, via the samecount_chat_tokensthe RAG admission path and five other call sites inllama_cpp.pyalready use for exact fitting. It is bounded and conservative:_MIN_PAGE_CHARS.Cost: English 1 call / 2.3 ms, base64 2 calls / 13.8 ms, results under 2,000 chars 0 calls.
After the fix, same session:
raw 27018 chars -> result 2552 chars, 1824 Qwen3 tokens (share 1792); session 1883 vs budget 3840; ADMITTED.2. A configured cap below the floor was raised, not preserved
_result_char_budgetapplied the readability floor outside the cap:_MAX_OUTPUT_CHARSis_env_int("UNSLOTH_TOOL_RESULT_MAX_CHARS", 16000)and_env_intaccepts any value above 0, so 500 is a supported configuration. Before #9384,_truncate(text, limit = _MAX_OUTPUT_CHARS)honoured it exactly. After:So the one function whose job is to lower the cap raised it fourfold, hardest on the smallest windows, and the same install got 500 characters from a hosted result and 2,000 from a local one (
studio_tool_loop._truncate_for_modelreads_MAX_OUTPUT_CHARSdirectly and still cut at 500).The floor is there to keep a result readable when the window is what makes it small. It was never meant to override what the install asked for. One line:
_page_char_budgethas the same shape but its cap is the constant_MAX_PAGE_CHARS = 16000, which cannot be configured below 2,000, so it is left alone.Tests
TestDenseAsciiIsMeasuredNotEstimated(7): base64 cut to its share; a dense result no longer outweighs the window; English keeps every character (the blast radius that matters); a resident GGUF does not price another model's request; a counter that raises falls back to the estimate; no backend leaves the estimate alone; the readable floor still holds.TestAConfiguredCapIsNeverRaised(4): a configured 500 survives a known 8,192 window; survives a 1,024 window where the share alone is 1,433; local and hosted agree; an unconfigured install still gets the floor.Neither existing test covered these paths, so nothing had to be relaxed:
test_an_explicit_limit_is_still_a_ceiling_not_a_floorexercises_dense_char_limit's argument (correctly clamped already) andtest_an_explicit_limit_still_winsexercises_truncate's argument. Both bypass_result_char_budget.Before this commit the new tests fail 6 of 11. After:
test_web_page_cap_fits_window,test_web_fetch_extraction,test_external_tool_truncated_and_budget,test_context_overflow_truncation-> 1208 passed.