Skip to content

fix(tests): the synthetic tiktoken encoding of the prepared-cache test stays in tiktoken's registry, so later token counts on that worker are per byte #2002

Closed

Description

@dan-petty

Problem

_prepare_o200k_cache_dir in tests/test_context_budget.py builds a synthetic o200k_base encoding, in which almost every token is one byte. When count_tokens loads it, tiktoken stores it in its own registry, tiktoken.registry.ENCODINGS. The helper removes the key with monkeypatch.delitem(..., raising=False). When the key was absent before the test, monkeypatch records nothing to restore, so the synthetic encoding stays in the registry after the test. The reset_tiktoken_encoding_cache reset in tests/conftest.py clears only the lru_cache of devops-cli, not tiktoken's registry.

Every later count_tokens call in that process then counts about one token per byte. The pre-push gate of #1995 failed on worker gw4 with four tests: test_truncate_to_token_limit (assert 37 <= 30, where 37 is count_tokens('\n...[truncated due to context budget]')), test_pack_code_fallback_on_non_python, test_pack_snippets_distributes_budget and test_pack_snippets_small_budget_never_exceeds_total.

The failure is deterministic in this order:

uv run pytest -n 0 -p no:randomly --no-cov \
  tests/test_context_budget.py::test_count_tokens_loads_encoding_from_prepared_cache_dir_without_network \
  tests/test_context_budget.py::test_truncate_to_token_limit
1 failed, 1 passed

Proposed fix

Give the test its own registry with monkeypatch.setattr(tiktoken.registry, "ENCODINGS", {}). monkeypatch then puts the original dict back at teardown, and the synthetic encoding goes with the test's dict.

Acceptance criteria

  • A test runs the prepared-cache test and then counts tokens with the real encoding in the same process, and the count is the real one.
  • The command above passes.

Activity

  1. added
    type/bug
    scope/ai
    on Oct 23, 2026
  2. added a commit that references this issue on Oct 24, 2026
    eed8767
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    scope/aitype/bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions