Skip to content

perf(agent): offer tools in admission order so the prompt cache survives a skill load - #4036

Merged
kovtcharov-amd merged 8 commits into
amd:mainfrom
kovtcharov:claude/tools-in-admission-order
Sep 26, 2026
Merged

kovtcharov-amd merged 8 commits into
amd:mainfrom
kovtcharov:claude/tools-in-admission-order

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Loading a skill mid-answer used to throw away the model's prompt cache. The tool list the model is sent was re-sorted alphabetically every time a tool was admitted, so pulling in one tool moved every tool after it — and the model's cache is a prefix match, with several chat templates putting the tool list ahead of the system prompt. On a measured GitHub task, only 4,276 of 12,545 prompt tokens came back from cache on the step after a skill load. Fresh input tokens are 53% of a run's cost, so that is real money and real latency on the exact turns where the agent is working hardest. Tools are now offered in the order they were admitted and appended, never re-shuffled, so a mid-turn load only adds bytes at the end and everything already sent stays cached. Which tools get selected is unchanged.

Test plan

  • python -m pytest tests/unit/test_tool_admission_order.py tests/unit/test_tool_loader_selection.py tests/unit/test_chat_dynamic_tools.py tests/unit/test_dynamic_tool_filtering.py tests/unit/test_chat_tool_bundles.py tests/unit/test_tool_recall.py tests/unit/test_adaptive_skills.py hub/agents/chat/python/tests -q
  • Full python -m pytest tests/unit -q — no new failures against this machine's known-failing set (profilespec goldens, tool-loader token budget, hub installer, diarize, coding starter skill, connectors/registry import).
  • python util/lint.py --black --isort --flake8 — black clean; the two isort failures (src/gaia/connectors/api.py, two integration tests) are pre-existing and untouched here.
  • gaia eval agent --category tool_selection shows no regression against the baseline. This changes the order tools appear in the prompt, so it needs a run on a machine with a backend.
🔍 Technical details

What sorted, and what it does now

Site Before After
ToolLoader.select return sorted(self._loaded) list(self._loaded) — dict insertion order is admission order
ToolLoader.select CORE tier sorted(self._core) registry order (matches the unfiltered prompt)
ToolLoader.load_bundle sorted(members), returned sorted(self._loaded) registry order, returns list(self._loaded)

Left alone on purpose: the semantic tier's (-score, name) tie-break (changing it would change which tool wins the last slot at the cap, not just the order), bundle_names() (a menu in the prompt's stable prefix), the TOOL_LOADER log's diagnostic set keys, and tool_recall.py's union (offline scoring, order-irrelevant).

Eviction moved to the turn boundary. load_bundle is now add-only and may exceed dynamic_tools_max for the rest of the turn — bounded by one bundle per call, logged with an over_cap count. select trims the overshoot LRU-first before admitting, and a dict delete leaves survivors in order, so the list only loses the evicted entries. Mid-turn eviction was the worst case of the original bug: it dropped a tool from the middle of the offered list.

Renderers were already fine. _build_openai_tool_schemas(filter_to=…) and _format_tools_for_prompt(filter_to=…) both iterate filter_to in the given order; only their docstrings claimed the list was pre-sorted. _refresh_active_tool_filter's != was already an ordered list comparison, so an unchanged set with the same order still recomputes nothing — there is now a test pinning both halves of that.

Changed assertion. test_load_bundle_is_cap_aware_and_protects_just_loaded → test_load_bundle_overshoots_the_cap_then_the_next_turn_trims. It pinned the mid-turn eviction this PR replaces; the new test asserts the add-only list and that the next select restores the cap.

Adjacent, not fixed here: #4021 adds _offer_skill_tools, which returns sorted({*current, *missing}) — the same alphabetical re-shuffle, on the mid-turn skill path. Whichever of the two lands second should switch it to append.

@github-actions github-actions Bot added documentation Documentation changes tests Test changes agents labels Sep 20, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions — after the tool-selection eval runs

