diff --git a/nanobot/providers/base.py b/nanobot/providers/base.py index 299ce7c30..7867f0f95 100644 --- a/nanobot/providers/base.py +++ b/nanobot/providers/base.py @@ -29,6 +29,7 @@ from nanobot.events import ( ) from nanobot.llm_usage.types import LLMUsage as LLMUsage from nanobot.providers.generation import GenerationSettings as GenerationSettings +from nanobot.utils.cancellation import shield_and_drain from nanobot.utils.helpers import sanitize_surrogates_deep if TYPE_CHECKING: @@ -433,6 +434,7 @@ class LLMProvider(ABC): self.provider_name = provider_name self.generation: GenerationSettings = GenerationSettings() self._llm_call_observer: LLMCallObserver | None = None + self._usage_estimation_slots = asyncio.Semaphore(2) def set_llm_call_observer(self, observer: LLMCallObserver | None) -> None: """Attach a fail-open observer for each physical retry-managed call.""" @@ -497,7 +499,59 @@ class LLMProvider(ABC): observer = self._llm_call_observer if observer is None: return response + finished_at_ns = time.monotonic_ns() usage = self._usage_for_call(response, kwargs) + return self._record_llm_call( + response, kwargs, observer=observer, usage=usage, + started_at_ms=started_at_ms, started_at_ns=started_at_ns, + finished_at_ns=finished_at_ns, stream=stream, + ) + + async def _observe_llm_call_async( + self, + response: LLMResponse, + kwargs: dict[str, Any], + *, + started_at_ms: int, + started_at_ns: int, + stream: bool, + ) -> LLMResponse: + observer = self._llm_call_observer + if ( + observer is None + or response.finish_reason in {"error", "cancelled"} + or (response.usage is not None and response.usage.total_tokens > 0) + ): + return self._observe_llm_call( + response, kwargs, started_at_ms=started_at_ms, + started_at_ns=started_at_ns, stream=stream, + ) + finished_at_ns = time.monotonic_ns() + + async def observe() -> LLMResponse: + async with self._usage_estimation_slots: + usage = await asyncio.to_thread(self._usage_for_call, response, kwargs) + return self._record_llm_call( + response, kwargs, observer=observer, usage=usage, + started_at_ms=started_at_ms, started_at_ns=started_at_ns, + finished_at_ns=finished_at_ns, stream=stream, + ) + + # Once the request completes, settle its usage and observer before cancellation. + return await shield_and_drain(observe()) + + def _record_llm_call( + self, + response: LLMResponse, + kwargs: dict[str, Any], + *, + observer: LLMCallObserver, + usage: LLMUsage | None, + started_at_ms: int, + started_at_ns: int, + finished_at_ns: int, + stream: bool, + ) -> LLMResponse: if usage is not None: response.usage = usage model_value = kwargs.get("model") @@ -508,7 +562,7 @@ class LLMProvider(ABC): observer(LLMCallRecord( started_at_ms=started_at_ms, - duration_ms=max(0, (time.monotonic_ns() - started_at_ns) // 1_000_000), + duration_ms=max(0, (finished_at_ns - started_at_ns) // 1_000_000), provider=self.provider_name, model=model, source=current_llm_usage_source(), @@ -1014,7 +1068,7 @@ class LLMProvider(ABC): raise except Exception as exc: response = self._error_response_from_exception(exc) - return self._observe_llm_call( + return await self._observe_llm_call_async( response, kwargs, started_at_ms=started_at_ms, @@ -1159,7 +1213,7 @@ class LLMProvider(ABC): raise except Exception as exc: response = self._error_response_from_exception(exc) - return self._observe_llm_call( + return await self._observe_llm_call_async( _attach_stream_timing(response), kwargs, started_at_ms=started_at_ms, diff --git a/nanobot/utils/cancellation.py b/nanobot/utils/cancellation.py index 29f68948e..ef7bba4ce 100644 --- a/nanobot/utils/cancellation.py +++ b/nanobot/utils/cancellation.py @@ -3,8 +3,45 @@ from __future__ import annotations import asyncio +from collections.abc import Awaitable +from typing import TypeVar + +_T = TypeVar("_T") def task_is_cancelling() -> bool: task = asyncio.current_task() return task is not None and task.cancelling() > 0 + + +async def shield_and_drain(awaitable: Awaitable[_T]) -> _T: + """Finish an accepted operation before propagating caller cancellation. + + Thread workers cannot be stopped by cancelling their awaiting task. Keep + their result and any subsequent settlement attached until both finish. + """ + settlement = asyncio.ensure_future(awaitable) + cancellation: asyncio.CancelledError | None = None + + while not settlement.done(): + try: + result = await asyncio.shield(settlement) + except asyncio.CancelledError as exc: + cancellation = cancellation or exc + except BaseException: + if cancellation is None: + raise + break + else: + if cancellation is not None: + raise cancellation + return result + + if cancellation is not None: + try: + settlement.result() + except BaseException: + # Cancellation wins after the operation's outcome has been observed. + pass + raise cancellation + return settlement.result() diff --git a/nanobot/utils/helpers.py b/nanobot/utils/helpers.py index e5c91ec2b..0af917472 100644 --- a/nanobot/utils/helpers.py +++ b/nanobot/utils/helpers.py @@ -14,6 +14,7 @@ from collections.abc import Iterable from contextlib import suppress from datetime import datetime from pathlib import Path +from threading import Lock from typing import TYPE_CHECKING, Any, TypeVar, cast, overload from loguru import logger @@ -29,6 +30,7 @@ if TYPE_CHECKING: _TOOLS_TOKEN_CACHE_MAX_ENTRIES = 64 _TOOLS_TOKEN_CACHE: dict[int, tuple[tuple[int, ...], dict[bool, int]]] = {} +_TOOLS_TOKEN_CACHE_LOCK = Lock() _T = TypeVar("_T") @@ -112,12 +114,16 @@ def _cache_tools_token_count( fingerprint: tuple[int, ...], counts: dict[bool, int], ) -> None: - if ( - tools_id not in _TOOLS_TOKEN_CACHE - and len(_TOOLS_TOKEN_CACHE) >= _TOOLS_TOKEN_CACHE_MAX_ENTRIES - ): - _TOOLS_TOKEN_CACHE.pop(next(iter(_TOOLS_TOKEN_CACHE))) - _TOOLS_TOKEN_CACHE[tools_id] = (fingerprint, counts) + with _TOOLS_TOKEN_CACHE_LOCK: + cached = _TOOLS_TOKEN_CACHE.get(tools_id) + if cached is not None and cached[0] == fingerprint: + counts = {**cached[1], **counts} + if ( + tools_id not in _TOOLS_TOKEN_CACHE + and len(_TOOLS_TOKEN_CACHE) >= _TOOLS_TOKEN_CACHE_MAX_ENTRIES + ): + _TOOLS_TOKEN_CACHE.pop(next(iter(_TOOLS_TOKEN_CACHE))) + _TOOLS_TOKEN_CACHE[tools_id] = (fingerprint, counts) def _estimate_tools_tokens( @@ -130,14 +136,15 @@ def _estimate_tools_tokens( # ToolRegistry keeps the returned definitions list alive until the registry changes. tools_id = id(tools) fingerprint = tuple(id(tool) for tool in tools) - cached = _TOOLS_TOKEN_CACHE.get(tools_id) - if cached and cached[0] == fingerprint: - token_count = cached[1].get(leading_separator) - if token_count is not None: - return token_count - counts = cached[1] - else: - counts = {} + with _TOOLS_TOKEN_CACHE_LOCK: + cached = _TOOLS_TOKEN_CACHE.get(tools_id) + if cached and cached[0] == fingerprint: + token_count = cached[1].get(leading_separator) + if token_count is not None: + return token_count + counts = dict(cached[1]) + else: + counts = {} rendered = json.dumps(tools, ensure_ascii=False) if leading_separator: diff --git a/tests/providers/test_llm_usage_observer.py b/tests/providers/test_llm_usage_observer.py index 0e5cbc097..3ef6662c4 100644 --- a/tests/providers/test_llm_usage_observer.py +++ b/tests/providers/test_llm_usage_observer.py @@ -1,13 +1,16 @@ from __future__ import annotations import asyncio -from collections.abc import Iterator +import threading +from collections.abc import Callable, Iterator from types import SimpleNamespace import pytest -from nanobot.llm_usage.context import llm_usage_source +from nanobot.llm_usage.context import current_llm_usage_source, llm_usage_source from nanobot.llm_usage.models import LLMCallRecord +from nanobot.llm_usage.service import record_llm_call +from nanobot.llm_usage.store import LLMUsageStore from nanobot.providers.base import LLMProvider, LLMResponse, LLMUsage from nanobot.providers.fallback_provider import FallbackProvider @@ -18,8 +21,10 @@ class _SequenceProvider(LLMProvider): def __init__(self, responses: Iterator[LLMResponse]) -> None: super().__init__(provider_name="test-provider") self._responses = responses + self.calls = 0 async def chat(self, **_kwargs: object) -> LLMResponse: + self.calls += 1 return next(self._responses) def get_default_model(self) -> str: @@ -30,6 +35,17 @@ class _NoRetryProvider(_SequenceProvider): _CHAT_RETRY_DELAYS = () +class _EstimatingProvider(_SequenceProvider): + def __init__( + self, responses: Iterator[LLMResponse], estimate: Callable[[], tuple[int, str]], + ) -> None: + super().__init__(responses) + self.estimate = estimate + + def estimate_prompt_tokens(self, messages, tools=None, model=None) -> tuple[int, str]: + return self.estimate() + + class _BlockingProvider(LLMProvider): async def chat(self, **_kwargs: object) -> LLMResponse: await asyncio.Event().wait() @@ -64,7 +80,8 @@ class _StreamingProvider(LLMProvider): @pytest.mark.asyncio -async def test_observer_receives_every_retry_attempt() -> None: +@pytest.mark.parametrize("stream", [False, True]) +async def test_observer_receives_every_retry_attempt(stream: bool) -> None: provider = _SequenceProvider( iter( [ @@ -86,14 +103,17 @@ async def test_observer_receives_every_retry_attempt() -> None: ) events: list[LLMCallRecord] = [] provider.set_llm_call_observer(events.append) + call = provider.chat_stream_with_retry if stream else provider.chat_with_retry with llm_usage_source("api"): - response = await provider.chat_with_retry( + response = await call( messages=[{"role": "user", "content": "hello"}], model="selected-model", ) assert response.finish_reason == "stop" + assert response.content == "ok" + assert provider.calls == 2 assert len(events) == 2 assert [event.finish_reason for event in events] == ["error", "stop"] assert all(event.provider == "test-provider" for event in events) @@ -101,6 +121,8 @@ async def test_observer_receives_every_retry_attempt() -> None: assert all(event.source == "api" for event in events) assert events[1].usage is not None assert events[1].usage.cache_read_tokens == 60 + assert events[1].usage.source == "reported" + assert response.usage == events[1].usage @pytest.mark.asyncio @@ -120,18 +142,228 @@ async def test_observer_estimates_missing_success_usage_without_storing_content( @pytest.mark.asyncio -async def test_observer_failure_never_breaks_provider_call() -> None: +@pytest.mark.parametrize("stream", [False, True]) +async def test_observer_failure_never_breaks_provider_call(stream: bool) -> None: provider = _SequenceProvider(iter([LLMResponse(content="ok")])) def _fail(_event: LLMCallRecord) -> None: raise RuntimeError("disk unavailable") provider.set_llm_call_observer(_fail) - response = await provider.chat_with_retry( + call = provider.chat_stream_with_retry if stream else provider.chat_with_retry + response = await call( messages=[{"role": "user", "content": "hello"}], ) assert response.content == "ok" + assert response.usage is not None and response.usage.source == "estimated" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("cancel", [False, True]) +async def test_missing_usage_keeps_loop_responsive_and_settles_before_cancellation( + monkeypatch, stream: bool, cancel: bool, +) -> None: + loop = asyncio.get_running_loop() + entered = asyncio.Event() + release = threading.Event() + finished = threading.Event() + sources = [] + worker_threads = [] + events: list[LLMCallRecord] = [] + observer_loops = [] + clock = [1_000_000_000] + monkeypatch.setattr("nanobot.providers.base.time.monotonic_ns", lambda: clock[0]) + + def estimate() -> tuple[int, str]: + sources.append(current_llm_usage_source()) + worker_threads.append(threading.get_ident()) + loop.call_soon_threadsafe(entered.set) + assert release.wait(5), "estimator was not released" + finished.set() + return 17, "provider-local" + + provider = _EstimatingProvider(iter([LLMResponse(content="hello")]), estimate) + original_chat = provider.chat + + async def chat(**kwargs): + response = await original_chat(**kwargs) + clock[0] = 1_013_000_000 + return response + + monkeypatch.setattr(provider, "chat", chat) + + def observe(event: LLMCallRecord) -> None: + observer_loops.append(asyncio.get_running_loop()) + events.append(event) + + provider.set_llm_call_observer(observe) + call = provider.chat_stream_with_retry if stream else provider.chat_with_retry + kwargs = {"messages": [{"role": "user", "content": "hello"}]} + if stream: + kwargs["on_content_delta"] = lambda _delta: asyncio.sleep(0) + with llm_usage_source("api"): + task = asyncio.create_task(call(**kwargs)) + try: + await asyncio.wait_for(entered.wait(), timeout=5) + beats = [] + + async def heartbeat() -> None: + for tick in range(3): + await asyncio.sleep(0) + beats.append(tick) + + await asyncio.wait_for(heartbeat(), timeout=1) + assert beats == [0, 1, 2] + assert len(worker_threads) == 1 + assert worker_threads[0] != threading.get_ident() + assert sources == ["api"] + assert provider.calls == 1 + assert not events + clock[0] = 6_000_000_000 + if cancel: + for _ in range(2): + task.cancel() + await asyncio.sleep(0) + assert not task.done() + release.set() + if cancel: + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(task, timeout=5) + else: + response = await asyncio.wait_for(task, timeout=5) + assert response.content == "hello" + assert response.usage == events[0].usage + assert finished.is_set() + assert len(events) == 1 + assert events[0].source == "api" + assert events[0].stream == stream + assert events[0].finish_reason == "stop" + assert events[0].duration_ms == 13 + assert events[0].usage is not None + assert events[0].usage.source == "estimated" + assert events[0].usage.input_tokens == 17 + if stream: + assert events[0].usage.ttft_ms == 13 + assert events[0].usage.generation_ms == 1 + assert observer_loops == [loop] + assert provider.calls == 1 + finally: + release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +async def test_provider_bounds_estimators_and_drains_cancelled_queued_call() -> None: + loop = asyncio.get_running_loop() + two_entered = asyncio.Event() + release = threading.Event() + lock = threading.Lock() + active = peak = completed = 0 + + def estimate() -> tuple[int, str]: + nonlocal active, peak, completed + with lock: + active += 1 + peak = max(peak, active) + if active == 2: + loop.call_soon_threadsafe(two_entered.set) + assert release.wait(5), "estimators were not released" + with lock: + active -= 1 + completed += 1 + return 17, "provider-local" + + provider = _EstimatingProvider( + iter([LLMResponse(content=str(index)) for index in range(3)]), estimate, + ) + events: list[LLMCallRecord] = [] + provider.set_llm_call_observer(events.append) + tasks = [asyncio.create_task(provider.chat_with_retry(messages=[])) for _ in range(3)] + try: + await asyncio.wait_for(two_entered.wait(), timeout=5) + assert provider.calls == 3 + tasks[2].cancel() + await asyncio.sleep(0) + assert not tasks[2].done() + release.set() + results = await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), timeout=5) + assert isinstance(results[2], asyncio.CancelledError) + assert [result.content for result in results[:2]] == ["0", "1"] + assert peak == 2 + assert active == 0 + assert completed == 3 + assert len(events) == 3 + assert all(event.finish_reason == "stop" for event in events) + finally: + release.set() + for task in tasks: + if not task.done(): + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("kind", ["reported", "error", "unobserved"]) +async def test_usage_fast_paths_skip_local_estimation(stream: bool, kind: str) -> None: + estimates = [] + + def estimate() -> tuple[int, str]: + estimates.append(True) + return 17, "provider-local" + + expected = LLMResponse(content="ok") + if kind == "reported": + expected.usage = LLMUsage.reported(input_tokens=12, output_tokens=2) + elif kind == "error": + expected.finish_reason = "error" + expected.error_should_retry = False + provider = _EstimatingProvider(iter([expected]), estimate) + events: list[LLMCallRecord] = [] + if kind != "unobserved": + provider.set_llm_call_observer(events.append) + call = provider.chat_stream_with_retry if stream else provider.chat_with_retry + response = await call(messages=[]) + assert response is expected + assert estimates == [] + assert len(events) == (0 if kind == "unobserved" else 1) + if kind == "reported": + assert response.usage is not None and response.usage.source == "reported" + else: + assert response.usage is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize("stream", [False, True]) +async def test_gateway_usage_observer_records_missing_usage_and_retry( + monkeypatch, tmp_path, stream: bool, +) -> None: + store = LLMUsageStore(tmp_path / "usage.sqlite3") + monkeypatch.setattr("nanobot.llm_usage.service.get_llm_usage_store", lambda: store) + provider = _SequenceProvider(iter([ + LLMResponse(content="temporary failure", finish_reason="error", error_kind="timeout"), + LLMResponse(content="hello"), + ])) + provider.set_llm_call_observer(record_llm_call) + call = provider.chat_stream_with_retry if stream else provider.chat_with_retry + try: + with llm_usage_source("api"): + response = await call(messages=[{"role": "user", "content": "hello"}]) + assert response.content == "hello" + assert response.usage is not None and response.usage.source == "estimated" + assert provider.calls == 2 + records = list(reversed(store.recent_calls())) + assert [record["finish_reason"] for record in records] == ["error", "stop"] + assert all(record["source"] == "api" for record in records) + assert all(record["stream"] == int(stream) for record in records) + assert records[0]["total_tokens"] is None + assert records[1]["total_tokens"] == response.usage.total_tokens + finally: + store.close() @pytest.mark.asyncio diff --git a/tests/utils/test_token_estimation.py b/tests/utils/test_token_estimation.py index 9f1514099..f1c636ff5 100644 --- a/tests/utils/test_token_estimation.py +++ b/tests/utils/test_token_estimation.py @@ -1,4 +1,6 @@ import json +import threading +from concurrent.futures import ThreadPoolExecutor import pytest @@ -150,6 +152,32 @@ def test_estimate_prompt_tokens_caches_tools_encoding(monkeypatch) -> None: assert fake_encoding.encoded.count(rendered_tools) == 1 +def test_concurrent_prompt_estimates_cache_both_tool_separator_counts(monkeypatch) -> None: + tools = [{"type": "function", "function": {"name": "demo"}}] + rendered = json.dumps(tools, ensure_ascii=False) + barrier = threading.Barrier(2) + encoded_tools = [] + + class Encoding: + def encode_ordinary(self, text: str) -> list[int]: + if text in (rendered, "\n" + rendered): + encoded_tools.append(text) + if len(encoded_tools) <= 2: + barrier.wait(timeout=5) + return list(text.encode("utf-8")) + + monkeypatch.setattr(helpers, "_get_token_encoding", Encoding) + messages = [{"role": "user", "content": "hello"}] + with ThreadPoolExecutor(max_workers=2) as pool: + empty = pool.submit(estimate_prompt_tokens, [], tools) + nonempty = pool.submit(estimate_prompt_tokens, messages, tools) + assert empty.result(timeout=5) == len(rendered) + assert nonempty.result(timeout=5) == len(rendered) + 1 + len("hello") + 4 + assert estimate_prompt_tokens([], tools) == len(rendered) + assert estimate_prompt_tokens(messages, tools) == len(rendered) + 1 + len("hello") + 4 + assert sorted(encoded_tools) == sorted([rendered, "\n" + rendered]) + + def test_estimate_prompt_tokens_recomputes_when_tool_items_change(monkeypatch) -> None: class FakeEncoding: def __init__(self) -> None: