Skip to content

fix(hub): bundle tiktoken's cl100k_base in the frozen agent - #5600

Merged
kovtcharov-amd merged 4 commits into
amd:mainfrom
kovtcharov:kalin/fix-5066-freeze-tiktoken
Oct 23, 2026
Merged

kovtcharov-amd merged 4 commits into
amd:mainfrom
kovtcharov:kalin/fix-5066-freeze-tiktoken

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

The published gaia-agent binary couldn't load tiktoken's cl100k_base, so every turn counted tokens with a deliberately high estimate. History trimming reads that number, so the shipped agent dropped conversation history earlier than it needed to. The frozen flagship and email agents now bundle the tokenizer plugin and its data, so they count exactly, offline included.

Found testing v0.25.1-rc5 on macOS (sidecar log: …could not load (Unknown encoding cl100k_base…)). Part of #5066 — source installs still download the file on first use.

Test plan

  • pytest tests/unit/test_tiktoken_bundle.py tests/unit/test_turn_metrics.py hub/agents/gaia/python/tests/test_freeze_required_modules.py: 80 passed; 4 new tests fail on main.
  • PyInstaller 6.22.3 builds of the real turn_metrics._tokenizer() with no cache dir and every proxy pointed at a closed port: without this config it reports the shipped "Unknown encoding" fallback; with the args freeze.py now adds it reports tiktoken:cl100k_base.
  • build_flagship_sidecar.yml passes the new check_tokenizer smoke check on a full freeze (not built here: not enough disk).
🔍 Technical details

src/gaia/utils/tiktoken_bundle.py: stage_cache(dest) downloads cl100k_base at build time (failing the build loudly if it can't), and use_bundled_cache() points TIKTOKEN_CACHE_DIR at the bundled copy only inside a frozen binary, and only when the user set neither TIKTOKEN_CACHE_DIR nor DATA_GYM_CACHE_DIR. Both freeze.py files hidden-import tiktoken_ext.openai_public (found by namespace scan, which PyInstaller misses) and add the staged cache as data. The email agent gets tiktoken through tavily-python, so it had the same gap.

The published gaia-agent binary could not load its tokenizer, so every
user of it got token counts from an overcounting estimate and the log
line "Unknown encoding cl100k_base". tiktoken finds encodings through a
plugin it discovers by scanning the tiktoken_ext namespace package, which
PyInstaller never collected, and then downloads the BPE file on first use.

- Both freezes (flagship and email) now hidden-import
  tiktoken_ext.openai_public and bundle the cl100k_base cache file, staged
  at build time; the build fails if it cannot be staged.
- In a frozen binary the tokenizer points TIKTOKEN_CACHE_DIR at the bundle
  before loading, so nothing is downloaded and counts are exact offline. A
  cache folder the user set still wins.
- The flagship smoke test asserts the agent's tokenizer is
  tiktoken:cl100k_base with no cache folder set and every request proxied
  through a closed port.

Source installs still download the file on first use; that part of the
issue is left open.

Part of amd#5066
@github-actions github-actions Bot added tests Test changes agents agent::email Email agent changes sidecar Agent sidecar contract / harness labels Oct 22, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

The released flagship and email agent binaries couldn't load their tokenizer, so they estimated token counts too high and trimmed conversation history earlier than they needed to. This PR packs the tokenizer and its data into both binaries, and the build now fails loudly if it can't fetch that data. The fix is sound and well tested. Nothing blocks merge.

  • The full-freeze check on the flagship binary is still unchecked in the test plan. It runs in build_flagship_sidecar.yml, so confirm it passes before the RC, not after.
  • The email binary gets the same packaging fix, but its smoke test has no matching offline check. A regression there would go unnoticed until someone reads a sidecar log.

Real-world evidence

N/A here: this is a build/packaging change with no evidence bundle, so this verdict rests on static review alone. The PR description reports PyInstaller test builds where the tokenizer loads offline. The real proof is the new check_tokenizer step in the flagship's full-freeze smoke test, which hasn't run yet.

🔍 Technical details

Issues

🟢 Email binary has no offline tokenizer smoke check (hub/agents/email/python/packaging/smoke_test.py). test_freeze_collect_targets.py only proves freeze.py passes the right PyInstaller args. It doesn't prove the email binary loads cl100k_base. Porting check_tokenizer/TOKENIZER_SCRIPT from the gaia smoke test would close the gap. That needs a way to run code inside the email binary, though. If the binary has no run_python equivalent, say in the PR that the email side is covered by args only.

🟢 Freeze relies on tiktoken arriving transitively. Neither freeze env installs tiktoken directly. It comes in through tavily-python (setup.py:162). If tavily ever drops it, stage_cache stops the build with a clear error, so nothing fails silently. Still, adding tiktoken to the uv pip install lines in build_flagship_sidecar.yml and release_agent_email.yml would make the dependency explicit.

🟢 An inherited TIKTOKEN_CACHE_DIR counts as user-set (src/gaia/utils/tiktoken_bundle.py, use_bundled_cache). use_bundled_cache writes TIKTOKEN_CACHE_DIR into os.environ. A child process that re-execs the onefile binary inherits it and keeps reading the parent's _MEIPASS cache, not its own. This works while the parent is alive, so it's only worth knowing about, not fixing now.

Strengths

  • stage_cache follows the fail-loudly rule: a failed download, or one that wrote no file, stops the build with an actionable message, so it never ships a binary that silently falls back to the estimate.
  • The smoke check tests from a cold start: no cache env, a fresh temp dir, and every proxy pointed at a closed port. That's the state a new offline user is actually in.
  • The tests pin the order that matters: test_the_tokenizer_switches_to_the_bundle_before_loading checks the cache path is set before get_encoding runs. A user-set TIKTOKEN_CACHE_DIR or DATA_GYM_CACHE_DIR still takes priority.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

The one failing job (Unit Tests, macOS) is the known flake test_the_next_waiter_takes_the_lock_within_milliseconds (6.4 ms vs a 5 ms bound, #5608), in file-lock code this PR doesn't touch; Linux and Windows passed. A re-run should clear it; I can't re-run jobs on this repo.

Kalin Ovtcharov and others added 2 commits October 22, 2026 18:52
# Conflicts:
#	hub/agents/gaia/npm/CHANGELOG.md
Both freeze.py files bundle tiktoken's cl100k_base, but the freeze envs only got tiktoken through tavily-python. Naming it keeps a tavily dependency change from breaking the build.
@github-actions github-actions Bot added the devops DevOps/infrastructure changes label Oct 23, 2026
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Both freeze environments now install tiktoken by name, so the build no longer depends on tavily-python pulling it in.

The email binary has no way to run a script the way the flagship's run_python does, so its side is covered by the freeze arguments test plus stage_cache, which stops the build if cl100k_base can't be staged. The inherited TIKTOKEN_CACHE_DIR case is left as is, as the review suggested.

The full-freeze check_tokenizer run still needs a build_flagship_sidecar.yml dispatch from a branch on amd/gaia before the RC.

The last red unit-test job (Windows) was the file-watcher timing test, which this PR doesn't touch.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Full freeze check on this PR's head (16529ce): Build flagship sidecar passed on all four platforms, plus the Linux binary's smoke test on Rocky 9, Ubuntu 22.04, Debian 12 and Ubuntu 24.04. That covers the bot's request to see the frozen tokenizer check pass before the RC.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 23, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Oct 23, 2026
Keep both sides' Unreleased CHANGELOG entries for the gaia and email agents.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 23, 2026
Merged via the queue into amd:main with commit afb0378 Oct 23, 2026
46 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the kalin/fix-5066-freeze-tiktoken branch October 23, 2026 10:07
kovtcharov-amd added a commit to tylerbea/gaia that referenced this pull request Oct 30, 2026
…reach (amd#5653)

Of the last 150 bug fixes, 147 shipped a regression test, yet CI caught
only about 7 of those bugs before users or RC testing did. Each test
guards the one call site that broke, and the next site with the same
flaw ships untested. Meanwhile every PR ran all ~27k unit tests on three
operating systems, even for a docs edit, and most main-branch runs were
cancelled before they finished. This PR guards the recurring bug shapes
everywhere, fixes a real bug the new tests found, and makes a PR run
only the tests it can affect.

- **Guards for the shapes behind most recent fixes.** A ratchet counts
subprocess and HTTP calls with no timeout, kill-by-image-name, and
`except Exception` bodies that only pass or return a placeholder.
Existing sites are grandfathered, new ones fail CI, and fixing one
lowers the count.
- **Folder grants were lost when several GAIA processes saved at once.**
A four-process test lost 96–98 of 100: the read-modify-write had no
lock, and a torn read "rebuilt" the file from empty. It is now locked
and atomic. Six runtime calls that could hang forever now time out, with
actionable errors.
- **PRs run only the reachable tests.** `util/select_tests.py` combines
a nightly per-test coverage map with static rules for what coverage
can't see. Windows and macOS run the OS-touching subset of that. The
median PR runs about a quarter of the suite. On ~1,150 recent commits,
it selected every bug fix's own regression test from the fix's source
changes alone.
- **Full coverage moves to main and nightly.** Every push to main runs
the full suite on Linux and now finishes instead of being cancelled. The
nightly run covers all three operating systems and rebuilds the map. The
frozen flagship binary also builds on packaging PRs and weekly, not only
at an RC.
- **Duplicates trimmed.** The email unit lane no longer re-runs ~90
files `test_unit.yml` already covers, and the warning-only C++
benchmarks run on main instead of every PR.

Also unbreaks main's TUI build: amd#5464 documented the desktop app's
`gaia` shim in backticks, and the TUI doc check only exempted it before
a space, so every PR's TUI checks went red. The shim is the Python
CLI's, so the exemption now accepts any punctuation after it.

Trade-offs to know: a Windows- or macOS-only bug outside the OS-touching
subset surfaces at the nightly run, not on the PR, and PRs no longer
upload partial coverage to Codecov. To run the full suite on a branch,
dispatch `test_unit.yml` on it.

## Test plan
- [x] `pytest tests/unit/test_select_tests.py
tests/unit/test_process_safety_ratchet.py
tests/unit/test_allowed_paths_concurrency.py`: 26 + 33 + 1 passed; the
concurrency test fails on the old code (96–98 of 100 grants lost)
- [x] Full `tests/unit` locally: 27,501 passed; 26 failures that fail
identically on main in this environment (PATH-installed `gaia`, real
wheel installs)
- [x] `python util/lint.py --all` passes, including the lane-coverage,
path-coverage, trigger and ancestor-skip checks
- [x] Selector replayed over ~1,150 recent commits with a map built from
a real `--cov-context=test` run
- [ ] After merge: the first nightly run saves `unit-test-map-*`, and
the next PR's "Select unit tests" summary reports a map-based selection

<details>
<summary>🔍 Technical details</summary>

- Static rules: module-level imports (transitive); every import and
module-naming string in tests and tooling (transitive); filename strings
and directory scans (one hop); nested `conftest.py`; top-level fixtures
by requested name, through fixture chains; autouse isolation fixtures
(one hop); CLIs run with `python -m`, whose lazy imports coverage can't
see. A package `__init__` reaches everything below it when it changes,
but the walk never continues through one.
- Full-run triggers: any `conftest.py`, packaging or pytest config, the
selector or `test_unit.yml`, and any deleted or renamed file (`git diff
--no-renames`). So does a selection over 70% of the suite.
- With no map (a cache miss), function-level imports are followed too
and the job summary says so; a map over 3 days old raises a warning.
- A push diffs against the last commit a successful main run tested, so
merges whose runs were dropped while pending still reach Windows and
macOS. The event name is in the concurrency group, so a push can't drop
the nightly.
- Known blind spot, documented in `docs/reference/dev.mdx`: code behind
a cache or shared fixture is credited in coverage only to the first test
that ran it.
- Open PRs touching the same files (amd#5453, amd#5417, amd#5511, amd#5600, amd#5475,
amd#5542, amd#5558) test-merge cleanly against this branch; none gains a
conflict from it.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: v <v@x>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent::email Email agent changes agents devops DevOps/infrastructure changes sidecar Agent sidecar contract / harness tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants