Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(model-hub): bound provider-reported hosted integers where they are read (#2818)

Call White1ae734c71b18
diff --git a/core/agent_core/ai/anthropic.py b/core/agent_core/ai/anthropic.py
index fba7f9860..07054d7a2 100644
--- a/core/agent_core/ai/anthropic.py
+++ b/core/agent_core/ai/anthropic.py
@@ -55,6 +55,7 @@ from core.agent_core.ai.provider import (
)
from core.agent_core.cancel import CancelToken
from core.agent_core.messages import (
+ MAX_HOSTED_COUNT,
AssistantMessage,
HostedToolBlock,
ImageBlock,
@@ -272,6 +273,7 @@ class AnthropicAdapter(ProviderAdapter):
paused = False
offset = next_index = 0
response_usage: Usage | None = None
+ # Exact totals, unbounded: a counter past the bound in any response stays past it however later ones add.
carried_counts: dict[str, int] = {}
response_counts: dict[str, int] = {}
@@ -390,8 +392,8 @@ class AnthropicAdapter(ProviderAdapter):
assembler.set_usage(response_usage)
start_usage = message.get("usage")
if isinstance(start_usage, Mapping) and "server_tool_use" in start_usage:
- response_counts = reported_counts(start_usage.get("server_tool_use"))
- assembler.set_hosted_facts(counts=_summed(carried_counts, response_counts))
+ response_counts = reported_counts(start_usage.get("server_tool_use"), bound=None)
+ assembler.set_hosted_facts(counts=_bounded(_summed(carried_counts, response_counts)))
elif event_type == "content_block_start":
index = block_index(chunk)
if index is None:
@@ -766,8 +768,8 @@ class AnthropicAdapter(ProviderAdapter):
response_usage = _anthropic_usage(usage, current=response_usage)
assembler.set_usage(response_usage)
if isinstance(usage, Mapping) and "server_tool_use" in usage:
- response_counts = reported_counts(usage.get("server_tool_use"))
- assembler.set_hosted_facts(counts=_summed(carried_counts, response_counts))
+ response_counts = reported_counts(usage.get("server_tool_use"), bound=None)
+ assembler.set_hosted_facts(counts=_bounded(_summed(carried_counts, response_counts)))
elif event_type == "error":
shape_error = _error_event_shape_error(chunk)
if shape_error is not None:
@@ -1266,6 +1268,12 @@ def _summed(counts: Mapping[str, int], more: Mapping[str, int]) -> dict[str, int
return summed
+def _bounded(counts: Mapping[str, int]) -> dict[str, int]:
+ """The counters a summary keeps of a response's exact totals: one past the bound is no count."""
+
+ return {name: value for name, value in counts.items() if value <= MAX_HOSTED_COUNT}
+
+
def _normalize_stop_reason(value: Any) -> str:
normalized = {
"end_turn": "stop",
diff --git a/core/agent_core/ai/hosted.py b/core/agent_core/ai/hosted.py
index f8d8cb271..793e7652c 100644
--- a/core/agent_core/ai/hosted.py
+++ b/core/agent_core/ai/hosted.py
@@ -19,6 +19,7 @@ from urllib.parse import urlsplit
from core.agent_core.ai.errors import redact_provider_text
from core.agent_core.messages import (
HOSTED_ERROR_MAX_CHARS,
+ MAX_HOSTED_COUNT,
AssistantMessage,
Citation,
HostedAction,
@@ -33,8 +34,10 @@ from core.agent_core.messages import (
from core.agent_core.tools.read import MAX_INLINE_IMAGE_BYTES
from core.agent_core.tools.truncate import format_size
-#: xAI reports a response's cost in ticks of 1e-10 USD (``usage.cost_in_usd_ticks``).
-_USD_PER_TICK = 1e-10
+#: xAI reports a response's cost in ticks of 1e-10 USD (``usage.cost_in_usd_ticks``). Past the bound (about $100M
+#: for one response) a reported figure is not a cost.
+_TICKS_PER_USD = 10_000_000_000
+_MAX_TICKS = 10**18
_X_HOSTS = frozenset({"x.com", "twitter.com"})
#: The counter names a summary holds (``message.schema.json``); a provider's other keys are not counters.
_COUNTER_NAME = re.compile(r"[a-z0-9_]{1,64}")
@@ -269,9 +272,11 @@ def x_cited_sources(citations: Iterable[Citation]) -> tuple[HostedSource, ...]:
return tuple(seen.values())
-def reported_counts(*sections: Any) -> dict[str, int]:
+def reported_counts(*sections: Any, bound: Optional[int] = MAX_HOSTED_COUNT) -> dict[str, int]:
"""Provider-reported hosted counters (xAI ``server_side_tool_usage_details``, Anthropic ``server_tool_use``),
- keeping the ones that counted something."""
+ keeping the ones that counted something. A count past ``bound`` is refused here, where counters enter, so it reads
+ as absent to everything that prices or keeps them. A caller that adds responses together reads them unbounded and
+ bounds the total, so a counter past the bound in one response stays past it."""
counts: dict[str, int] = {}
for section in sections:
@@ -282,17 +287,23 @@ def reported_counts(*sections: Any) -> dict[str, int]:
if len(counts) >= MAX_HOSTED_COUNTERS or scanned >= _COUNTERS_SCANNED:
break
counted = isinstance(value, int) and not isinstance(value, bool) and value > 0
+ if counted and bound is not None:
+ counted = value <= bound
if counted and isinstance(name, str) and _COUNTER_NAME.fullmatch(name):
counts[name] = value
return counts
def reported_cost(usage: Any) -> Optional[HostedCost]:
- """The response's cost when the provider reports one (xAI ``cost_in_usd_ticks``); never a priced guess."""
+ """The response's cost when the provider reports one (xAI ``cost_in_usd_ticks``); never a priced guess.
+
+ Vibey's native call and the gateway's proxied one both read it here. A figure that is not a whole number of ticks
+ within the bound is no figure.
+ """
ticks = usage.get("cost_in_usd_ticks") if isinstance(usage, Mapping) else None
- if isinstance(ticks, int) and not isinstance(ticks, bool) and ticks >= 0:
- return HostedCost(basis="reported", usd=ticks * _USD_PER_TICK)
+ if isinstance(ticks, int) and not isinstance(ticks, bool) and 0 <= ticks <= _MAX_TICKS:
+ return HostedCost(basis="reported", usd=ticks / _TICKS_PER_USD)
return None
diff --git a/core/agent_core/messages.py b/core/agent_core/messages.py
index c57c4483f..051065e17 100644
--- a/core/agent_core/messages.py
+++ b/core/agent_core/messages.py
@@ -35,6 +35,9 @@ EXECUTION_MODES: tuple[str, ...] = ("proxy", "direct")
HostedStatus = Literal["completed", "failed", "incomplete", "pending"]
HOSTED_STATUSES: tuple[str, ...] = ("completed", "failed", "incomplete", "pending")
HOSTED_ERROR_MAX_CHARS = 400
+#: The largest hosted count a summary holds: the largest integer every JSON reader holds exactly. A provider's count
+#: past it is no count, and no price or display has to survive one.
+MAX_HOSTED_COUNT = 2**53 - 1
#: The stable code of each hosted failure Avibe words itself (``HostedRecord.error_code``), by which a display localizes
#: it; a provider's own reason has none. A record loads with any snake_case code, so one a newer build wrote still reads.
#: ``image_not_streamed`` has no producer since native images went (v2); it stays for the records already written.
@@ -477,8 +480,8 @@ class HostedSummary:
if not isinstance(name, str) or not _COUNTER_NAME_RE.fullmatch(name):
raise ValueError(f"invalid hosted counter name: {name!r}")
_require(value, int, f"hosted count {name}")
- if value < 0:
- raise ValueError("hosted counts must not be negative")
+ if not 0 <= value <= MAX_HOSTED_COUNT:
+ raise ValueError(f"hosted counts are between 0 and {MAX_HOSTED_COUNT}")
object.__setattr__(self, "counts", dict(self.counts))
if not isinstance(self.cited_sources, tuple) or not all(
isinstance(s, HostedSource) for s in self.cited_sources
@@ -1027,7 +1030,13 @@ def message_from_dict(data: Mapping[str, Any]) -> Message:
if "hosted_summary" in f:
h = _read(f["hosted_summary"], "hosted summary", {"counts": dict, "cited_sources": list}, {"cost": dict})
summary = HostedSummary(
- counts=dict(h["counts"]),
+ # A release before the bound may have stored a count past it: that counter is dropped, not refused,
+ # so its transcript still loads.
+ counts={
+ name: value
+ for name, value in h["counts"].items()
+ if not (isinstance(value, int) and value > MAX_HOSTED_COUNT)
+ },
cited_sources=tuple(_source_from_dict(source) for source in h["cited_sources"]),
cost=_cost_from_dict(h["cost"]) if "cost" in h else None,
)
diff --git a/core/handlers/model_hub/hosted_executor.py b/core/handlers/model_hub/hosted_executor.py
index 1adf5f9b2..84071de07 100644
--- a/core/handlers/model_hub/hosted_executor.py
+++ b/core/handlers/model_hub/hosted_executor.py
@@ -19,12 +19,11 @@ from dataclasses import dataclass, field, replace
from typing import Any, Callable, Final, Mapping
from config.v2_config import ModelHubSourceConfig
-from core.agent_core.ai.hosted import reported_counts
+from core.agent_core.ai.hosted import reported_cost, reported_counts
from core.agent_core.ai.sse import SSEParser
from .events import bounded_diagnostic_detail
from .hosted_items import responses_item_tool
-from .pricing import usd_from_xai_ticks
from .request import ModelHubRequest
EXECUTOR_TOOLS: Final = ("web_search", "x_search")
@@ -301,7 +300,8 @@ def provider_charges(protocol: str, usage: Mapping[str, Any] | None) -> tuple[di
if usage is None:
return {}, None
counters = usage.get("server_tool_use") if protocol == "anthropic" else usage.get("server_side_tool_usage_details")
- return reported_counts(counters), usd_from_xai_ticks(usage.get("cost_in_usd_ticks"))
+ cost = reported_cost(usage)
+ return reported_counts(counters), cost.usd if cost is not None else None
def _usage_section(response: Any) -> Mapping[str, Any] | None:
diff --git a/core/handlers/model_hub/pricing.py b/core/handlers/model_hub/pricing.py
index a1e183825..f8bb70126 100644
--- a/core/handlers/model_hub/pricing.py
+++ b/core/handlers/model_hub/pricing.py
@@ -639,11 +639,8 @@ def quota_values(
#
# One owner turns a hosted response's usage into money: this module. Callers
# (Vibey's hosted_summary, the gateway's ProxyExecution) only pass what the
-# response reported.
-
-XAI_USD_TICKS_PER_USD: Final = 10_000_000_000
-# Above this (about $100M for one response) a reported figure is not a cost.
-_MAX_XAI_TICKS: Final = 10**18
+# response reported, read and bounded where it enters
+# (``core.agent_core.ai.hosted``, ``stream_wire``), so no guard is needed here.
# The provider counter that counts one unit of a hosted tool's list price.
_HOSTED_UNIT_COUNTERS: Final[Mapping[tuple[str, str], str]] = {
@@ -655,14 +652,6 @@ _HOSTED_UNIT_COUNTERS: Final[Mapping[tuple[str, str], str]] = {
}
-def usd_from_xai_ticks(ticks: object) -> Optional[float]:
- """xAI's ``cost_in_usd_ticks`` in USD; None when it is not a non-negative integer."""
-
- if isinstance(ticks, bool) or not isinstance(ticks, int) or not 0 <= ticks <= _MAX_XAI_TICKS:
- return None
- return ticks / XAI_USD_TICKS_PER_USD
-
-
def hosted_response_cost(
*,
billing: str,
diff --git a/core/handlers/model_hub/stream_wire.py b/core/handlers/model_hub/stream_wire.py
index 7ab89be2c..e9faca980 100644
--- a/core/handlers/model_hub/stream_wire.py
+++ b/core/handlers/model_hub/stream_wire.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import json
from dataclasses import dataclass, field
-from typing import AbstractSet, BinaryIO, Callable, Final, Literal, Mapping
+from typing import AbstractSet, BinaryIO, Callable, Final, Iterable, Literal, Mapping
from .async_owner import run_owned_in_thread
from .hosted_items import responses_item_succeeded
@@ -909,22 +909,29 @@ def is_protocol_model_output(
)
-def _usage_sum(container: Mapping[str, object], paths: tuple[tuple[str, ...], ...]) -> int | None:
- """Sum one logical field's leaves, rejecting anything not a bounded count."""
+def _usage_total(values: Iterable[object]) -> int | None:
+ """Sum one logical field's leaves, rejecting anything not a bounded count.
+
+ Every token count read from the wire, streamed or buffered, passes here: the
+ one place the per-report ceiling applies.
+ """
total: int | None = None
- for path in paths:
- for value in _path_values(container, path):
- if not isinstance(value, int) or isinstance(value, bool):
- continue
- if value < 0 or value > USAGE_REPORT_TOKEN_CEILING:
- continue
- total = value if total is None else total + value
+ for value in values:
+ if not isinstance(value, int) or isinstance(value, bool):
+ continue
+ if value < 0 or value > USAGE_REPORT_TOKEN_CEILING:
+ continue
+ total = value if total is None else total + value
if total is None:
return None
return min(total, USAGE_REPORT_TOKEN_CEILING)
+def _usage_sum(container: Mapping[str, object], paths: tuple[tuple[str, ...], ...]) -> int | None:
+ return _usage_total(value for path in paths for value in _path_values(container, path))
+
+
def extract_protocol_usage(
protocol: str,
payload: Mapping[str, object],
@@ -963,15 +970,7 @@ def _usage_from_scalar_paths(
for container_path in taxonomy.container_paths:
def usage_sum(paths: tuple[tuple[str, ...], ...]) -> int | None:
- total: int | None = None
- for path in paths:
- value = scalars.get((*container_path, *path))
- if not isinstance(value, int) or isinstance(value, bool):
- continue
- if value < 0 or value > USAGE_REPORT_TOKEN_CEILING:
- continue
- total = value if total is None else total + value
- return None if total is None else min(total, USAGE_REPORT_TOKEN_CEILING)
+ return _usage_total(scalars.get((*container_path, *path)) for path in paths)
input_tokens = usage_sum(taxonomy.input_paths)
cached_input_tokens = usage_sum(taxonomy.cached_input_paths)
diff --git a/docs/plans/agent-core-contracts/message.schema.json b/docs/plans/agent-core-contracts/message.schema.json
index cf9a1ac23..aff14e4ca 100644
--- a/docs/plans/agent-core-contracts/message.schema.json
+++ b/docs/plans/agent-core-contracts/message.schema.json
@@ -1207,9 +1207,10 @@
},
"additionalProperties": {
"type": "integer",
- "minimum": 0
+ "minimum": 0,
+ "maximum": 9007199254740991
},
- "description": "Provider-reported counters by name, e.g. `web_search_calls`, `x_posts_fetched`, `web_search_requests`."
+ "description": "Provider-reported counters by name, e.g. `web_search_calls`, `x_posts_fetched`, `web_search_requests`. A count is at most 2^53 - 1, the largest integer every JSON reader holds exactly; a provider's count past it is not kept."
},
"cited_sources": {
"type": "array",
diff --git a/docs/plans/vibey-hosted-tools.md b/docs/plans/vibey-hosted-tools.md
index 4948ee9f1..2a920ee32 100644
--- a/docs/plans/vibey-hosted-tools.md
+++ b/docs/plans/vibey-hosted-tools.md
@@ -386,7 +386,10 @@ never dropped.
result (§7.3).
- **`AssistantMessage.hosted_summary`** (per response, present exactly when the message has hosted blocks):
`cost` (`{basis, usd}` with `basis` `reported` or `list`, or `included` with no `usd`; absent when unknown),
- `counts` (provider counters by name), `cited_sources[]` (the xAI X-search `url_citation`s).
+ `counts` (provider counters by name, each at most 2^53 - 1), `cited_sources[]` (the xAI X-search `url_citation`s).
+ A provider's counter or `cost_in_usd_ticks` past its bound is refused where it is read
+ (`core/agent_core/ai/hosted.py`), for the native and the proxied call alike, so it reads as absent and never
+ fails a response (#2572).
- **`TextBlock.citations`** (optional): `[{url, title?, cited_text?, start?, end?}]`, presentation only, never
replayed, materialized at delivery by `core/citations.py`.
- **`ToolResultMessage.hosted`** (optional): `{record, execution?, action?}` for a proxied search call and for every
diff --git a/tests/agent_core/ai/test_hosted_parsing.py b/tests/agent_core/ai/test_hosted_parsing.py
index edf578ee0..e2e779f74 100644
--- a/tests/agent_core/ai/test_hosted_parsing.py
+++ b/tests/agent_core/ai/test_hosted_parsing.py
@@ -16,7 +16,7 @@ import pytest
import core.agent_core.ai._common as common_module
from core.agent_core.ai._common import OutputBudgetExceeded, StreamAssembler
-from core.agent_core.ai.hosted import anthropic_hosted_block, reported_counts, responses_hosted_block
+from core.agent_core.ai.hosted import anthropic_hosted_block, reported_cost, reported_counts, responses_hosted_block
from core.agent_core.ai.provider import Done, HostedToolRoute, ModelEndpoint, ModelRequest
from core.agent_core.ai.registry import create_adapter
from core.agent_core.cancel import CancelToken
@@ -237,6 +237,32 @@ async def test_xai_x_searches_keep_their_variants_and_the_answer_cites_each_post
assert summary.cost.usd == pytest.approx(0.11272688)
+async def test_an_xai_response_reporting_a_number_past_its_bound_completes_without_that_number():
+ """MH-HOSTED-VIBEY-002 (#2572): a malformed relay's cost or counter past its bound is no figure, never an error
+ that fails the turn."""
+ usage = {
+ "input_tokens": 22965,
+ "output_tokens": 1402,
+ "cost_in_usd_ticks": 10**400,
+ "server_side_tool_usage_details": {"web_search_calls": 1, "x_posts_fetched": 10**400},
+ }
+
+ message = await _message("openai_responses", _responses([WEB_SEARCH_CALL, ANSWER_ITEM], usage))
+
+ assert message.stop_reason == "stop"
+ assert message.hosted_summary.counts == {"web_search_calls": 1}
+ assert message.hosted_summary.cost is None
+
+
+def test_xai_cost_ticks_are_a_cost_only_as_a_whole_number_within_the_bound():
+ """MH-PRICE-020: xAI reports cost in 1e-10 USD ticks; Vibey's native call and a proxied one read it here."""
+
+ assert reported_cost({"cost_in_usd_ticks": 1127268800}).usd == pytest.approx(0.11272688)
+ assert reported_cost({"cost_in_usd_ticks": 10**18}).usd == pytest.approx(10**8)
+ for ticks in (-1, True, "9", 1.5, 10**18 + 1, 10**400):
+ assert reported_cost({"cost_in_usd_ticks": ticks}) is None
+
+
@pytest.mark.parametrize(
("item", "action", "status"),
[
diff --git a/tests/agent_core/ai/test_hosted_pause_turn.py b/tests/agent_core/ai/test_hosted_pause_turn.py
index 25f46a313..3ab3eaad4 100644
--- a/tests/agent_core/ai/test_hosted_pause_turn.py
+++ b/tests/agent_core/ai/test_hosted_pause_turn.py
@@ -20,7 +20,15 @@ from core.agent_core.ai.anthropic import MAX_PAUSE_CONTINUATIONS, PAUSE_LIMIT_ME
from core.agent_core.ai.provider import Done, HostedToolRoute, ModelEndpoint, ModelRequest, ProviderError
from core.agent_core.ai.registry import create_adapter
from core.agent_core.cancel import CancelToken
-from core.agent_core.messages import HostedToolBlock, ImageBlock, TextBlock, ThinkingBlock, Usage, UserMessage
+from core.agent_core.messages import (
+ MAX_HOSTED_COUNT,
+ HostedToolBlock,
+ ImageBlock,
+ TextBlock,
+ ThinkingBlock,
+ Usage,
+ UserMessage,
+)
from core.agent_core.tools.hosted import hosted_tool_spec
SOURCE = "src_served00001"
@@ -162,6 +170,36 @@ async def test_a_paused_response_continues_as_one_response_pinned_to_its_source_
assert not [event for event in events if isinstance(event, ProviderError)]
+ "searches",
+ [
+ (MAX_HOSTED_COUNT, MAX_HOSTED_COUNT, 1),
+ (10**400, 1),
+ ],
+ ids=["total-past-the-bound", "one-response-past-the-bound"],
+)
+async def test_a_counter_past_the_bound_in_any_pause_stays_absent_and_the_response_completes(searches):
+ """MH-HOSTED-VIBEY-006 (#2572): each response's counts are bounded, but not their total across pauses. A counter
+ whose total passes the bound, in one response or summed over several, is no count, and a later pause cannot bring
+ back a smaller one; it never fails the turn."""
+
+ def answer(number: int) -> httpx.Response:
+ if number < len(searches):
+ body = _response(
+ _use(), stop_reason="pause_turn", input_tokens=100, output_tokens=10, searches=searches[number - 1]
+ )
+ else:
+ body = _response([{"type": "content_block_start", "content_block": RESULT}], _text("v8 is out"),
+ stop_reason="end_turn", input_tokens=300, output_tokens=20, searches=searches[-1])
+ return httpx.Response(200, headers=_served(), text=body)
+
+ sent, events = await _stream(answer)
+
+ assert len(sent) == len(searches)
+ assert isinstance(events[-1], Done) and events[-1].message.stop_reason == "stop"
+ assert dict(events[-1].message.hosted_summary.counts) == {}
+
+
async def test_a_continuation_that_reports_no_usage_leaves_the_message_without_the_paused_requests():
"""The merged message's usage stands for the final request; a final response that reports none leaves it unknown,
never the smaller paused request's."""
diff --git a/tests/agent_core/test_hosted_messages.py b/tests/agent_core/test_hosted_messages.py
index 4d56aa3ff..98cbc2b20 100644
--- a/tests/agent_core/test_hosted_messages.py
+++ b/tests/agent_core/test_hosted_messages.py
@@ -17,6 +17,7 @@ from referencing import Registry, Resource
from core.agent_core.messages import (
HOSTED_ERROR_CODES,
+ MAX_HOSTED_COUNT,
AssistantMessage,
Citation,
FailedAttempt,
@@ -323,6 +324,22 @@ def test_schema_and_reader_refuse_the_same_hosted_violations(payload):
message_from_dict(payload)
+def test_a_count_past_the_bound_is_never_written_and_a_stored_one_is_dropped_on_read():
+ """#2572: a count is at most 2^53 - 1, the largest integer every JSON reader holds exactly. A release before the
+ bound may have stored a larger one: that counter alone is dropped, so its transcript still loads."""
+
+ with pytest.raises(ValueError):
+ HostedSummary(counts={"x_posts_fetched": MAX_HOSTED_COUNT + 1})
+ stored = _set(NATIVE, ("hosted_summary", "counts", "x_posts_fetched"), MAX_HOSTED_COUNT + 1)
+ assert not VALIDATOR.is_valid(stored)
+ loaded = message_from_dict(stored)
+ assert loaded.hosted_summary.counts == {"web_search_calls": 2, "x_search_calls": 1}
+ VALIDATOR.validate(message_to_dict(loaded))
+ at_bound = _set(NATIVE, ("hosted_summary", "counts", "x_posts_fetched"), MAX_HOSTED_COUNT)
+ VALIDATOR.validate(at_bound)
+ assert message_from_dict(at_bound).hosted_summary.counts["x_posts_fetched"] == MAX_HOSTED_COUNT
+
+
def test_a_record_with_an_error_code_this_build_does_not_know_still_loads():
"""#2589: a newer build may add codes; an older one reads the record and shows its English error."""
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 6ee9279f1..4c819d614 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -362,6 +362,7 @@ scenarios:
test: tests/agent_core/ai/test_hosted_parsing.py::test_an_xai_web_search_is_one_hosted_call_with_its_sources_cited_text_and_reported_cost
related_tests:
- tests/agent_core/ai/test_hosted_parsing.py::test_xai_x_searches_keep_their_variants_and_the_answer_cites_each_post_once
+ - tests/agent_core/ai/test_hosted_parsing.py::test_an_xai_response_reporting_a_number_past_its_bound_completes_without_that_number
- tests/agent_core/ai/test_hosted_parsing.py::test_the_mapping_rule_gives_every_responses_item_a_provider_neutral_action
- tests/agent_core/ai/test_hosted_parsing.py::test_no_hosted_call_without_a_native_declaration_or_a_known_serving_source
- tests/agent_core/ai/test_hosted_parsing.py::test_an_anthropic_search_and_its_result_are_one_hosted_call_and_the_text_keeps_its_citation
@@ -421,6 +422,7 @@ scenarios:
- tests/agent_core/ai/test_hosted_pause_turn.py::test_a_response_paused_past_the_bound_ends_interrupted_and_keeps_everything_it_assembled
- tests/agent_core/ai/test_hosted_pause_turn.py::test_a_paused_response_its_source_cannot_continue_ends_interrupted_and_keeps_what_it_has
- tests/agent_core/ai/test_hosted_pause_turn.py::test_a_continued_response_is_verified_only_when_every_response_in_it_was_from_one_origin
+ - tests/agent_core/ai/test_hosted_pause_turn.py::test_a_counter_past_the_bound_in_any_pause_stays_absent_and_the_response_completes
- id: MH-HOSTED-VIBEY-007
name: An image_generate call goes to the gateway's image endpoint with its arguments alone, after the turn's frozen models accept every argument and its reference images are read as read reads them; the images it returns are saved through the media sink and its record names those files; no base64 enters history, and a call that saved no file is a failed record with its code
status: covered
@@ -1862,7 +1864,7 @@ scenarios:
layer: unit
test: tests/test_model_hub_pricing.py::test_a_hosted_response_is_priced_by_the_one_pricing_owner
related_tests:
- - tests/test_model_hub_pricing.py::test_xai_cost_ticks_are_converted_by_the_pricing_module
+ - tests/agent_core/ai/test_hosted_parsing.py::test_xai_cost_ticks_are_a_cost_only_as_a_whole_number_within_the_bound
- id: MH-PRICE-019
name: A tiered row the current table no longer lists is valued at the largest listed tier it exceeded
status: covered
diff --git a/tests/test_model_hub_hosted_executor.py b/tests/test_model_hub_hosted_executor.py
index 3c343401d..66f10ab8d 100644
--- a/tests/test_model_hub_hosted_executor.py
+++ b/tests/test_model_hub_hosted_executor.py
@@ -311,6 +311,20 @@ ANTHROPIC_SEARCH = {
_responses(WEB_CALL, WEB_ANSWER, usage={"input_tokens": 2000, "output_tokens": 100}),
None,
),
+ # A provider's number past its bound is refused where it enters (#2572): the call still completes, and a cost
+ # that needs the number is unknown, never an error. A search counter past the bound counts no searches to value.
+ (
+ "web_search", (ANTHROPIC, "claude-haiku-4-5"), "metered",
+ {**ANTHROPIC_SEARCH, "usage": {"input_tokens": 2000, "output_tokens": 100,
+ "server_tool_use": {"web_search_requests": 10**400}}},
+ None,
+ ),
+ # xAI's own figure past the bound is no figure, and nothing else prices this call.
+ (
+ "x_search", (XAI, "grok-4.6"), "metered",
+ _responses(X_CALL, X_ANSWER, usage={"input_tokens": 2000, "output_tokens": 100, "cost_in_usd_ticks": 10**400}),
+ None,
+ ),
])
async def test_a_proxied_call_carries_the_pricing_modules_cost(tmp_path, tool, executor, billing, response, cost):
"""MH-HOSTED-GATEWAY-004: the cost is included, the provider's own figure, or the list price; absent when unknown."""
diff --git a/tests/test_model_hub_pricing.py b/tests/test_model_hub_pricing.py
index 986911f69..3ff1cfe24 100644
--- a/tests/test_model_hub_pricing.py
+++ b/tests/test_model_hub_pricing.py
@@ -917,16 +917,6 @@ def test_a_hosted_response_is_priced_by_the_one_pricing_owner(billing, reported,
assert result[0] == expected[0] and result[1] == pytest.approx(expected[1])
-def test_xai_cost_ticks_are_converted_by_the_pricing_module():
- """MH-PRICE-020: xAI reports cost in 1e-10 USD ticks."""
- from core.handlers.model_hub.pricing import usd_from_xai_ticks
-
- assert usd_from_xai_ticks(1127268800) == pytest.approx(0.11272688)
- assert usd_from_xai_ticks(-1) is None and usd_from_xai_ticks(True) is None and usd_from_xai_ticks("9") is None
- # An absurd figure from a malformed relay is unknown, never an OverflowError that fails the turn.
- assert usd_from_xai_ticks(10**400) is None
-
-
def test_a_price_table_parses_every_price_when_built_and_none_on_lookup(monkeypatch):
"""MH-PRICE-016: building the table (never on the loop) parses every price, so a lookup on the loop parses none."""
from core.handlers.model_hub import pricing