Tools are now offered to the model in the order they were admitted instead of being re-sorted alphabetically, so pulling in one bundle mid-answer appends to the end of the list rather than shuffling everything after it. That is the right fix for the cache-loss problem the description measures, and the selection logic itself is untouched — the same tools get picked, they just keep their place.

One thing to settle before merge: this changes the order the tool list is sent to the model, and model behaviour is sensitive to ordering. The test plan already lists the agent eval as the outstanding item, unchecked. That run is the gate here, not optional — the unit tests pin the ordering invariant, but nothing yet shows the model still picks the same tools when they arrive in a different sequence. Worth also capturing the after-number for the cache hit rate on the same task the description measures before: that is the proof the fix worked, and right now only the before-number exists.

Everything else is small. The escape hatch now deliberately lets the tool count run over its cap for the rest of a turn, which is a reasonable trade — trimming mid-turn is exactly the cost this PR removes — and the next turn puts it back. The behaviour is documented in the plan and the changelog, and the affected tests were updated rather than deleted.

Real-world evidence

N/A — no evidence bundle was produced for this PR, and this change touches no CLI, API, MCP or Agent-UI surface directly; its observable surface is the agent's prompt and cost. My verdict rests on static review of the diff plus reading the new and updated tests against the current loader source. I did not execute the test suite (no pytest in this review environment), so the test-plan checkmarks are the author's evidence, not mine. The one piece of evidence I would want and that does not exist yet is the gaia eval agent --category tool_selection comparison against the committed baseline, which the author flags as pending.

🔍 Technical details

🟡 Important

Required eval not yet run for an LLM-affecting change. CLAUDE.md → "Run agent evals when changing LLM-affecting code paths" names "the JSON tool schema sent to Lemonade" explicitly, and this PR changes the order of that schema array (_build_openai_tool_schemas(filter_to=…) now receives admission order) and of the AVAILABLE TOOLS block. Order is a real behavioural lever for tool choice — a tool that used to sit near the top of an alphabetical list may now land last. Before merge:

gaia eval agent --category tool_selection --agent-type doc
gaia eval agent --compare tests/fixtures/eval_baselines/<model>/scorecard_tool_selection.json <run-dir>/scorecard.json

The description's cache measurement (4,276 / 12,545 prompt tokens reused) is a before-number; the matching after-number on the same task would close the loop on the perf claim too.

🟢 Minor

load_bundle's log line hardcodes empty eviction fields (src/gaia/agents/base/tool_loader.py:490). sel still collects evicted / skipped_at_cap, so if eviction ever comes back to this path the log will silently claim none happened. Reading the scratch costs nothing and stays honest:

            "admitted": sorted(sel.admitted),
            "evicted": sorted(sel.evicted),
            "skipped_at_cap": sorted(sel.skipped_at_cap),
            "loaded": list(self._loaded),

"Bounded (one bundle per call)" is a per-call bound, not a per-turn one (tool_loader.py:458, and the same wording in docs/plans/tool-loader.mdx:387). Nothing limits how many times the model calls load_tools within one turn, so cumulative overshoot is bounded only by the registry size — on the flagship, 80 tools against a cap of 28. That is a defensible trade (each call's cost is just the appended tail, and the model asked for it), but the docstring reads as a stronger guarantee than the code gives. Either say "bounded per call; a turn with repeated calls can accumulate" or add a per-turn ceiling.

Module-level importorskip skips tests that don't need the chat wheel (tests/unit/test_tool_admission_order.py:460). The first eight tests exercise ToolLoader alone and have no gaia_agent_chat dependency; a framework-only environment loses the core ordering invariants along with the agent-level ones. Moving the guard to a pytest.mark.skipif on the agent tests (or a fixture) keeps the loader tests running everywhere.

Strengths

  • The invariant is pinned where it can actually regress: test_later_admission_appends_and_leaves_the_prefix_identical and test_render_paths_preserve_admission_order_and_prefix assert the prefix is unchanged, not just that the set matches — which is the property the KV cache depends on and the property a future alphabetical sort would break.
  • test_active_filter_is_compared_by_order_not_as_a_set pins both halves of the recompute rule (same order → no recompute, re-order → recompute). That guards the one place where making the comparison order-insensitive would look like a harmless cleanup and quietly reintroduce the bug.
  • The eviction move is coherent rather than a patch: _trim_to_cap runs at the single point where dropping a tool is affordable, _pick_eviction_victim still protects CORE, and a dict delete leaves survivors in order — so the offered list only loses entries, never reshuffles.
  • Doc surfaces were updated together (plan + npm CHANGELOG), and the replaced test was rewritten to assert the new contract (test_load_bundle_overshoots_the_cap_then_the_next_turn_trims) instead of being dropped. I checked the other loader tests and the tool_recall log parser — all compare sets, so none were silently relying on sorted output.

Kalin Ovtcharov and others added 3 commits September 21, 2026 04:38
The turn's tool subset is picked from the user's message before the first
model call. A skill the model loaded during that turn joined the prompt but
not the tool list, so the tool its recipe names stayed missing until the next
turn - and a one-turn task has no next turn. After loading github-triage
("run every GitHub command through run_shell_command") the agent had no shell
tool and ran `gh` through run_python instead: 3 of 3 GitHub tasks that loaded
the skill in a 14-task benchmark run. For a user that is an approval prompt
per call, where the skill's grant needs none.

load_skill now adds the skill's tools_required and its own tools to an
active tool subset, the same way the load_tools escape hatch already widens
it mid-turn. Agents without a subset are unchanged, and a required tool the
agent does not have is not invented.
…offered list

Re-sorting moved every tool after the new ones, and on a template that renders
tools first that re-prefilled the whole prompt: 4,276 of 12,545 tokens cached
on the step after a skill load, measured on the benchmark.
…ves a skill load

One mid-turn `load_tools` used to cost a near-full re-prefill of the prompt. The
offered tool list was re-sorted alphabetically on every admission, so adding one
tool moved every tool after it — and several chat templates render the tool list
*before* the system prompt, which makes it the cached prefix. On a measured
GitHub task only 4,276 of 12,545 prompt tokens came back from cache on the step
after a skill load; fresh input tokens are 53% of a run's cost.

Tools are now offered in admission order — the always-on core in registry order,
then each later admission appended where it happened — and never re-sorted, so a
new tool only adds bytes at the end. Eviction moved to the turn boundary:
load_bundle is add-only and may briefly exceed dynamic_tools_max, which the next
select trims LRU-first, survivors keeping their relative order.

Which tools get selected is unchanged; only their order, and when the list
shrinks. test_load_bundle_is_cap_aware_and_protects_just_loaded became
test_load_bundle_overshoots_the_cap_then_the_next_turn_trims — it pinned the
mid-turn eviction this replaces.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Restacked on #4021 (skill-tools-same-turn). Merge after #4021.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Merged main in — this is mergeable again.

One conflict, and it was the interesting kind: main now documents the loaded set as sorted, which is exactly the behaviour this PR replaces. Kept this PR's wording (admission order) and main's new _turn_seq counter, so neither side lost anything.

🔍 Technical details

Conflict was a single hunk in the class-attribute block of src/gaia/agents/base/agent.py: main added _turn_seq: int = 0 immediately above the _active_tool_filter docstring this PR rewrites, so the two edits landed on adjacent lines. Resolution keeps both — one _turn_seq definition (verified: exactly one, at line 944), and the admission-order comment.

Tests: test_tool_admission_order.py, test_tool_loader_selection.py, test_skill_tools_same_turn.py → 48 passed. black --check clean.

test_tool_loader_token_budget.py fails 4 tests, all cascading from doc tool count changed: 38 != 37. That's pre-existing on main — this PR adds no tool (git diff origin/main...HEAD on the chat agent shows no @tool change), and the pin hasn't been touched since #1456. Someone added a doc-profile tool without bumping the baseline; worth a separate fix.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Confirmed the token-budget failures are not yours, and #4038 is the fix. Nothing to do here.

Ran the file on origin/main (88441a017) and on this branch's head: identical results — 4 failed, same four assertions, same numbers (38 vs the pinned 37; CORE 2736; worst-case-14 3932). #4038 re-pins the token baselines and the tool count, and wires the file into a CI lane so it stops drifting.

🔍 Technical details

Bisected the tool-count change to 482390a16 (#3670), which added read_tool_output to the doc bundle without touching tests/unit/test_tool_loader_token_budget.py. Nothing caught it because that file never ran: module-level pytest.importorskip("gaia_agent_chat"), and no lane that installs the wheel names the file (#3294).

Kalin Ovtcharov and others added 2 commits September 23, 2026 16:22
# Conflicts:
#	hub/agents/gaia/npm/CHANGELOG.md
…literal

The load_tools log line hardcoded "evicted": [] and "skipped_at_cap": [].
That is accurate while the path is add-only, which is the point -- it
looks right, so if eviction ever comes back here the log would keep
reporting that none happened, and the eval's recall parser reads these
fields. Reads them off the scratch object instead.

The new test drives eviction onto the path and asserts the payload carries
it; reverting the two fields to literals fails it.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Unblocked: this is mergeable and clean against main, and #4021 is mergeable too, so the stack is no longer stuck — merge order is the only remaining constraint. The _offer_skill_tools follow-up this PR's description deferred to "whichever lands second" is already done on this branch, so there's nothing left to hand off between the two.

Fixed the one real defect: the escape-hatch log claimed nothing was ever evicted by writing that in as a constant rather than reading it. Harmless today, because that path genuinely evicts nothing — which is exactly why it would survive review if eviction ever came back, and the eval's recall parser reads those fields.

The eval is still the open gate, and I could not close it here. No inference backend is reachable on this machine, so gaia eval agent --category tool_selection cannot run. That item stays unchecked, and it is the one piece of evidence that matters — reordering the tool schema is a behavioural change to tool choice, and no amount of unit-test green speaks to it.

🔍 Technical details

The log fix (tool_loader.py, load_bundle): "evicted": [] / "skipped_at_cap": [] → sorted(sel.evicted) / sorted(sel.skipped_at_cap). sel already collects both.

New test test_load_bundle_reports_evictions_from_the_selection_not_a_literal wraps _admit to push entries onto the scratch and asserts they reach the payload. Mutation-checked — restoring the literals fails it:

MUTATED -> 1 failed in 1.17s

Stack state: #4021 MERGEABLE/UNSTABLE, #4036 MERGEABLE/CLEAN. This branch contains 0cf1ccceb (#4021) plus 5982ec0fb, which is the _offer_skill_tools append fix — verified: it now does agent._apply_tool_filter([*current, *missing]) with no sorted().

Tests: 193 passed across test_tool_admission_order, test_tool_loader_selection, test_chat_dynamic_tools, test_dynamic_tool_filtering, test_chat_tool_bundles, test_tool_recall, test_adaptive_skills, test_skill_tools_same_turn. black/isort/flake8 clean.

On the eval. Nothing reachable on 8000, 13305 or 4200, and no other eval is running (checked, per the one-eval-per-backend rule). Two tool_selection baselines are committed and both are usable references for a Gemma-4-E4B run:

baseline model date
gemma-4-e4b-d71cd914 Gemma-4-E4B-it-GGUF 2026-04-24
qwen-3.5-35b-3b51ca92 Qwen3.5-35B-A3B-GGUF 2026-04-24

Worth noting before anyone runs it: these predate the flagship becoming the default --agent-type, so check what the baseline scored before reading a diff as a regression — compare_scorecards keys on scenario_id alone and will happily compare across two different agents.

Not addressed (the review's remaining 🟢 items): the "bounded (one bundle per call)" docstring still reads as a per-turn guarantee it does not give, and tests/unit/test_tool_admission_order.py's module-level importorskip still skips the eight loader-only tests in a framework-only env. Both are wording/scoping, not behaviour, and I left them rather than widen a PR whose real gate is the eval.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 26, 2026
Merged via the queue into amd:main with commit 7fc92fe Sep 26, 2026
47 of 49 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/tools-in-admission-order branch September 26, 2026 04:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants