Skip to content

Studio: pay for the tool result framing probe once per model, not once per result - #9541

Merged
danielhanchen merged 6 commits into
mainfrom
tool-result-probe-lazy-cached
Aug 23, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
tool-result-probe-lazy-cached

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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_tokens is two llama-server calls, /apply-template then /tokenize, over a fresh httpx.Client each 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:

tool result before after (first result) after (later result) after (same result again)
English, 27,000 chars 2 calls / 4 HTTP 1 / 2 1 / 2 0 / 0
base64 payload.bin, 27,000 chars 4 / 8 4 / 8 3 / 6 0 / 0
base64 then prose, 27,000 chars 4 / 8 4 / 8 3 / 6 0 / 0
hexdump -C, 10,270 chars 4 / 8 4 / 8 3 / 6 0 / 0
base64, 3,000 chars 4 / 8 4 / 8 3 / 6 0 / 0

And the small-window case, where the budget is already at the floor before anything is measured:

window before after
512 2 calls / 4 HTTP 0
1024 2 / 4 0
1400 2 / 4 0
2048 2 / 4 2 / 4

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_limit clamps with max(_MIN_PAGE_CHARS, fitted), and every value _exact_prefix_chars can return is either at most its chars argument 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 0 ran 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:

if spent is None:
    return chars          # guard rejected the count: keep the estimate
if spent <= token_budget:
    return chars          # count fits: keep the estimate

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:

  • 1,230 results, each checked twice: the _dense_char_limit integer and the full _truncate string.
  • 11 tokenizer shapes: English, base64, CJK, hexdump, whitespace, dense-then-prose, prose-then-dense, and the pathological ones the guard exists for, a constant count, a sublinear count, zero and negative.
  • 10 windows from 512 to 131,072, and caps of 500, 2,000, 7,168, 16,000 and random.
  • 8 backend modes: healthy, raising on some chunks, raising on all, returning a float, returning junk, and framing values of 0, 8, 11 and 37.
  • Several results in a row through the same model, so the cache is live across calls and would have to be wrong for an answer to differ.
1230 generated tool results compared (_dense_char_limit AND the full _truncate string)
mismatches: 0
counter calls  merge base: 5049   this branch: 1408   (72.1% fewer)
llama-server HTTP round trips (2 per counter call): 10098 -> 2816

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 check clean, scripts/run_ruff_format.py applied.

…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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 3149c348ad

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

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@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
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 8ab4b4a3b7

ℹ️ 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 45b13db into main Aug 23, 2026
38 checks passed
@danielhanchen
danielhanchen deleted the tool-result-probe-lazy-cached branch August 23, 2026 16:32
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