Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(tokens): warm fallback tokenizer in background (#5861)
chengyongru4a7ad00e4f58
diff --git a/conftest.py b/conftest.pyindex b81dda2e5..5de6db38e 100644--- a/conftest.py+++ b/conftest.py@@ -7,12 +7,20 @@ import sslimport sysfrom collections.abc import Iteratorfrom pathlib import Path+from threading import Threadimport certifiimport pytestfrom loguru import logger[email protected](autouse=True)+def _isolate_tokenizer_warmup(monkeypatch: pytest.MonkeyPatch) -> None:+ """Keep tests deterministic and out of the user's tokenizer cache and network."""+ monkeypatch.setattr("nanobot.utils.token_encoding._encoding", None)+ monkeypatch.setattr("nanobot.utils.token_encoding._warmup_thread", Thread())++@pytest.fixture(autouse=True)def _isolate_nanobot_log_activation() -> Iterator[None]:"""Keep CLI log settings from leaking into later tests in the same process."""diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex 154457750..b06ee5783 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -29,34 +29,25 @@ This separates failures into layers:If `nanobot agent -m "Hello!"` fails, fix that before debugging WebUI, Telegram, Discord, Docker, systemd, or any chat app.-`nanobot status` does not call the model. If provider/model setup is incomplete, it points to-WebUI **Settings → Models** or the CLI setup wizard, then prints the command to check again.+`nanobot status` does not call the model. If provider/model setup is incomplete, it points to WebUI **Settings → Models** or the CLI setup wizard, then prints the command to check again.## Session storage overlaps the workspace-Sessions live at `<config-dir>/sessions/<workspace-id>/`, outside the agent workspace.-If startup reports a conflict, compare the printed paths. A valid layout is-`bot/config.json`, `bot/sessions/`, and `bot/workspace/`.+Sessions live at `<config-dir>/sessions/<workspace-id>/`, outside the agent workspace. If startup reports a conflict, compare the printed paths. A valid layout is `bot/config.json`, `bot/sessions/`, and `bot/workspace/`.-`--workspace` overrides `agents.defaults.workspace` without moving sessions. The override-is temporary for `agent` and `gateway`; `webui --workspace` saves it to the config.+`--workspace` overrides `agents.defaults.workspace` without moving sessions. The override is temporary for `agent` and `gateway`; `webui --workspace` saves it to the config.To fix an existing instance:1. Stop the instance and back up its config directory and workspace.-2. Keep the workspace and `.nanobot/workspace-id` in place. Move the config file **and its- runtime data, including sessions**, to a directory outside the workspace.+2. Keep the workspace and `.nanobot/workspace-id` in place. Move the config file **and its runtime data, including sessions**, to a directory outside the workspace.3. Update `--config` in your launch command or service, check relative paths, and restart.-Moving only the config leaves history behind. Choosing a new workspace without moving-its contents (including memory, skills, and `.nanobot/workspace-id`) can start an empty-workspace with a different session identity.+Moving only the config leaves history behind. Choosing a new workspace without moving its contents (including memory, skills, and `.nanobot/workspace-id`) can start an empty workspace with a different session identity.## How to Read `nanobot status`-`nanobot status` does not call a model. It checks the selected config and workspace,-resolves environment references, and validates the local settings required by the active-provider/model without constructing a provider client.+`nanobot status` does not call a model. It checks the selected config and workspace, resolves environment references, and validates the local settings required by the active provider/model without constructing a provider client.The output has this shape:@@ -180,6 +171,10 @@ If you need a known-good snippet instead of diagnosis, use [`provider-cookbook.m| xAI returns 400 `invalid-argument` | Read the bounded `Response body` appended to the provider error. Hosted `x_search` is sent only when xAI's model catalog advertises `supportsBackendSearch`; the model ID `grok-4.5` itself is valid. || xAI model or X Search stops working after an upstream release | The integration follows Grok Build's public OAuth/proxy client contract. Update nanobot if xAI changes that contract. |+### Local Token Estimation++Gateway loads the fallback tokenizer in the background, caching it beside the active config under `cache/tiktoken` unless `TIKTOKEN_CACHE_DIR` or `DATA_GYM_CACHE_DIR` is set; chats use UTF-8 byte estimates while loading or after failure (restart to retry), and token estimates may differ from model usage.+## Langfuse ProblemsLangfuse tracing is optional and controlled by environment variables.@@ -222,17 +217,9 @@ nanobot gateway --verbose### Slow Optional Channel Dependency Installation-Before loading enabled channels, the gateway checks the dependencies declared by their-channel manifests. The CLI and WebUI normally install these dependencies when a channel is-enabled. Installation during startup is a recovery path for an enabled config whose Python-environment no longer has the required packages, for example after manually editing the-config, upgrading nanobot, or recreating an isolated `uv tool`/`pipx` environment. The-gateway waits for the install so an enabled channel is not silently skipped; later starts-skip the installation once the dependencies are present.+Before loading enabled channels, the gateway checks the dependencies declared by their channel manifests. The CLI and WebUI normally install these dependencies when a channel is enabled. Installation during startup is a recovery path for an enabled config whose Python environment no longer has the required packages, for example after manually editing the config, upgrading nanobot, or recreating an isolated `uv tool`/`pipx` environment. The gateway waits for the install so an enabled channel is not silently skipped; later starts skip the installation once the dependencies are present.-If access to PyPI is slow in your region, configure pip to use a trusted package index. The-installer honors the standard `PIP_INDEX_URL` environment variable, including when nanobot-itself was installed with `uv tool`:+If access to PyPI is slow in your region, configure pip to use a trusted package index. The installer honors the standard `PIP_INDEX_URL` environment variable, including when nanobot itself was installed with `uv tool`:```bashPIP_INDEX_URL=https://your-trusted-mirror.example/simple nanobot gateway@@ -256,9 +243,7 @@ systemctl --user daemon-reloadsystemctl --user restart nanobot-gateway.service```-For a system-level or custom service, use `sudo systemctl edit <unit>` instead. Prefer an-HTTPS index operated by an organization you trust, and do not put index credentials in-commands or logs.+For a system-level or custom service, use `sudo systemctl edit <unit>` instead. Prefer an HTTPS index operated by an organization you trust, and do not put index credentials in commands or logs.## WebUI Problemsdiff --git a/nanobot/cli/gateway_runtime.py b/nanobot/cli/gateway_runtime.pyindex 581a45e56..b5a298a63 100644--- a/nanobot/cli/gateway_runtime.py+++ b/nanobot/cli/gateway_runtime.py@@ -43,6 +43,7 @@ from nanobot.session.keys import ()from nanobot.utils.evaluator import evaluate_response, resolve_evaluator_promptfrom nanobot.utils.helpers import sync_workspace_templates+from nanobot.utils.token_encoding import warmup_token_encodingfrom nanobot.webui.build import BuildModefrom nanobot.webui.dev import WebUIDevError, WebUIDevServerfrom nanobot.webui.sidebar_state import read_webui_sidebar_state@@ -406,6 +407,7 @@ def _run_gateway(raise typer.Exit(1)console.print(f"{__logo__} Starting nanobot gateway version {__version__} on port {port}...")+ warmup_token_encoding()_prepare_webui_bundle_for_gateway(config,mode=webui_bundle_mode,diff --git a/nanobot/utils/helpers.py b/nanobot/utils/helpers.pyindex f02d728fd..d8552e66f 100644--- a/nanobot/utils/helpers.py+++ b/nanobot/utils/helpers.py@@ -14,14 +14,16 @@ import uuidfrom collections.abc import Iterablefrom contextlib import suppressfrom datetime import datetime-from functools import lru_cachefrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, TypeVar, cast, overload-import tiktokenfrom loguru import logger+from nanobot.utils.token_encoding import get_token_encoding as _get_token_encoding+if TYPE_CHECKING:+ from tiktoken import Encoding+from nanobot.providers.base import LLMUsage_TOOLS_TOKEN_CACHE_MAX_ENTRIES = 64@@ -104,11 +106,6 @@ def sanitize_surrogates_deep(value: Any) -> Any:return value-@lru_cache(maxsize=1)-def _get_token_encoding() -> Any:- return tiktoken.get_encoding("cl100k_base")--def _cache_tools_token_count(tools_id: int,fingerprint: tuple[int, ...],@@ -123,7 +120,7 @@ def _cache_tools_token_count(def _estimate_tools_tokens(- enc: Any,+ enc: Encoding,tools: list[dict[str, Any]],*,leading_separator: bool,@@ -144,7 +141,7 @@ def _estimate_tools_tokens(rendered = json.dumps(tools, ensure_ascii=False)if leading_separator:rendered = "\n" + rendered- token_count = len(enc.encode(rendered))+ token_count = len(enc.encode_ordinary(rendered))counts[leading_separator] = token_count_cache_tools_token_count(tools_id, fingerprint, counts)return token_count@@ -410,34 +407,35 @@ def truncate_text(text: str, max_chars: int) -> str:def truncate_text_to_tokens(text: str, max_tokens: int) -> str:"""Truncate text to a token budget with a stable suffix.- Unlike :func:`truncate_text`, this measures actual tokens, so the cap holds- regardless of language or content (CJK and code cost more tokens per char).- Falls back to a conservative UTF-8 byte budget if tiktoken is unavailable.+ Uses cl100k_base when ready, which may differ from the model's tokenizer.+ Falls back to a UTF-8 byte budget while loading or if initialization failed."""if max_tokens <= 0:return texttry:enc = _get_token_encoding()- tokens = enc.encode(text)- if len(tokens) <= max_tokens:- return text- suffix_tokens = enc.encode(_TRUNCATED_SUFFIX)- body_budget = max_tokens - len(suffix_tokens)- if body_budget <= 0:+ if enc is not None:+ tokens = enc.encode_ordinary(text)+ if len(tokens) <= max_tokens:+ return text+ suffix_tokens = enc.encode_ordinary(_TRUNCATED_SUFFIX)+ body_budget = max_tokens - len(suffix_tokens)+ if body_budget <= 0:+ return enc.decode(tokens[:max_tokens])+ for candidate_budget in range(body_budget, -1, -1):+ result = enc.decode(tokens[:candidate_budget]) + _TRUNCATED_SUFFIX+ if len(enc.encode_ordinary(result)) <= max_tokens:+ return resultreturn enc.decode(tokens[:max_tokens])- for candidate_budget in range(body_budget, -1, -1):- result = enc.decode(tokens[:candidate_budget]) + _TRUNCATED_SUFFIX- if len(enc.encode(result)) <= max_tokens:- return result- return enc.decode(tokens[:max_tokens])except Exception:- if len(text.encode("utf-8")) <= max_tokens:- return text- suffix_bytes = len(_TRUNCATED_SUFFIX.encode("utf-8"))- if max_tokens <= suffix_bytes:- return _truncate_text_to_utf8_bytes(text, max_tokens)- body = _truncate_text_to_utf8_bytes(text, max_tokens - suffix_bytes)- return body + _TRUNCATED_SUFFIX+ pass+ if len(text.encode("utf-8")) <= max_tokens:+ return text+ suffix_bytes = len(_TRUNCATED_SUFFIX.encode("utf-8"))+ if max_tokens <= suffix_bytes:+ return _truncate_text_to_utf8_bytes(text, max_tokens)+ body = _truncate_text_to_utf8_bytes(text, max_tokens - suffix_bytes)+ return body + _TRUNCATED_SUFFIXdef _truncate_text_to_utf8_bytes(text: str, max_bytes: int) -> str:@@ -812,20 +810,22 @@ def _estimate_prompt_tokens_with_source(per_message_overhead = len(messages) * 4try:enc = _get_token_encoding()- tool_tokens = (- _estimate_tools_tokens(enc, tools, leading_separator=bool(parts)) if tools else 0- )- message_tokens = len(enc.encode(message_payload)) if message_payload else 0- return message_tokens + tool_tokens + per_message_overhead, "tiktoken"+ if enc is not None:+ tool_tokens = (+ _estimate_tools_tokens(enc, tools, leading_separator=bool(parts)) if tools else 0+ )+ message_tokens = len(enc.encode_ordinary(message_payload)) if message_payload else 0+ return message_tokens + tool_tokens + per_message_overhead, "tiktoken"except Exception:- tool_payload = (- ("\n" if message_payload else "") + json.dumps(tools, ensure_ascii=False)- if tools- else ""- )- payload = message_payload + tool_payload- estimated = len(payload.encode("utf-8"))- return estimated + per_message_overhead, "heuristic"+ pass+ tool_payload = (+ ("\n" if message_payload else "") + json.dumps(tools, ensure_ascii=False)+ if tools+ else ""+ )+ payload = message_payload + tool_payload+ estimated = len(payload.encode("utf-8"))+ return estimated + per_message_overhead, "heuristic"def estimate_prompt_tokens(@@ -871,9 +871,11 @@ def estimate_message_tokens(message: dict[str, Any]) -> int:return 4try:enc = _get_token_encoding()- return max(4, len(enc.encode(payload)) + 4)+ if enc is not None:+ return max(4, len(enc.encode_ordinary(payload)) + 4)except Exception:- return max(4, len(payload.encode("utf-8")) + 4)+ pass+ return max(4, len(payload.encode("utf-8")) + 4)def estimate_prompt_tokens_chain(diff --git a/nanobot/utils/token_encoding.py b/nanobot/utils/token_encoding.pynew file mode 100644index 000000000..ac5b62ba7--- /dev/null+++ b/nanobot/utils/token_encoding.py@@ -0,0 +1,48 @@+"""Background initialization of the fallback token counter."""++import os+from threading import Lock, Thread++import tiktoken+from loguru import logger++_encoding: tiktoken.Encoding | None = None+_warmup_thread: Thread | None = None+_warmup_lock = Lock()+++def _load_encoding() -> None:+ global _encoding+ try:+ if "TIKTOKEN_CACHE_DIR" not in os.environ and "DATA_GYM_CACHE_DIR" not in os.environ:+ from nanobot.config.paths import get_data_dir++ os.environ.setdefault("TIKTOKEN_CACHE_DIR", str(get_data_dir() / "cache" / "tiktoken"))+ _encoding = tiktoken.get_encoding("cl100k_base")+ except Exception as exc:+ logger.warning(+ "Token encoding unavailable ({}); using UTF-8 byte estimates until restart.", exc,+ )+++def warmup_token_encoding() -> None:+ """Start one process-wide load; tiktoken reuses its persistent vocabulary cache."""+ global _warmup_thread+ with _warmup_lock:+ if _warmup_thread is not None:+ return+ # A stalled upstream download must not hold up asyncio's executor shutdown.+ _warmup_thread = Thread(target=_load_encoding, name="nanobot-tokenizer", daemon=True)+ try:+ _warmup_thread.start()+ except Exception as exc:+ logger.warning(+ "Token encoding unavailable ({}); using UTF-8 byte estimates until restart.", exc,+ )+++def get_token_encoding() -> tiktoken.Encoding | None:+ """Return immediately, using byte estimates while loading or after failure."""+ if _warmup_thread is None:+ warmup_token_encoding()+ return _encodingdiff --git a/tests/agent/test_codex_context_pressure.py b/tests/agent/test_codex_context_pressure.pyindex 05692b341..4a5af7127 100644--- a/tests/agent/test_codex_context_pressure.py+++ b/tests/agent/test_codex_context_pressure.py@@ -22,7 +22,7 @@ from nanobot.providers.openai_codex_provider import OpenAICodexProvider, _CodexHfrom 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]diff --git a/tests/agent/test_consolidator.py b/tests/agent/test_consolidator.pyindex e4fc3b273..08ac5ec16 100644--- a/tests/agent/test_consolidator.py+++ b/tests/agent/test_consolidator.py@@ -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"),diff --git a/tests/agent/test_dream.py b/tests/agent/test_dream.pyindex 8070ddc7e..2f9faf1a5 100644--- a/tests/agent/test_dream.py+++ b/tests/agent/test_dream.py@@ -396,6 +396,7 @@ class TestEphemeralDirect:provider.get_default_model.return_value = "test-model"provider.supports_tools = Trueprovider.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 = Trueprovider.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,diff --git a/tests/agent/test_history_replay.py b/tests/agent/test_history_replay.pyindex b2fc21482..51a5ef40e 100644--- a/tests/agent/test_history_replay.py+++ b/tests/agent/test_history_replay.py@@ -86,6 +86,9 @@ async def test_process_message_hands_complete_replay_to_runner(tmp_path: Path) -@pytest.mark.asyncioasync 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))diff --git a/tests/agent/test_session_model_runtime.py b/tests/agent/test_session_model_runtime.pyindex dd1dee5a6..16eb159ef 100644--- a/tests/agent/test_session_model_runtime.py+++ b/tests/agent/test_session_model_runtime.py@@ -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.asyncioasync def test_sessions_run_concurrently_with_isolated_model_presets(tmp_path) -> None:diff --git a/tests/cli/test_commands.py b/tests/cli/test_commands.pyindex 8785fa63c..a8cab903c 100644--- a/tests/cli/test_commands.py+++ b/tests/cli/test_commands.py@@ -2974,6 +2974,24 @@ def test_gateway_uses_workspace_from_config_by_default(monkeypatch, tmp_path: Paassert 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()diff --git a/tests/command/test_compact_command.py b/tests/command/test_compact_command.pyindex 4482faccc..13207ab09 100644--- a/tests/command/test_compact_command.py+++ b/tests/command/test_compact_command.py@@ -363,6 +363,7 @@ async def test_stop_finishes_inflight_compaction_as_cancelled(loop) -> None:@pytest.mark.asyncioasync 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")diff --git a/tests/utils/conftest.py b/tests/utils/conftest.pynew file mode 100644index 000000000..3cdd59877--- /dev/null+++ b/tests/utils/conftest.py@@ -0,0 +1,13 @@+import pytest+import tiktoken+++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},+ )diff --git a/tests/utils/test_helpers.py b/tests/utils/test_helpers.pyindex 5d4168d10..0afe01bd5 100644--- a/tests/utils/test_helpers.py+++ b/tests/utils/test_helpers.py@@ -3,9 +3,8 @@ import osfrom pathlib import Pathimport pytest-import tiktoken-from nanobot.utils import helpers+from nanobot.utils import helpers, token_encodingfrom 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_000result = truncate_text_to_tokens(text, 50)assert result.endswith("\n... (truncated)")- assert len(enc.encode(result)) <= 50+ assert len(byte_encoding.encode_ordinary(result)) <= 50def test_truncate_text_to_tokens_non_positive_budget_returns_text():diff --git a/tests/utils/test_token_encoding.py b/tests/utils/test_token_encoding.pynew file mode 100644index 000000000..fb075e7be--- /dev/null+++ b/tests/utils/test_token_encoding.py@@ -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++[email protected](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)++[email protected]("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.stdoutdiff --git a/tests/utils/test_token_estimation.py b/tests/utils/test_token_estimation.pyindex f3949ad49..9f1514099 100644--- a/tests/utils/test_token_estimation.py+++ b/tests/utils/test_token_estimation.py@@ -1,6 +1,8 @@import json-from nanobot.utils import helpers+import pytest++from nanobot.utils import helpers, token_encodingfrom nanobot.utils.helpers import (estimate_message_tokens,estimate_prompt_tokens,@@ -18,6 +20,39 @@ class _BrokenCounterProvider:raise RuntimeError("counter unavailable")[email protected](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()++[email protected]("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)) + 4assert tokens == len(content.encode("utf-8")) + 4assert tokens >= actual_tokensassert 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 == 1rendered_tools = "\n" + json.dumps(tools, ensure_ascii=False)assert fake_encoding.encoded.count(rendered_tools) == 1def 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"}]