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:
1 parent
e0b8efa0be
commit
4a7ad00e4f
16 files changed
+378
-101
No files matched your search
@@ -22,7 +22,7 @@ from nanobot.providers.openai_codex_provider import OpenAICodexProvider, _CodexH
|
||||
from nanobot.providers.openai_responses import build_responses_state
|
||||
|
||||
|
||||
def _request_state(provider, *, prior_tokens=180_000, repetitions=15_000):
|
||||
def _request_state(provider, *, prior_tokens=180_000, repetitions=12_000):
|
||||
model = "openai-codex/gpt-5.6-sol"
|
||||
accepted = [
|
||||
{"role": "system", "content": "Continue the coding task."},
|
||||
@@ -42,6 +42,8 @@ def _request_state(provider, *, prior_tokens=180_000, repetitions=15_000):
|
||||
],
|
||||
usage=LLMUsage.reported(input_tokens=prior_tokens, output_tokens=10),
|
||||
)
|
||||
# The default delta pressures prior state but fits after compaction, even with
|
||||
# UTF-8 byte estimates while the fallback tokenizer is unavailable.
|
||||
delta = {"role": "tool", "name": "read_file", "tool_call_id": "read-1",
|
||||
"content": "source_line\n" * repetitions}
|
||||
raw = [*deepcopy(accepted), delta]
|
||||
|
||||
@@ -136,6 +136,7 @@ class TestTurnTranscriptSummary:
|
||||
runtime,
|
||||
summary,
|
||||
):
|
||||
runtime = replace(runtime, context_window_tokens=4096)
|
||||
accepted = [
|
||||
{"role": "system", "content": "stable system"},
|
||||
{"role": "user", "content": "accepted history"},
|
||||
@@ -401,7 +402,7 @@ class TestConsolidatorSummarize:
|
||||
mock_provider,
|
||||
runtime,
|
||||
):
|
||||
runtime = replace(runtime, generation=GenerationSettings(max_tokens=96))
|
||||
runtime = replace(runtime, generation=GenerationSettings(max_tokens=256))
|
||||
mock_provider.chat_stream_with_retry.side_effect = RuntimeError("API error")
|
||||
|
||||
result = await _archive(
|
||||
@@ -910,6 +911,7 @@ class TestCompactIdleSession:
|
||||
store,
|
||||
runtime,
|
||||
):
|
||||
runtime = replace(runtime, generation=GenerationSettings(max_tokens=256))
|
||||
mock_provider.chat_stream_with_retry.side_effect = [
|
||||
LLMResponse(content="Earlier durable checkpoint.", finish_reason="stop"),
|
||||
RuntimeError("LLM unavailable"),
|
||||
|
||||
@@ -396,6 +396,7 @@ class TestEphemeralDirect:
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.supports_tools = True
|
||||
provider.generation = MagicMock(max_tokens=4096)
|
||||
provider.estimate_prompt_tokens.return_value = (100, "test")
|
||||
provider.chat_stream_with_retry = AsyncMock(
|
||||
return_value=LLMResponse(content="done", tool_calls=[], finish_reason="stop", usage=None)
|
||||
)
|
||||
@@ -671,6 +672,7 @@ class TestEphemeralHooks:
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.supports_tools = True
|
||||
provider.generation = MagicMock(max_tokens=4096)
|
||||
provider.estimate_prompt_tokens.return_value = (100, "test")
|
||||
provider.chat_stream_with_retry = AsyncMock(
|
||||
return_value=LLMResponse(
|
||||
content="done", finish_reason="stop", tool_calls=[], usage=None,
|
||||
|
||||
@@ -86,6 +86,9 @@ async def test_process_message_hands_complete_replay_to_runner(tmp_path: Path) -
|
||||
@pytest.mark.asyncio
|
||||
async def test_runner_checkpoint_keeps_current_user_as_replay_boundary(tmp_path: Path) -> None:
|
||||
loop = _make_loop(tmp_path, context_window_tokens=8_000)
|
||||
loop.provider.estimate_prompt_tokens.side_effect = (
|
||||
lambda messages, tools, model: (100 * len(messages), "test")
|
||||
)
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(
|
||||
return_value=LLMResponse(content="ok", tool_calls=[], usage=None)
|
||||
)
|
||||
|
||||
@@ -31,6 +31,9 @@ class RecordingProvider(LLMProvider):
|
||||
def get_default_model(self) -> str:
|
||||
return self.name
|
||||
|
||||
def estimate_prompt_tokens(self, messages, tools=None, model=None) -> tuple[int, str]:
|
||||
return 100, "test"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sessions_run_concurrently_with_isolated_model_presets(tmp_path) -> None:
|
||||
|
||||
@@ -2974,6 +2974,24 @@ def test_gateway_uses_workspace_from_config_by_default(monkeypatch, tmp_path: Pa
|
||||
assert seen["workspace"] == Path(config.agents.defaults.workspace)
|
||||
|
||||
|
||||
def test_gateway_starts_tokenizer_warmup_before_provider_setup(monkeypatch, tmp_path: Path) -> None:
|
||||
config_file = _write_instance_config(tmp_path)
|
||||
config = Config()
|
||||
config.agents.defaults.workspace = str(tmp_path / "workspace")
|
||||
events = []
|
||||
|
||||
def stop_provider(_config):
|
||||
events.append("provider")
|
||||
raise _StopGatewayError("stop")
|
||||
|
||||
_patch_cli_command_runtime(monkeypatch, config, make_provider=stop_provider)
|
||||
monkeypatch.setattr(cli_gateway_runtime, "warmup_token_encoding", lambda: events.append("warmup"))
|
||||
result = runner.invoke(app, ["gateway", "--config", str(config_file)])
|
||||
|
||||
assert isinstance(result.exception, _StopGatewayError)
|
||||
assert events == ["warmup", "provider"]
|
||||
|
||||
|
||||
def test_gateway_workspace_option_overrides_config(monkeypatch, tmp_path: Path) -> None:
|
||||
config_file = _write_instance_config(tmp_path)
|
||||
config = Config()
|
||||
|
||||
@@ -363,6 +363,7 @@ async def test_stop_finishes_inflight_compaction_as_cancelled(loop) -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_idle_and_manual_compact_share_persisted_checkpoint(loop) -> None:
|
||||
loop.provider.estimate_prompt_tokens.return_value = (100, "test")
|
||||
key = "cli:test"
|
||||
session = loop.sessions.get_or_create(key)
|
||||
session.add_message("user", "large tool turn")
|
||||
|
||||
@@ -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},
|
||||
)
|
||||
@@ -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():
|
||||
|
||||
@@ -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
|
||||
@@ -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"}]
|
||||
|
||||
Reference in new issue
Block a user