fix(tokens): warm fallback tokenizer in background (#5861)

* fix(tokens): keep fallback token estimation offline

* fix(tokens): warm fallback tokenizer in background

* test(tokens): isolate agent fixtures from tokenizer readiness

* test(tokens): keep Codex pressure fixtures within byte budget

* docs: remove manual wrapping from troubleshooting prose
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-28 13:50:55 +08:00
1 parent e0b8efa0be
commit 4a7ad00e4f
16 files changed
+378 -101

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
import pytest
import tiktoken
@pytest.fixture
def byte_encoding() -> tiktoken.Encoding:
"""Exercise the tokenizer API without downloading an upstream vocabulary."""
return tiktoken.Encoding(
name="test-bytes",
pat_str=r"(?s).",
mergeable_ranks={bytes([value]): value for value in range(256)},
special_tokens={"<|endoftext|>": 256},
)
+4 -5
View File
@@ -3,9 +3,8 @@ import os
from pathlib import Path
import pytest
import tiktoken
from nanobot.utils import helpers
from nanobot.utils import helpers, token_encoding
from nanobot.utils.helpers import (
_write_text_atomic,
atomic_write_lines,
@@ -107,14 +106,14 @@ def test_truncate_text_to_tokens_keeps_text_within_budget():
assert result == text
def test_truncate_text_to_tokens_truncates_over_budget():
enc = tiktoken.get_encoding("cl100k_base")
def test_truncate_text_to_tokens_truncates_over_budget(monkeypatch, byte_encoding):
monkeypatch.setattr(token_encoding, "_encoding", byte_encoding)
text = "word " * 1_000
result = truncate_text_to_tokens(text, 50)
assert result.endswith("\n... (truncated)")
assert len(enc.encode(result)) <= 50
assert len(byte_encoding.encode_ordinary(result)) <= 50
def test_truncate_text_to_tokens_non_positive_budget_returns_text():
+167
View File
@@ -0,0 +1,167 @@
import hashlib
import os
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from threading import Event, get_ident
import pytest
import tiktoken.load
from loguru import logger
from nanobot.utils import helpers, token_encoding
@pytest.fixture(autouse=True)
def isolate_warmup(monkeypatch, tmp_path, byte_encoding):
monkeypatch.setattr(token_encoding, "_warmup_thread", None)
monkeypatch.setenv("TIKTOKEN_CACHE_DIR", str(tmp_path / "cache"))
monkeypatch.setattr(token_encoding.tiktoken, "get_encoding", lambda _name: byte_encoding)
yield
worker = token_encoding._warmup_thread
if worker is not None and worker.ident is not None:
worker.join(timeout=5)
assert not worker.is_alive()
def finish_warmup():
worker = token_encoding._warmup_thread
assert worker is not None
worker.join(timeout=5)
assert not worker.is_alive()
def test_slow_warmup_does_not_block_concurrent_estimates(monkeypatch, byte_encoding):
entered, release = Event(), Event()
calls = []
caller_thread = get_ident()
def load(name):
calls.append((name, get_ident()))
entered.set()
assert release.wait(5)
return byte_encoding
monkeypatch.setattr(token_encoding.tiktoken, "get_encoding", load)
token_encoding.warmup_token_encoding()
try:
assert entered.wait(2)
with ThreadPoolExecutor(max_workers=8) as pool:
pending = [pool.submit(helpers.estimate_message_tokens, {"content": "🙂你"}) for _ in range(37)]
assert [task.result(timeout=1) for task in pending] == [11] * 37
assert helpers.estimate_prompt_tokens_chain(object(), "test", [{"content": "hello"}]) == (9, "heuristic")
assert len(helpers.truncate_text_to_tokens("hello " * 100, 40).encode()) <= 40
assert len(calls) == 1 and calls[0][0] == "cl100k_base"
assert calls[0][1] != caller_thread
finally:
release.set()
finish_warmup()
assert token_encoding.get_token_encoding() is byte_encoding
assert helpers.estimate_prompt_tokens_chain(object(), "test", [{"content": "hello"}]) == (9, "tiktoken")
def test_direct_consumer_starts_warmup_without_waiting(monkeypatch, byte_encoding):
release = Event()
def load(_name):
assert release.wait(5)
return byte_encoding
monkeypatch.setattr(token_encoding.tiktoken, "get_encoding", load)
try:
assert token_encoding.get_token_encoding() is None
assert token_encoding._warmup_thread is not None
finally:
release.set()
finish_warmup()
assert token_encoding.get_token_encoding() is byte_encoding
def test_failed_warmup_is_not_retried_per_message(monkeypatch):
calls, warnings = [], []
def fail(_name):
calls.append(_name)
raise OSError("offline")
monkeypatch.setattr(token_encoding.tiktoken, "get_encoding", fail)
sink = logger.add(lambda message: warnings.append(str(message)), level="WARNING")
try:
token_encoding.warmup_token_encoding()
finish_warmup()
for _ in range(37):
token_encoding.warmup_token_encoding()
assert helpers.estimate_prompt_tokens_chain(object(), "test", [{"content": "hi"}]) == (6, "heuristic")
assert calls == ["cl100k_base"]
assert len(warnings) == 1 and "until restart" in warnings[0]
finally:
logger.remove(sink)
@pytest.mark.parametrize("variable,value", [
(None, None), ("TIKTOKEN_CACHE_DIR", "custom-cache"),
("DATA_GYM_CACHE_DIR", "legacy-cache"), ("TIKTOKEN_CACHE_DIR", ""),
])
def test_cache_location_respects_configuration(monkeypatch, tmp_path, variable, value):
monkeypatch.delenv("TIKTOKEN_CACHE_DIR", raising=False)
monkeypatch.delenv("DATA_GYM_CACHE_DIR", raising=False)
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
if variable:
monkeypatch.setenv(variable, value)
token_encoding.warmup_token_encoding()
finish_warmup()
if variable:
assert os.environ[variable] == value
if variable == "DATA_GYM_CACHE_DIR":
assert "TIKTOKEN_CACHE_DIR" not in os.environ
else:
assert os.environ["TIKTOKEN_CACHE_DIR"] == str(tmp_path / "cache" / "tiktoken")
def test_completed_download_is_reused_after_reinitialization(monkeypatch, byte_encoding):
downloads = []
payload = b"test vocabulary"
checksum = hashlib.sha256(payload).hexdigest()
def download(url):
downloads.append(url)
return payload
def load(_name):
assert tiktoken.load.read_file_cached("https://example.test/vocabulary", checksum) == payload
return byte_encoding
monkeypatch.setattr(tiktoken.load, "read_file", download)
monkeypatch.setattr(token_encoding.tiktoken, "get_encoding", load)
for _ in range(2):
monkeypatch.setattr(token_encoding, "_warmup_thread", None)
monkeypatch.setattr(token_encoding, "_encoding", None)
token_encoding.warmup_token_encoding()
finish_warmup()
assert token_encoding.get_token_encoding() is byte_encoding
assert downloads == ["https://example.test/vocabulary"]
def test_stalled_download_does_not_hold_up_process_exit(tmp_path):
code = """
from threading import Event
from nanobot.utils import token_encoding
from nanobot.utils.helpers import estimate_message_tokens
started = Event()
def blocked(_name):
started.set()
Event().wait()
token_encoding.tiktoken.get_encoding = blocked
token_encoding.warmup_token_encoding()
assert started.wait(2)
assert estimate_message_tokens({"content": "hello"}) == 9
print("chat completed; exiting with download pending")
"""
result = subprocess.run(
[sys.executable, "-c", code], cwd=Path(__file__).resolve().parents[2],
env={**os.environ, "TIKTOKEN_CACHE_DIR": str(tmp_path)},
capture_output=True, text=True, timeout=10,
)
assert result.returncode == 0, result.stderr
assert "chat completed; exiting with download pending" in result.stdout
+43 -21
View File
@@ -1,6 +1,8 @@
import json
from nanobot.utils import helpers
import pytest
from nanobot.utils import helpers, token_encoding
from nanobot.utils.helpers import (
estimate_message_tokens,
estimate_prompt_tokens,
@@ -18,6 +20,39 @@ class _BrokenCounterProvider:
raise RuntimeError("counter unavailable")
@pytest.fixture(autouse=True)
def isolate_token_caches(monkeypatch, byte_encoding):
monkeypatch.setattr(token_encoding, "_encoding", byte_encoding)
helpers._TOOLS_TOKEN_CACHE.clear()
yield
helpers._TOOLS_TOKEN_CACHE.clear()
@pytest.mark.parametrize("text", ["hello world", "你好,世界🙂", "print(123)\n", "<|endoftext|>"])
def test_token_estimation_treats_prompt_text_as_ordinary(text, byte_encoding):
expected = len(byte_encoding.encode_ordinary(text)) + 4
assert estimate_prompt_tokens_chain(
_NoCounterProvider(), "custom-model", [{"role": "user", "content": text}],
) == (expected, "tiktoken")
assert estimate_message_tokens({"role": "user", "content": text}) == expected
assert len(byte_encoding.encode_ordinary(truncate_text_to_tokens(text * 100, 40))) <= 40
def test_provider_counter_does_not_initialize_fallback(monkeypatch):
def forbidden():
raise AssertionError("provider counter must take precedence")
class Provider:
def estimate_prompt_tokens(self, messages, tools=None, model=None):
assert model == "provider-specific-model"
return 1234, "provider-local"
monkeypatch.setattr(helpers, "_get_token_encoding", forbidden)
assert estimate_prompt_tokens_chain(
Provider(), "provider-specific-model", [{"role": "user", "content": "hi"}],
) == (1234, "provider-local")
def test_estimate_prompt_tokens_chain_falls_back_without_provider_counter() -> None:
tokens, source = estimate_prompt_tokens_chain(
_NoCounterProvider(),
@@ -58,7 +93,9 @@ def test_estimate_prompt_tokens_uses_conservative_fallback_when_tiktoken_fails(
messages,
)
actual_tokens = len(helpers.tiktoken.get_encoding("cl100k_base").encode(content)) + 4
encoding = token_encoding.get_token_encoding()
assert encoding is not None
actual_tokens = len(encoding.encode(content)) + 4
assert tokens == len(content.encode("utf-8")) + 4
assert tokens >= actual_tokens
assert chain_tokens == tokens
@@ -92,27 +129,16 @@ def test_truncate_text_to_tokens_uses_utf8_byte_budget_fallback(monkeypatch) ->
def test_estimate_prompt_tokens_caches_tools_encoding(monkeypatch) -> None:
helpers._get_token_encoding.cache_clear()
helpers._TOOLS_TOKEN_CACHE.clear()
class FakeEncoding:
def __init__(self) -> None:
self.encoded: list[str] = []
def encode(self, text: str) -> list[int]:
def encode_ordinary(self, text: str) -> list[int]:
self.encoded.append(text)
return list(range(max(1, len(text) // 4)))
fake_encoding = FakeEncoding()
get_encoding_calls = 0
def fake_get_encoding(name: str) -> FakeEncoding:
nonlocal get_encoding_calls
assert name == "cl100k_base"
get_encoding_calls += 1
return fake_encoding
monkeypatch.setattr(helpers.tiktoken, "get_encoding", fake_get_encoding)
monkeypatch.setattr(token_encoding, "_encoding", fake_encoding)
tools = [{"type": "function", "function": {"name": "demo", "description": "cached"}}]
messages = [{"role": "user", "content": "hello"}]
@@ -120,25 +146,21 @@ def test_estimate_prompt_tokens_caches_tools_encoding(monkeypatch) -> None:
second = estimate_prompt_tokens(messages, tools)
assert first == second
assert get_encoding_calls == 1
rendered_tools = "\n" + json.dumps(tools, ensure_ascii=False)
assert fake_encoding.encoded.count(rendered_tools) == 1
def test_estimate_prompt_tokens_recomputes_when_tool_items_change(monkeypatch) -> None:
helpers._get_token_encoding.cache_clear()
helpers._TOOLS_TOKEN_CACHE.clear()
class FakeEncoding:
def __init__(self) -> None:
self.encoded: list[str] = []
def encode(self, text: str) -> list[int]:
def encode_ordinary(self, text: str) -> list[int]:
self.encoded.append(text)
return list(range(max(1, len(text) // 4)))
fake_encoding = FakeEncoding()
monkeypatch.setattr(helpers.tiktoken, "get_encoding", lambda _name: fake_encoding)
monkeypatch.setattr(token_encoding, "_encoding", fake_encoding)
tools = [{"type": "function", "function": {"name": "before"}}]
messages = [{"role": "user", "content": "hello"}]