-
Notifications
You must be signed in to change notification settings - Fork 228
feat: preserve provider timing in normalized usage #1261
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
njbrake
merged 5 commits into
mozilla-ai:main
from
mikemikimike:fix/1258-provider-timing
Aug 12, 2026
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
9b72071
feat: preserve provider timing in normalized usage
mikemikimike 714d3da
refactor(groq,ollama): use typed attribute access for timing helpers
njbrake d9b6128
tests(groq): cover streaming usage without timing; rename timing helpers
njbrake 4df7f55
fix(groq): handle usage-only streaming chunks
mikemikimike dcb0aa2
tests(groq,ollama): cover the real Groq streaming shape; add timing i…
njbrake File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| """Integration tests for issue #1258: provider-reported timing must survive normalization. | ||
|
|
||
| Groq reports timing in seconds on its usage object, Ollama in nanoseconds on its chat | ||
| response. Both land in ``usage.model_extra``. The unit tests hand-build the provider SDK | ||
| objects, so only these tests prove the fields are actually on the wire, which matters most | ||
| for Groq streaming: groq 1.6.0 takes no ``stream_options``, so streaming usage arrives under | ||
| ``x_groq.usage`` rather than top-level ``chunk.usage``. | ||
|
|
||
| Requires GROQ_API_KEY for the Groq tests and a reachable Ollama host for the Ollama ones. | ||
| """ | ||
|
|
||
| from collections.abc import AsyncIterator | ||
| from typing import Any | ||
|
|
||
| import httpx | ||
| import pytest | ||
|
|
||
| from any_llm import AnyLLM, LLMProvider | ||
| from any_llm.exceptions import MissingApiKeyError | ||
| from any_llm.types.completion import ChatCompletion, ChatCompletionChunk, ChatCompletionMessage | ||
|
|
||
| _GROQ_TIMING_FIELDS = ("queue_time", "prompt_time", "completion_time", "total_time") | ||
| _OLLAMA_TIMING_FIELDS = ("total_duration", "load_duration", "prompt_eval_duration", "eval_duration") | ||
|
|
||
| _PROMPT: list[dict[str, Any] | ChatCompletionMessage] = [{"role": "user", "content": "Reply with the single word OK."}] | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_groq_timing_non_streaming(provider_model_map: dict[LLMProvider, str]) -> None: | ||
| """Groq's per-request timing survives on a non-streaming completion.""" | ||
| try: | ||
| llm = AnyLLM.create(LLMProvider.GROQ) | ||
| except MissingApiKeyError: | ||
| pytest.skip("Groq API key not provided, skipping") | ||
|
|
||
| result = await llm.acompletion(model=provider_model_map[LLMProvider.GROQ], messages=_PROMPT) | ||
|
|
||
| assert isinstance(result, ChatCompletion) | ||
| assert result.usage is not None | ||
| extras = result.usage.model_extra or {} | ||
| assert set(_GROQ_TIMING_FIELDS) <= extras.keys(), f"missing Groq timing fields in {extras}" | ||
| assert extras["total_time"] > 0 | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_groq_timing_streaming(provider_model_map: dict[LLMProvider, str]) -> None: | ||
| """Groq's streaming usage and timing arrive on the final chunk via x_groq.""" | ||
| try: | ||
| llm = AnyLLM.create(LLMProvider.GROQ) | ||
| except MissingApiKeyError: | ||
| pytest.skip("Groq API key not provided, skipping") | ||
|
|
||
| stream = await llm.acompletion(model=provider_model_map[LLMProvider.GROQ], messages=_PROMPT, stream=True) | ||
| assert isinstance(stream, AsyncIterator) | ||
|
|
||
| usages = [] | ||
| async for chunk in stream: | ||
| assert isinstance(chunk, ChatCompletionChunk) | ||
| if chunk.usage is not None: | ||
| usages.append(chunk.usage) | ||
|
|
||
| assert usages, "no chunk reported usage: streaming usage is not reaching the converter" | ||
| extras = usages[-1].model_extra or {} | ||
| assert set(_GROQ_TIMING_FIELDS) <= extras.keys(), f"missing Groq timing fields in {extras}" | ||
| assert usages[-1].completion_tokens > 0 | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_ollama_timing_non_streaming(provider_model_map: dict[LLMProvider, str]) -> None: | ||
| """Ollama's duration fields survive on a non-streaming completion.""" | ||
| llm = AnyLLM.create(LLMProvider.OLLAMA) | ||
|
|
||
| try: | ||
| result = await llm.acompletion(model=provider_model_map[LLMProvider.OLLAMA], messages=_PROMPT) | ||
| # An unreachable host surfaces as a builtin ConnectionError from the ollama SDK on the | ||
| # non-streaming call and as a raw httpx.ConnectError on the streaming one. | ||
| except (ConnectionError, httpx.ConnectError, httpx.HTTPStatusError): | ||
| pytest.skip("Local Ollama host is not set up, skipping") | ||
|
|
||
| assert isinstance(result, ChatCompletion) | ||
| assert result.usage is not None | ||
| extras = result.usage.model_extra or {} | ||
| assert set(_OLLAMA_TIMING_FIELDS) <= extras.keys(), f"missing Ollama timing fields in {extras}" | ||
| assert extras["total_duration"] > 0 | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_ollama_timing_streaming(provider_model_map: dict[LLMProvider, str]) -> None: | ||
| """Ollama reports its duration fields on the final streaming chunk.""" | ||
| llm = AnyLLM.create(LLMProvider.OLLAMA) | ||
|
|
||
| try: | ||
| stream = await llm.acompletion(model=provider_model_map[LLMProvider.OLLAMA], messages=_PROMPT, stream=True) | ||
| assert isinstance(stream, AsyncIterator) | ||
|
|
||
| usages = [] | ||
| async for chunk in stream: | ||
| assert isinstance(chunk, ChatCompletionChunk) | ||
| if chunk.usage is not None: | ||
| usages.append(chunk.usage) | ||
| except (ConnectionError, httpx.ConnectError, httpx.HTTPStatusError): | ||
| pytest.skip("Local Ollama host is not set up, skipping") | ||
|
|
||
| assert usages, "no chunk reported usage" | ||
| extras = usages[-1].model_extra or {} | ||
| assert set(_OLLAMA_TIMING_FIELDS) <= extras.keys(), f"missing Ollama timing fields in {extras}" | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Do not skip all HTTP response failures.
httpx.HTTPStatusErrorincludes invalid model names, authentication failures, and provider failures. These conditions must fail the test. Skip only confirmed unavailable-service conditions, such as connection errors or connection timeouts. Include the concrete connection failure in the skip message.tests/integration/test_provider_timing.py#L73-L78: Removehttpx.HTTPStatusErrorfrom the skip handler.tests/integration/test_provider_timing.py#L92-L102: Removehttpx.HTTPStatusErrorfrom the skip handler.As per coding guidelines, “Every test skip and fix must have a concrete root cause”.
📍 Affects 1 file
tests/integration/test_provider_timing.py#L73-L78(this comment)tests/integration/test_provider_timing.py#L92-L102🤖 Prompt for AI Agents
Source: Coding guidelines