Repository navigation
Studio: pay for the tool result framing probe once per model, not once per result - #9541
Merged
Merged
Conversation
…sult The probe #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.
…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 #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.
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 #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.
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.
|
Codex Review: Didn't find any major issues. Nice work! 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". |
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.
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs 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". |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Follow-up to #9421, which measures a dense tool result with the serving model's tokenizer instead of estimating it. The measurement is worth its round trips. Paying for it again on the next result is not.
count_chat_tokensis two llama-server calls,/apply-templatethen/tokenize, over a freshhttpx.Clienteach time. So every counter call on this path is two HTTP round trips between a tool finishing and the model seeing its result. Counted on a 5,120-token window with the code tool's own budget:base64 payload.bin, 27,000 charshexdump -C, 10,270 charsbase64, 3,000 charsAnd the small-window case, where the budget is already at the floor before anything is measured:
Every "chars out" in those runs is identical before and after.
What was being bought and thrown away
A floor that was measured anyway.
_dense_char_limitclamps withmax(_MIN_PAGE_CHARS, fitted), and every value_exact_prefix_charscan return is either at most itscharsargument or exactly_MIN_PAGE_CHARS. So once the estimate is at or below the floor, the caller lands on the floor whichever branch runs, and the probe spends a full set of round trips rediscovering a number it already has. Checked before the counter is even looked up.A baseline priced before the count that decides whether it is needed.
framing = _rendered("") or 0ran up front, but the baseline is only ever used to decide whether a count that came in OVER budget is a real measurement rather than a template that dropped the content. A result that fits on its first count never reaches that question, and the two branches around it return the same value:So the budget now travels with the chunk and the baseline is priced on demand. English, which fits on its first pass, goes from 2 counter calls to 1.
A measurement discarded the moment it was read. A count is a pure function of model, chat template, window and chunk: the same text rendered through the same template tokenizes to the same number every time. The baseline in particular is one number for every result the process ever truncates. Both are now cached per model, so the baseline costs one round trip per model rather than one per tool result, and a result seen twice costs nothing the second time.
The cache key is the model's own identity, not the backend object:
model_identifier, the GGUF's resolved path, device, inode and size from_gguf_load_identity, the chat template override, and the window. A reload lands on a different key and clears the map, so a different model can never be answered from the one it replaced, even into the same window. A backend that can name neither its model nor its GGUF is not cached across calls at all. Failures are never cached: a busy server is a property of the moment, not of the text, and remembering one would turn a single timeout into a permanent estimate for that result. Bounded at 64 entries for one model, so at most about a megabyte.Output is byte-identical
Both copies of
tools.py, this branch's and #9421's merge commit, loaded into one process and handed the same deterministic counter, then compared on generated tool results:_dense_char_limitinteger and the full_truncatestring.Run again with the cache disabled, so only the laziness and the floor check are active: 0 mismatches, 62.9% fewer. Nothing in the saving depends on the cache being correct for the output to be correct.
Tests
TestTheProbeIsNotPaidForTwice(9), each asserting the merge base's return value alongside the round trips it no longer takes: an estimate at the floor is not measured at all; a result that fits does not price the baseline; the baseline is priced once per model rather than once per result; the same result twice costs nothing the second time; a different model never reads the previous one's counts; a backend that cannot name its model is not cached; a failed count is never remembered as an answer; the cache cannot grow without bound; and the guard still rejects a template that renders no content, because the baseline is deferred, not dropped.The autouse fixture now clears the cache around every test, so one backend double cannot answer the next one's questions.
test_web_page_cap_fits_window,test_web_fetch_extraction,test_external_tool_truncated_and_budget,test_context_overflow_truncation-> 1220 passed, against 1211 at the merge base, which is the 9 new tests and nothing else. Across all 68 backend test files that touch this path: 7,914 passed here against 7,905 at the merge base, with byte-identical failure and error sets (190 entries, all pre-existing local environment gaps).ruff checkclean,scripts/run_ruff_format.pyapplied.