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.

feat(model-hub): price hosted tools and long contexts, and project executor binding and evidence expiry for the Tools tab (#2566)

Call White5e32d4cfa3f0
diff --git a/core/handlers/model_hub/capability_evidence.py b/core/handlers/model_hub/capability_evidence.py
index 3ec280554..90dd159dd 100644
--- a/core/handlers/model_hub/capability_evidence.py
+++ b/core/handlers/model_hub/capability_evidence.py
@@ -23,7 +23,7 @@ import json
import re
import threading
from dataclasses import dataclass
-from datetime import datetime, timezone
+from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Iterable, Literal, Mapping, Optional
@@ -121,6 +121,12 @@ class EvidenceRecord:
raise ValueError("evidence shape is a non-negative integer")
if self.observed_at.tzinfo is None:
raise ValueError("evidence time must be timezone-aware")
+ try:
+ # Its expiry and re-verify instants must be representable, or every
+ # read that resolves it would fail; such a record reads as unknown.
+ self.observed_at + timedelta(seconds=max(OBSERVED_TTL_SECONDS, PROBE_REVERIFY_AFTER_SECONDS))
+ except OverflowError:
+ raise ValueError("evidence time is out of range") from None
@property
def key(self) -> tuple[str, str, str, str, str]:
@@ -185,6 +191,8 @@ class EvidenceView:
status: RoutingStatus
stale: Optional[Staleness] = None
record: Optional[EvidenceRecord] = None
+ changes_at: Optional[datetime] = None
+ """When this record stops reading as it does now (observed expiry, probe re-verify mark); None when nothing is scheduled."""
UNKNOWN = EvidenceView("unknown")
@@ -212,18 +220,23 @@ def resolve(
age = (now - record.observed_at).total_seconds()
if record.basis == "observed":
# Relays change; an expired negative record falls back to the priors.
- return UNKNOWN if age > OBSERVED_TTL_SECONDS else EvidenceView("unsupported", None, record)
+ if age > OBSERVED_TTL_SECONDS:
+ return UNKNOWN
+ return EvidenceView("unsupported", None, record, record.observed_at + timedelta(seconds=OBSERVED_TTL_SECONDS))
wire_stale = (
record.engine != engine
or record.shape != shape
or UNKNOWN_ENGINE_STAMP in (record.engine, engine)
)
stale: Optional[Staleness] = "wire" if wire_stale else "age" if age > PROBE_REVERIFY_AFTER_SECONDS else None
+ changes_at = (
+ record.observed_at + timedelta(seconds=PROBE_REVERIFY_AFTER_SECONDS) if stale is None else None
+ )
if record.feature.kind == "hosted_tool" and wire_stale:
# Evidence taken on another wire cannot vouch for this one, and a silent
# native drop would never trip a narrow rule: route as unknown (proxy).
return EvidenceView("unknown", stale, record)
- return EvidenceView(record.status, stale, record)
+ return EvidenceView(record.status, stale, record, changes_at)
class CapabilityEvidenceStore:
diff --git a/core/handlers/model_hub/hosted_tools.py b/core/handlers/model_hub/hosted_tools.py
index 75db08670..546900bed 100644
--- a/core/handlers/model_hub/hosted_tools.py
+++ b/core/handlers/model_hub/hosted_tools.py
@@ -17,7 +17,7 @@ from __future__ import annotations
import json
import os
from dataclasses import dataclass
-from datetime import datetime
+from datetime import datetime, timezone
from functools import lru_cache
from importlib import resources
from pathlib import Path
@@ -160,6 +160,10 @@ def resolve_hosted_tools(
return resolved
+def _utc_text(moment: Optional[datetime]) -> Optional[str]:
+ return moment.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") if moment is not None else None
+
+
def _evidence_payload(view) -> dict[str, Any]:
record = view.record
return {
@@ -168,6 +172,21 @@ def _evidence_payload(view) -> dict[str, Any]:
"basis": record.basis if record is not None else None,
"observed_at": record.payload()["observed_at"] if record is not None else None,
"detail": record.detail if record is not None else None,
+ "changes_at": _utc_text(view.changes_at),
+ }
+
+
+def _price_payload(price: Any) -> dict[str, Any] | None:
+ """The overlay's list price for the cost hint; None when no list price is known, never zero."""
+
+ if price is None:
+ return None
+ return {
+ "unit": price.unit,
+ "usd_per_1k": price.usd_per_1k,
+ "extra": [{"unit": part.unit, "usd_per_1k": part.usd_per_1k} for part in price.extra],
+ "as_of": price.as_of.isoformat(),
+ "url": price.url,
}
@@ -208,7 +227,8 @@ def hosted_tools_status(
candidates = []
for source in _candidate_sources(config):
for model in source.models:
- if spec_for(source.vendor, source.protocol, model.id, tool) is None:
+ spec = spec_for(source.vendor, source.protocol, model.id, tool)
+ if spec is None:
continue
views = {
aspect: evidence.view(
@@ -222,13 +242,18 @@ def hosted_tools_status(
"model_id": model.id,
"call": _evidence_payload(views["call"]),
"replay": _evidence_payload(views["replay"]) if "replay" in views else None,
+ "billing": source.billing,
+ "price": _price_payload(spec.price),
}
)
+ chosen = (toggle.executor.source_id, toggle.executor.model_id) if toggle and toggle.executor else None
tools.append(
{
"name": tool,
"enabled": bool(toggle and toggle.enabled),
"executor": toggle.executor.to_payload() if toggle and toggle.executor else None,
+ # What a turn would bind now, by the same rule hop resolution uses.
+ "bound": _executor(_Context(evidence, spec_for, engine, shape, now), config, tool, chosen),
"candidates": candidates,
}
)
diff --git a/core/handlers/model_hub/pricing.py b/core/handlers/model_hub/pricing.py
index 8cd70ddd1..7741dd55c 100644
--- a/core/handlers/model_hub/pricing.py
+++ b/core/handlers/model_hub/pricing.py
@@ -10,6 +10,10 @@ Avibe already caches for the model picker, read from the model's first-party
provider only. Every day is priced at the current table — the page says which
table that is — because the table is what we have, not what was in force then.
+A call whose context input exceeds one of the model's context tiers is billed
+whole at that tier's rates. A ledger row holds many calls, so the tier is
+decided when a call is recorded and kept in the row; valuation reads it back.
+
A model with no price is never priced as zero: it is left out and its tokens are
counted, so a total can say how much it does not cover.
"""
@@ -20,7 +24,7 @@ import json
import logging
import math
import re
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from datetime import date, datetime, timedelta
from pathlib import Path
from typing import Any, Callable, Final, Mapping, Optional
@@ -39,6 +43,8 @@ _MAX_INT_DIGITS: Final = 400 # below Python's lowest settable int-to-str digit
_MAX_ALIAS_HOPS: Final = 4
# One-hour cache writes cost twice the input price where the table says nothing.
_CACHE_WRITE_1H_INPUT_MULTIPLE: Final = 2.0
+# The context size models.dev's legacy `cost.context_over_200k` names.
+_LEGACY_CONTEXT_TIER_SIZE: Final = 200_000
# Model IDs the agents send that models.dev does not list under that name.
# Keys are already normalized (lowercase, no date or bracket suffix).
@@ -113,6 +119,9 @@ class ModelPrice:
# counts only when listed: its default is a multiple of input for every
# model, so a defaulted one says nothing about the vendor.
charges_cache_writes: bool = False
+ # Higher rates past a context size, as (size, rates) by ascending size. A call
+ # whose context input exceeds a size is billed whole at that tier's rates.
+ context_tiers: tuple[tuple[int, "ModelPrice"], ...] = ()
def _bounded(value: object, ceiling: float) -> Optional[float]:
@@ -138,8 +147,60 @@ def model_price(cost: object) -> Optional[ModelPrice]:
Input and output are required. A missing cache member falls back to what the
tokens are otherwise: a cache read or write is input.
+
+ Context tiers come from `tiers[]` entries of type `context`, each read by the
+ same rules as the flat price, and from the legacy `context_over_200k` only
+ when no such entry is usable. An unusable tier is ignored; tiers never price
+ a model whose flat price is missing.
+ """
+
+ if not isinstance(cost, Mapping):
+ return None
+ price = _flat_price(cost)
+ if price is None:
+ return None
+ tiers: dict[int, ModelPrice] = {}
+ entries = cost.get("tiers")
+ for entry in entries if isinstance(entries, list) else ():
+ match entry:
+ case {"tier": {"type": "context", "size": int() as size}} if size > 0 and not isinstance(size, bool):
+ rates = _flat_price(entry)
+ if rates is not None:
+ tiers.setdefault(size, rates)
+ if not tiers:
+ legacy = _flat_price(cost.get("context_over_200k"))
+ if legacy is not None:
+ tiers[_LEGACY_CONTEXT_TIER_SIZE] = legacy
+ return replace(price, context_tiers=tuple(sorted(tiers.items()))) if tiers else price
+
+
+def context_tier_size(price: Optional[ModelPrice], context_input_tokens: int) -> int:
+ """The context tier one call falls in: the largest tier size its context input exceeds, or 0.
+
+ Context input is the whole prompt — fresh input plus cache reads and writes —
+ which is what a ledger's `input_tokens` already counts.
+ """
+
+ if price is None:
+ return 0
+ return max((size for size, _rates in price.context_tiers if context_input_tokens > size), default=0)
+
+
+def context_tier_price(price: ModelPrice, size: int) -> ModelPrice:
+ """The rates usage recorded in the context tier `size` is valued at.
+
+ That tier's rates; or, once the table no longer lists that size, those of the
+ largest listed tier below it, which the call exceeded too. Tier 0 is the base.
"""
+ rates = price
+ for tier_size, tier_rates in price.context_tiers:
+ if tier_size <= size:
+ rates = tier_rates
+ return rates
+
+
+def _flat_price(cost: object) -> Optional[ModelPrice]:
if not isinstance(cost, Mapping):
return None
input_price = _price(cost.get("input"))
@@ -193,6 +254,24 @@ def _first_party(model_id: str, vendor_map: Mapping[str, Any]) -> Optional[str]:
return max(matches, key=lambda item: len(item["prefix"]))["vendor_id"]
+def _first_party_costs(catalog: Mapping[str, Any], vendor_map: Mapping[str, Any]) -> dict[str, dict[str, object]]:
+ """Each first-party provider's `cost` objects by model key: the part of the catalog a price is read from."""
+
+ families = vendor_map.get("families")
+ vendors = {
+ item["vendor_id"]
+ for item in (families if isinstance(families, list) else ())
+ if isinstance(item, Mapping) and isinstance(item.get("vendor_id"), str)
+ }
+ costs: dict[str, dict[str, object]] = {}
+ for vendor in vendors:
+ provider = catalog.get(vendor)
+ models = provider.get("models") if isinstance(provider, Mapping) else None
+ if isinstance(models, Mapping):
+ costs[vendor] = {key: entry.get("cost") for key, entry in models.items() if isinstance(entry, Mapping)}
+ return costs
+
+
def plan_key(vendor: str, plan: Optional[str]) -> Optional[str]:
"""Resolve a reported plan to a fee-table key, or None when it is not a known plan."""
@@ -235,14 +314,26 @@ class PriceTable:
self.price_table_date = price_table_date
# No models.dev table yet, and a first fetch is running that should land.
self.pending = pending
- self._catalog = catalog
+ # Only first-party prices are ever read, so they are all a table keeps:
+ # held between reads it costs kilobytes, not the parsed models.dev copy.
+ # Every price is parsed here, when the table is built, which is never on the
+ # controller loop (at startup, then on the usage writer's thread), so a
+ # lookup on the loop is a dictionary read however large the catalog is.
+ self._prices: dict[str, dict[str, Optional[ModelPrice]]] = {
+ vendor: {key: model_price(cost) for key, cost in costs.items()}
+ for vendor, costs in _first_party_costs(catalog, vendor_map).items()
+ }
self._vendor_map = vendor_map
- self._model_overrides: dict[str, Mapping[str, Any]] = {}
+ self._model_overrides: dict[str, tuple[Optional[str], Optional[ModelPrice]]] = {}
models = overrides.get("models")
if isinstance(models, Mapping):
for key, entry in models.items():
if isinstance(key, str) and len(key) <= _MAX_KEY_CHARS and isinstance(entry, Mapping):
- self._model_overrides[normalize_model_id(key)] = entry
+ alias = entry.get("alias")
+ self._model_overrides[normalize_model_id(key)] = (
+ normalize_model_id(alias) if isinstance(alias, str) and alias.strip() else None,
+ model_price(entry),
+ )
self._fees = dict(PLAN_FEES_USD)
plans = overrides.get("plans")
if isinstance(plans, Mapping):
@@ -282,10 +373,9 @@ class PriceTable:
return None
override = self._model_overrides.get(key)
if override is not None:
- alias = override.get("alias")
- if isinstance(alias, str) and alias.strip():
- return self._resolve(normalize_model_id(alias), hops=hops + 1)
- price = model_price(override)
+ alias, price = override
+ if alias is not None:
+ return self._resolve(alias, hops=hops + 1)
if price is not None:
return price
price = self._catalog_price(key)
@@ -300,14 +390,7 @@ class PriceTable:
vendor = _first_party(key, self._vendor_map)
if vendor is None:
return None
- provider = self._catalog.get(vendor)
- models = provider.get("models") if isinstance(provider, Mapping) else None
- if not isinstance(models, Mapping):
- return None
- entry = models.get(key)
- if not isinstance(entry, Mapping):
- return None
- return model_price(entry.get("cost"))
+ return self._prices.get(vendor, {}).get(key)
def fields(self) -> dict[str, Any]:
"""The table's own part of every priced block: currency, date, and a first fetch still running."""
@@ -357,7 +440,7 @@ class Cost:
def row_cost(row: Mapping[str, Any], price: Optional[ModelPrice]) -> Cost:
- """Price one ledger row's counters at one model's price."""
+ """Price one ledger row's counters at one model's price, in the row's context tier."""
input_tokens = int(row.get("input_tokens") or 0)
output_tokens = int(row.get("output_tokens") or 0)
@@ -366,6 +449,7 @@ def row_cost(row: Mapping[str, Any], price: Optional[ModelPrice]) -> Cost:
unreported = int(row.get("requests") or 0) > int(row.get("token_reports") or 0)
if price is None:
return Cost(excluded_tokens=input_tokens + output_tokens, api_cost_lower_bound=unreported)
+ price = context_tier_price(price, int(row.get("context_tier") or 0))
cache_read = min(int(row.get("cached_input_tokens") or 0), input_tokens)
cache_write = min(int(row.get("cache_write_input_tokens") or 0), input_tokens - cache_read)
cache_write_1h = min(int(row.get("cache_write_1h_input_tokens") or 0), cache_write)
@@ -540,3 +624,78 @@ def quota_values(
else None
),
}
+
+
+# --- hosted tools (model-hub-capability-model.md §6.4) ----------------------
+#
+# 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
+
+# The provider counter that counts one unit of a hosted tool's list price.
+_HOSTED_UNIT_COUNTERS: Final[Mapping[tuple[str, str], str]] = {
+ ("web_search", "call"): "web_search_calls",
+ ("web_search", "search"): "web_search_requests",
+ ("x_search", "call"): "x_search_calls",
+ ("x_search", "post"): "x_posts_fetched",
+ ("x_search", "profile"): "x_users_fetched",
+}
+
+
+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,
+ reported_usd: Optional[float],
+ model_price: Optional[ModelPrice],
+ usage: Any,
+ tool_prices: Mapping[str, Any],
+ counts: Mapping[str, int],
+) -> Optional[tuple[str, Optional[float]]]:
+ """``(basis, usd)`` for one hosted response, or None when no price is known (never zero).
+
+ A subscription's call is ``included``. A provider's own figure for the whole
+ response is ``reported``. Otherwise the ``list`` price is the response's
+ tokens at the model's rates (in its context tier) plus each used tool's list
+ fee from the provider's counters; a missing token price, tool price or
+ counter makes the whole response unknown rather than partly priced.
+ ``usage`` is a ``ProtocolUsageReport``: its input already counts cache tokens.
+ """
+
+ if billing == "monthly":
+ return ("included", None)
+ if reported_usd is not None:
+ return ("reported", reported_usd)
+ if model_price is None or usage is None:
+ return None
+ row = {
+ "input_tokens": usage.input_tokens,
+ "output_tokens": usage.output_tokens,
+ "cached_input_tokens": usage.cached_input_tokens,
+ "cache_write_input_tokens": usage.cache_write_input_tokens,
+ "cache_write_1h_input_tokens": usage.cache_write_1h_input_tokens,
+ "requests": 1,
+ "token_reports": 1,
+ "context_tier": context_tier_size(model_price, usage.input_tokens),
+ }
+ usd = row_cost(row, model_price).api_cost_usd or 0.0
+ for tool, price in tool_prices.items():
+ if price is None:
+ return None
+ for unit, usd_per_1k in ((price.unit, price.usd_per_1k), *((part.unit, part.usd_per_1k) for part in price.extra)):
+ counter = _HOSTED_UNIT_COUNTERS.get((tool, unit))
+ if counter is None or counter not in counts:
+ return None
+ usd += counts[counter] * usd_per_1k / 1000
+ return ("list", usd)
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index b437d43c1..c9c92e935 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -43,6 +43,7 @@ from config.v2_config import (
validate_model_hub_source_client_nonce,
)
from core.agent_auth_service import BackendLoginInProgressError
+from core.agent_core.messages import HostedCost
from core.os_errors import format_os_errno, local_error_detail
from core.services.settings import default_config
from storage.db import get_cached_sqlite_engine
@@ -146,7 +147,7 @@ from .oauth import (
OAuthFlowRegistry,
UnavailableNativeOAuthAdapter,
)
-from .pricing import VALUE_WINDOW_DAYS, PriceTable, load_price_table, quota_values
+from .pricing import VALUE_WINDOW_DAYS, PriceTable, hosted_response_cost, load_price_table, quota_values
from .quota import QuotaSourceRef, SubscriptionQuotaCache, SubscriptionQuotaError
from .provenance import (
REQUEST_NONFALLBACK_TURN_OUTCOME,
@@ -163,7 +164,7 @@ from .provenance import (
)
from .request import ModelHubRequest, without_opaque_history
from .reasoning_tiers import catalog_wire_efforts, resolve_reasoning_tiers
-from .stream_wire import ProtocolSSEState
+from .stream_wire import ProtocolSSEState, ProtocolUsageReport
from .resolver import (
BackendName,
ModelHubTurnResolution,
@@ -1178,7 +1179,13 @@ class ModelHubService:
)
# One writer per ledger, shared with the gateway: both metering populations
# then have the same owner for the lifetime of what they write.
- self.usage_writer = UsageWriter(self.usage)
+ # Read per report: the override file is hand-edited and the catalog refreshes itself.
+ self.price_table: Callable[[], PriceTable] = price_table or (
+ lambda: load_price_table(paths.get_state_dir())
+ )
+ # Built here, at controller startup before the loop serves, so the writer's
+ # first price-table read never runs on the loop and every call is tiered.
+ self.usage_writer = UsageWriter(self.usage, price_table=self.price_table)
self.native_oauth_adapter = native_oauth_adapter or UnavailableNativeOAuthAdapter()
self.oauth_flows = oauth_flows or OAuthFlowRegistry(
paths.get_state_dir() / "model_hub_oauth_flows.json",
@@ -1249,10 +1256,6 @@ class ModelHubService:
self._builtin_snapshot_cache: dict[BackendName, list[dict[str, Any]]] = {}
self._pending_builtin_catalog_refresh: set[BackendName] = set()
self.quota = SubscriptionQuotaCache(self._fetch_subscription_quota, now=lambda: self.now())
- # Read per report: the override file is hand-edited and the catalog refreshes itself.
- self.price_table: Callable[[], PriceTable] = price_table or (
- lambda: load_price_table(paths.get_state_dir())
- )
# A cached copy only: the picker read must not wait on the network.
self.models_dev_catalog: Callable[[], Mapping[str, Any]] = models_dev_catalog or (
lambda: _cached_models_dev_catalog()
@@ -2759,8 +2762,12 @@ class ModelHubService:
config: ModelHubConfig | None = None,
) -> dict:
payload = source.to_payload()
+ observed_at = self.now()
for model in payload["models"]:
model.setdefault("retired", False)
+ refused = self._refused_efforts(source, model["id"], observed_at)
+ if refused:
+ model["refused_efforts"] = refused
payload["adopted_by"] = self._adopted_by(source.id, config)
return self._source_account_payload(payload)
@@ -5909,6 +5916,41 @@ class ModelHubService:
now=self.now(),
)
+ def hosted_call_cost(
+ self,
+ source: ModelHubSourceConfig,
+ model_id: str,
+ tools: Iterable[str],
+ *,
+ usage: Optional[ProtocolUsageReport],
+ counts: Mapping[str, int],
+ reported_usd: Optional[float] = None,
+ ) -> Optional[HostedCost]:
+ """The cost of one hosted response served by ``source``/``model_id``; None when unknown, never zero.
+
+ Vibey's ``hosted_summary`` and the gateway's ``ProxyExecution`` both ask
+ here, so only the pricing module turns usage into money. Memory-only:
+ the token price comes from the table the usage writer already holds, so
+ a response that ends before the first table is read is simply unpriced.
+ """
+
+ prices = self.usage_writer.held_prices
+ priced = hosted_response_cost(
+ billing=source.billing,
+ reported_usd=reported_usd,
+ model_price=prices.price(model_id) if prices is not None else None,
+ usage=usage,
+ tool_prices={
+ tool: (spec.price if (spec := hosted_tool_spec(source.vendor, source.protocol, model_id, tool)) else None)
+ for tool in tools
+ },
+ counts=counts,
+ )
+ if priced is None:
+ return None
+ basis, usd = priced
+ return HostedCost(basis=basis, usd=None if usd is None else round(usd, 6))
+
def hosted_tools_for_hop(self, config: ModelHubConfig, source: ModelHubSourceConfig, model_id: str) -> dict:
"""``HopResolution.hosted_tools`` for a Vibey launch served by this Source and model."""
@@ -6971,15 +7013,20 @@ class ModelHubService:
source, model_id, record.feature, engine=self.engine_stamp, shape=HOSTED_PROBE_SHAPE, now=now,
)
if view.status == "unsupported":
- refused.append(record)
+ refused.append(view)
return [
{
- "effort": record.feature.name,
- "basis": record.basis,
- "observed_at": record.payload()["observed_at"],
- "detail": record.detail,
+ "effort": view.record.feature.name,
+ "basis": view.record.basis,
+ "observed_at": view.record.payload()["observed_at"],
+ "detail": view.record.detail,
+ "changes_at": (
+ view.changes_at.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
+ if view.changes_at is not None
+ else None
+ ),
}
- for record in sorted(refused, key=lambda item: (item.observed_at, item.feature.name))
+ for view in sorted(refused, key=lambda item: (item.record.observed_at, item.record.feature.name))
]
def agent_chain(self, backend: str, model_id: object) -> dict:
diff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.py
index 409aa7844..4d6f6dc69 100644
--- a/core/handlers/model_hub/usage.py
+++ b/core/handlers/model_hub/usage.py
@@ -6,8 +6,8 @@ over populations that ``InvokeHandle.stream is not None`` keeps disjoint: the
resolver reports every call it consumed itself, including a failover hop that
billed us before the turn moved on, and the turn gateway reports every call whose
body it forwarded. This module owns what happens to those counts afterwards: one
-bounded daily aggregate per source and model, and the read shape the settings page
-consumes.
+bounded daily aggregate per source, model, and context tier, and the read shape the
+settings page consumes.
Two properties are deliberate. `requests` is self-measured by our own code and is
always available; token counts are vendor-reported and may be absent, which is
@@ -37,10 +37,11 @@ from concurrent.futures import Future as CFuture
from dataclasses import dataclass, replace
from datetime import date, datetime, time, timedelta, timezone
from pathlib import Path
+from time import monotonic
from typing import Callable, Final, Mapping, Optional, Sequence
from .identifiers import persisted_ledger_key, usage_ledger_key
-from .pricing import Cost, ModelPrice, PriceTable, row_cost
+from .pricing import Cost, ModelPrice, PriceTable, context_tier_size, row_cost
from .state_file import write_state_document
from .stream_wire import ProtocolUsageReport
@@ -639,6 +640,11 @@ def _normalize_row(row: object) -> Optional[dict]:
calendar_day = _calendar_day(day)
if calendar_day is None:
return None
+ # Part of the row's identity, so a value that is not a tier size leaves no
+ # row to fold it into. Absent on every row a released version wrote.
+ context_tier = row.get("context_tier", 0)
+ if not isinstance(context_tier, int) or isinstance(context_tier, bool) or context_tier < 0:
+ return None
if all(key not in row for key in _CACHE_WRITE_KEYS):
row = {**_released_cache_write_counters(row), **row}
counters: dict[str, int] = {}
@@ -651,6 +657,8 @@ def _normalize_row(row: object) -> Optional[dict]:
"day": calendar_day.isoformat(),
"source_id": source_id,
"model_id": model_id,
+ # Written only past the base tier, so a base row keeps the released shape.
+ **({"context_tier": context_tier} if context_tier else {}),
**counters,
}
if row.get("history_degraded") is True:
@@ -794,19 +802,38 @@ def _row_price(
return prices.price(keyed_model_labels.get((row["source_id"], row["model_id"]), row["model_id"]))
-def _priced_bucket_row(
- row: dict,
+def _bucket_rows(
+ rows: Sequence[dict],
prices: Optional[PriceTable],
keyed_model_labels: Mapping[tuple[str, str], str],
*,
degraded: bool = False,
-) -> dict:
+) -> list[dict]:
+ """Publish one bucket's rows: one per Source and model, summed across context tiers.
+
+ Each row is valued at its own tier before the sum, because a tier's rates
+ apply only to the calls recorded in it.
+ """
+
+ published: dict[tuple[str, str], dict] = {}
+ costs: dict[tuple[str, str], Cost] = {}
+ for row in rows:
+ key = (row["source_id"], row["model_id"])
+ target = published.setdefault(
+ key, {"source_id": row["source_id"], "model_id": row["model_id"], **_empty_totals()}
+ )
+ _accumulate(target, row)
+ if prices is not None:
+ costs.setdefault(key, Cost()).add(row_cost(row, _row_price(row, prices, keyed_model_labels)))
if prices is None:
- return row
- cost = row_cost(row, _row_price(row, prices, keyed_model_labels))
- # A degraded read lost rows of unknown size, so no figure from it is exact.
- cost.api_cost_lower_bound = cost.api_cost_lower_bound or degraded
- return {**row, **cost.fields()}
+ return [published[key] for key in sorted(published)]
+ priced = []
+ for key in sorted(published):
+ cost = costs[key]
+ # A degraded read lost rows of unknown size, so no figure from it is exact.
+ cost.api_cost_lower_bound = cost.api_cost_lower_bound or degraded
+ priced.append({**published[key], **cost.fields()})
+ return priced
def _recency(
@@ -873,8 +900,10 @@ def _cache_write_increment(usage: Optional[ProtocolUsageReport]) -> dict[str, in
}
-def _row_key(row: dict) -> tuple[str, str, str]:
- return (row["day"], row["source_id"], row["model_id"])
+def _row_key(row: dict) -> tuple[str, str, str, int]:
+ """A row is one day of one model on one Source, in one context tier."""
+
+ return (row["day"], row["source_id"], row["model_id"], row.get("context_tier", 0))
def _empty_totals() -> dict:
@@ -1104,7 +1133,7 @@ class BoundedUsageLedger:
if not isinstance(payload, list):
logger.warning("Model Hub usage ledger %s is not a list of rows", self.path)
return _LedgerRead([], True)
- rows: dict[tuple[str, str, str], dict] = {}
+ rows: dict[tuple[str, str, str, int], dict] = {}
dropped = 0
for item in payload:
row = _normalize_row(item)
@@ -1275,6 +1304,7 @@ class BoundedUsageLedger:
"day": owner_day,
"source_id": source_key,
"model_id": model_key,
+ "context_tier": call.context_tier,
"requests": call.requests,
"token_reports": call.requests if usage is not None else 0,
"input_tokens": usage.input_tokens if usage else 0,
@@ -1681,18 +1711,7 @@ class BoundedUsageLedger:
}
for row in rows:
if row["day"] in by_day:
- by_day[row["day"]].append(
- _priced_bucket_row(
- {
- "source_id": row["source_id"],
- "model_id": row["model_id"],
- **{key: row[key] for key in _COUNTER_KEYS},
- },
- prices,
- keyed_model_labels,
- degraded=read_degraded,
- )
- )
+ by_day[row["day"]].append(row)
buckets = []
for index in range(bounded_days):
bucket_day = from_day + timedelta(days=index)
@@ -1708,9 +1727,11 @@ class BoundedUsageLedger:
"start_at": start.isoformat(),
"end_at": end.isoformat(),
"history_complete": not read_degraded,
- "rows": sorted(
+ "rows": _bucket_rows(
by_day.get(bucket_day.isoformat(), []),
- key=lambda row: (row["source_id"], row["model_id"]),
+ prices,
+ keyed_model_labels,
+ degraded=read_degraded,
),
}
)
@@ -1747,7 +1768,7 @@ class BoundedUsageLedger:
# three local dates. Select rows from their durable UTC-hour evidence
# before applying the current host timezone to their local presentation.
rows, read_degraded = self._hourly_rows(starts=starts, now=report_instant)
- measured_by_bucket: list[dict[tuple[str, str], dict]] = [
+ measured_by_bucket: list[dict[tuple[str, str, int], dict]] = [
{} for _ in starts
]
incomplete: set[int] = set(range(len(starts))) if read_degraded else set()
@@ -1793,7 +1814,7 @@ class BoundedUsageLedger:
if bucket is None:
continue
_start_utc, index = bucket
- key = (row["source_id"], row["model_id"])
+ key = _row_key(row)[1:]
projected = measured_by_bucket[index].get(key)
if projected is None:
start_local = start.astimezone()
@@ -1801,6 +1822,7 @@ class BoundedUsageLedger:
"day": start_local.date().isoformat(),
"source_id": row["source_id"],
"model_id": row["model_id"],
+ **({"context_tier": row["context_tier"]} if "context_tier" in row else {}),
**{counter: 0 for counter in _COUNTER_KEYS},
"last_metered_at": None,
}
@@ -1817,23 +1839,13 @@ class BoundedUsageLedger:
end = starts[index + 1] if index + 1 < len(starts) else report_instant
start_local = start.astimezone()
end_local = end.astimezone()
- projected_rows = [
- _priced_bucket_row(
- {
- "source_id": row["source_id"],
- "model_id": row["model_id"],
- **{counter: row[counter] for counter in _COUNTER_KEYS},
- },
- prices,
- keyed_model_labels,
- # An incomplete hour holds usage it cannot place, so its cost is a floor.
- degraded=index in incomplete,
- )
- for row in sorted(
- measured_by_bucket[index].values(),
- key=lambda row: (row["source_id"], row["model_id"]),
- )
- ]
+ projected_rows = _bucket_rows(
+ list(measured_by_bucket[index].values()),
+ prices,
+ keyed_model_labels,
+ # An incomplete hour holds usage it cannot place, so its cost is a floor.
+ degraded=index in incomplete,
+ )
bucket_rows.append(
{
"key": start_local.isoformat(timespec="seconds"),
@@ -1919,6 +1931,11 @@ _LEDGER_EXECUTOR: Optional[_AbandonableWriter] = None
# local read-modify-write and an fsync plus scheduling slack, which is orders of
# magnitude under it, so nothing but a disk that has stopped answering gets here.
_DURABILITY_WAIT_SECONDS: Final = 2.0
+# How long a price table the writer read decides context tiers before a flush reads
+# it again. A read parses the whole models.dev copy, megabytes, so it happens on the
+# writer's thread rather than once per call; the override file is hand-edited, and
+# minutes are soon enough for an edit to reach new calls.
+_PRICE_TABLE_TTL_SECONDS: Final = 300.0
def _ledger_executor() -> _AbandonableWriter:
@@ -1961,6 +1978,9 @@ class UsageCall:
at: datetime
requests: int = 1
owner_day: str = ""
+ # The context tier the call was billed in (`pricing.context_tier_size`), 0 for
+ # the base rates. Decided per call, since a folded row can no longer tell.
+ context_tier: int = 0
def __post_init__(self) -> None:
# An init field intentionally survives dataclasses.replace during a fold.
@@ -1969,11 +1989,13 @@ class UsageCall:
object.__setattr__(self, "owner_day", local_usage_day(self.at).isoformat())
@property
- def fold_key(self) -> tuple[str, str, str, str, bool]:
+ def fold_key(self) -> tuple[str, str, str, str, int, bool]:
"""What makes two calls one daily row and one hourly slice.
The ledger's own row key plus whether tokens were reported, which is the
part that keeps a fold arithmetically identical to the calls it replaces.
+ The row key includes the context tier, so calls billed at different rates
+ never fold: one call's tier would otherwise price the other's tokens.
The hour is part of the queue key so a flush cannot merge calls from
different hours before the ledger sees their temporal identity. The local
date must also remain: a UTC hour can cross local midnight, and folding
@@ -1985,6 +2007,7 @@ class UsageCall:
_hour_key(self.at),
self.source_id,
self.model_id,
+ self.context_tier,
self.usage is not None,
)
@@ -2046,12 +2069,31 @@ class UsageWriter:
something this module exists to prevent: a capacity means choosing rows to
drop, which loses billed usage, and blocking the caller stalls a served turn
on a disk that is already failing.
+
+ A call's context tier is part of its row, so the writer decides it before the
+ call folds, from the price table it holds: read when the writer is built, at
+ controller startup, and refreshed on its own thread.
"""
- def __init__(self, ledger: BoundedUsageLedger, *, durability_wait: float = _DURABILITY_WAIT_SECONDS):
+ def __init__(
+ self,
+ ledger: BoundedUsageLedger,
+ *,
+ durability_wait: float = _DURABILITY_WAIT_SECONDS,
+ price_table: Optional[Callable[[], PriceTable]] = None,
+ ):
self.ledger = ledger
self._durability_wait = durability_wait
- self._pending: dict[tuple[str, str, str, str, bool], _QueuedRow] = {}
+ self._pending: dict[tuple[str, str, str, str, int, bool], _QueuedRow] = {}
+ # Where context tiers come from: the valuation's table factory, and the
+ # table last read from it with the monotonic instant it was read.
+ self._price_table = price_table
+ self._prices: Optional[tuple[PriceTable, float]] = None
+ if price_table is not None:
+ # Read here, once: the writer is built with Model Hub's service at
+ # controller startup, before anything is metered or served, so every
+ # call finds a table and is tiered when it is recorded.
+ self._read_prices()
# The batch on its way to disk, kept visible so a drain that times out
# can count it: in the executor is not the same as persisted.
self._writing: tuple[_QueuedRow, ...] = ()
@@ -2060,6 +2102,13 @@ class UsageWriter:
# starts and ends rather than once per failed write.
self._dropping = False
+ @property
+ def held_prices(self) -> Optional[PriceTable]:
+ """The price table this writer last read, without any I/O; None before its first read."""
+
+ held = self._prices
+ return held[0] if held is not None else None
+
def record(
self,
*,
@@ -2082,12 +2131,22 @@ class UsageWriter:
`wait_recorded`; one that does not can simply drop it. Callers whose calls
fold together share one future, which is the same promise each would have
had alone: it completes when their row reaches the disk.
+
+ The call's context tier is decided here from the price table the writer
+ holds, a lookup in memory. A writer built without a table, or holding one
+ without tiers (no models.dev copy yet), records the base tier.
"""
- call = UsageCall(source_id=source_id, model_id=model_id, usage=usage, at=at)
- queued = self._pending.get(call.fold_key)
- if queued is None:
- queued = _QueuedRow(call=call, done=asyncio.get_running_loop().create_future())
+ call = UsageCall(
+ source_id=source_id,
+ model_id=model_id,
+ usage=usage,
+ at=at,
+ context_tier=self._context_tier(model_id, usage),
+ )
+ done = asyncio.get_running_loop().create_future
+ if (queued := self._pending.get(call.fold_key)) is None:
+ queued = _QueuedRow(call=call, done=done())
self._pending[call.fold_key] = queued
else:
queued.call = queued.call.folded_with(call)
@@ -2131,7 +2190,10 @@ class UsageWriter:
because the hub got busier.
"""
- return sum(queued.call.requests for queued in (*self._pending.values(), *self._writing))
+ return sum(
+ queued.call.requests
+ for queued in (*self._pending.values(), *self._writing)
+ )
async def drain(self, *, timeout: float) -> int:
"""Wait out the calls still queued; answers how many did not reach disk.
@@ -2159,11 +2221,11 @@ class UsageWriter:
self._pending = {}
self._writing = batch
try:
- await loop.run_in_executor(
- _ledger_executor(),
- self.ledger.record_many,
- tuple(queued.call for queued in batch),
- )
+ calls = tuple(queued.call for queued in batch)
+ if self._prices_due():
+ # A refresh for the calls after this batch; these are already tiered.
+ await loop.run_in_executor(_ledger_executor(), self._read_prices)
+ await loop.run_in_executor(_ledger_executor(), self.ledger.record_many, calls)
except (OSError, ValueError) as exc:
self._report_dropped(batch, exc)
else:
@@ -2174,6 +2236,37 @@ class UsageWriter:
if not queued.done.done():
queued.done.set_result(None)
+ def _context_tier(self, model_id: str, usage: Optional[ProtocolUsageReport]) -> int:
+ """The tier the held price table puts one call in; the base tier without usage or a table."""
+
+ held = self._prices
+ if usage is None or held is None:
+ return 0
+ return context_tier_size(held[0].price(model_id), usage.input_tokens)
+
+ def _prices_due(self) -> bool:
+ """Whether the next flush re-reads the price table: none held, too old, or still being fetched."""
+
+ if self._price_table is None:
+ return False
+ held = self._prices
+ return held is None or held[0].pending or monotonic() - held[1] >= _PRICE_TABLE_TTL_SECONDS
+
+ def _read_prices(self) -> None:
+ """Read the price table; one that cannot be read leaves the held one (or none).
+
+ Never on the controller loop: at construction, before anything is served,
+ and afterwards on the writer's thread. A valuation must never cost a
+ metered call.
+ """
+
+ if self._price_table is None:
+ return
+ try:
+ self._prices = (self._price_table(), monotonic())
+ except Exception: # noqa: BLE001 - valuation is optional; metering is not
+ logger.warning("Model Hub usage metering could not read the price table", exc_info=True)
+
def _report_dropped(self, batch: Sequence[_QueuedRow], exc: BaseException) -> None:
"""Report that metering stopped, once per outage rather than per flush.
diff --git a/docs/plans/model-hub-capability-model.md b/docs/plans/model-hub-capability-model.md
index e8a122fa2..5b1363058 100644
--- a/docs/plans/model-hub-capability-model.md
+++ b/docs/plans/model-hub-capability-model.md
@@ -230,7 +230,7 @@ and the existing tone vocabulary (`TimeHint` for dates):
| --- | --- | --- |
| Token prices: input, output, cache read, cache write | models.dev base `cost.*`; the user's override file | used |
| One-hour cache write | override file, or 2× input by default (`pricing.py`) | used; models.dev has no field |
-| **Context-tier prices** (a higher rate past a context size) | models.dev `cost.tiers[]` with `{"tier": {"type": "context", "size": N}}`, plus the legacy `cost.context_over_200k`. On 2026-10-13: 630 and 517 models (e.g. `gpt-6-astra` above 272K: $20/$75; `grok-4.6` above 200K: $4/$12) | **not used.** `model_price` reads only the flat fields, so valuation understates long-context use. Fix: when a call's total context input (input plus cache-read and cache-write tokens) exceeds `size`, the tier's rates apply to the whole call, as the vendors bill. The usage ledger aggregates per (day, Source, model) and keeps no per-call rows, so the tier must be applied when a call is recorded (Phase 1 pricing PR). |
+| **Context-tier prices** (a higher rate past a context size) | models.dev `cost.tiers[]` with `{"tier": {"type": "context", "size": N}}`, plus the legacy `cost.context_over_200k` (size 200K, read only when no context tier is usable); an override entry in the same shape. On 2026-10-13: 630 and 517 models (e.g. `gpt-6-astra` above 272K: $20/$75; `grok-4.6` above 200K: $4/$12) | used. `model_price` reads each tier by the flat-price rules and ignores an unusable one. A call whose total context input (input plus cache-read and cache-write tokens, which the ledger's `input_tokens` already counts) exceeds a size is billed whole at that tier's rates; the highest tier exceeded wins. The ledger keeps no per-call rows, so the usage writer decides the tier when it records a call, from a price table it reads off the event loop and holds for five minutes, and the tier is part of the row's identity (`context_tier`, persisted only above the base tier, so released rows read as base). Valuation prices each row at its own tier and sums tiers per Source and model; a tier the table no longer lists is valued at the largest listed tier below it. |
| **Hosted-tool call prices** | overlay `providers.<vendor>.models[].hosted_tools.<protocol>.<tool>.price` (§4): unit, USD per 1,000 units, date and source URL | new. models.dev has none; the open proposal anomalyco/models.dev#8707 adds `cost.web_search = {search, prompt}` (no maintainer response yet) |
| Search-result tokens | the provider's usage (input tokens), priced by the token rows | already counted as input |
| Provider-reported cost | per-call usage, when present: xAI `cost_in_usd_ticks` (USD × 10¹⁰), `server_side_tool_usage_details`; Anthropic `server_tool_use.web_search_requests` | not read today; hosted tools read it (§6.4) |
@@ -262,7 +262,9 @@ and the existing tone vocabulary (`TimeHint` for dates):
- native: the tool fee per call plus a token estimate;
- proxy: the same plus the executor model's call.
- All of it is computed by the one pricing owner, `pricing.py`. It is stored once per response: as the message's
+ All of it is computed by the one pricing owner, `pricing.py` (`hosted_response_cost`, reached through
+ `ModelHubService.hosted_call_cost`, which reads only the price table the usage writer already holds, so pricing a
+ response does no I/O). It is stored once per response: as the message's
`hosted_summary.cost` for native calls, and as `ProxyExecution.cost` for a proxied call, which is its own executor
response. A provider-reported figure is never copied into individual calls. Neither the
executor nor an adapter prices anything itself.
diff --git a/docs/plans/model-hub-contracts/agent-chain.schema.json b/docs/plans/model-hub-contracts/agent-chain.schema.json
index 86bbcd5f3..a2b1e6f29 100644
--- a/docs/plans/model-hub-contracts/agent-chain.schema.json
+++ b/docs/plans/model-hub-contracts/agent-chain.schema.json
@@ -104,13 +104,14 @@
"description": "Reasoning efforts this exact hop is currently known to refuse (capability evidence, model-hub-capability-model.md §3.4), oldest evidence first; absent when none. A request at one of them skips this hop. The effort menu omits a tier only when every hop that can serve the model lists it, and otherwise marks it \"not on: <Source>\". Read-only: routing reads the evidence store itself.",
"items": {
"type": "object",
- "required": ["effort", "basis", "observed_at", "detail"],
+ "required": ["effort", "basis", "observed_at", "detail", "changes_at"],
"additionalProperties": false,
"properties": {
"effort": { "type": "string", "minLength": 1 },
"basis": { "enum": ["probe", "observed"] },
"observed_at": { "type": "string", "format": "date-time" },
- "detail": { "type": ["string", "null"], "maxLength": 64 }
+ "detail": { "type": ["string", "null"], "maxLength": 64 },
+ "changes_at": { "type": ["string", "null"], "format": "date-time", "description": "When this refusal stops reading as it does now (observed expiry, probe re-verify mark); null when nothing is scheduled." }
}
}
}
diff --git a/docs/plans/model-hub-contracts/hosted-tools-status.schema.json b/docs/plans/model-hub-contracts/hosted-tools-status.schema.json
index 6384b87df..5dda25e88 100644
--- a/docs/plans/model-hub-contracts/hosted-tools-status.schema.json
+++ b/docs/plans/model-hub-contracts/hosted-tools-status.schema.json
@@ -12,7 +12,7 @@
"description": "Every catalog tool, in catalog order.",
"items": {
"type": "object",
- "required": ["name", "enabled", "executor", "candidates"],
+ "required": ["name", "enabled", "executor", "bound", "candidates"],
"additionalProperties": false,
"properties": {
"name": { "enum": ["web_search", "x_search", "image_generation"] },
@@ -32,12 +32,27 @@
}
]
},
+ "bound": {
+ "description": "The executor a turn would bind now, by the same rule hop resolution uses: the chosen executor if verified, else the first verified candidate in Vibey's Source order; null when none is verified.",
+ "oneOf": [
+ { "type": "null" },
+ {
+ "type": "object",
+ "required": ["source_id", "model_id"],
+ "additionalProperties": false,
+ "properties": {
+ "source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },
+ "model_id": { "type": "string", "minLength": 1 }
+ }
+ }
+ ]
+ },
"candidates": {
"type": "array",
"description": "Every (Source, model) the overlay offers the tool on, with an eligible credential and an untranslated path; Vibey's Source order first.",
"items": {
"type": "object",
- "required": ["source_id", "model_id", "call", "replay"],
+ "required": ["source_id", "model_id", "call", "replay", "billing", "price"],
"additionalProperties": false,
"properties": {
"source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },
@@ -46,6 +61,11 @@
"replay": {
"description": "Null for image_generation, which is never replayed.",
"oneOf": [{ "type": "null" }, { "$ref": "#/definitions/Evidence" }]
+ },
+ "billing": { "enum": ["monthly", "metered"], "description": "The Source's billing: monthly shows \"included in subscription\", metered shows the list price \"at API price\"." },
+ "price": {
+ "description": "The overlay's list price for this tool on this provider, or null when no list price is known (never zero). OpenAI lists no per-image price, so image_generation has none.",
+ "oneOf": [{ "type": "null" }, { "$ref": "#/definitions/ListPrice" }]
}
}
}
@@ -64,16 +84,40 @@
}
},
"definitions": {
+ "ListPrice": {
+ "type": "object",
+ "required": ["unit", "usd_per_1k", "extra", "as_of", "url"],
+ "additionalProperties": false,
+ "properties": {
+ "unit": { "enum": ["call", "search", "post", "profile"] },
+ "usd_per_1k": { "type": "number", "minimum": 0 },
+ "extra": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["unit", "usd_per_1k"],
+ "additionalProperties": false,
+ "properties": {
+ "unit": { "enum": ["call", "search", "post", "profile"] },
+ "usd_per_1k": { "type": "number", "minimum": 0 }
+ }
+ }
+ },
+ "as_of": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$" },
+ "url": { "type": "string", "pattern": "^https://" }
+ }
+ },
"Evidence": {
"type": "object",
- "required": ["status", "stale", "basis", "observed_at", "detail"],
+ "required": ["status", "stale", "basis", "observed_at", "detail", "changes_at"],
"additionalProperties": false,
"properties": {
"status": { "enum": ["verified", "unsupported", "unknown"], "description": "As routing reads it." },
"stale": { "enum": [null, "wire", "age"] },
"basis": { "enum": [null, "probe", "observed"] },
"observed_at": { "type": ["string", "null"] },
- "detail": { "type": ["string", "null"], "maxLength": 64 }
+ "detail": { "type": ["string", "null"], "maxLength": 64 },
+ "changes_at": { "type": ["string", "null"], "description": "When this record stops reading as it does now: an observed record's expiry or a probe record's re-verify mark; null when nothing is scheduled." }
}
}
}
diff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.json
index 242aaf0b6..087d93c81 100644
--- a/docs/plans/model-hub-contracts/source.schema.json
+++ b/docs/plans/model-hub-contracts/source.schema.json
@@ -439,6 +439,23 @@
"null"
],
"format": "date-time"
+ },
+ "refused_efforts": {
+ "type": "array",
+ "minItems": 1,
+ "description": "Server-derived, read-only: the reasoning efforts this Source model currently refuses (capability evidence, model-hub-capability-model.md §3.4), the same shape as an AgentChain hop's. Absent when none. Returned on Source reads only; never persisted on the Source record and never accepted in a write.",
+ "items": {
+ "type": "object",
+ "required": ["effort", "basis", "observed_at", "detail", "changes_at"],
+ "additionalProperties": false,
+ "properties": {
+ "effort": { "type": "string", "minLength": 1 },
+ "basis": { "enum": ["probe", "observed"] },
+ "observed_at": { "type": "string", "format": "date-time" },
+ "detail": { "type": ["string", "null"], "maxLength": 64 },
+ "changes_at": { "type": ["string", "null"], "format": "date-time" }
+ }
+ }
}
}
}
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index d2aa9b985..40d957ee8 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -1120,6 +1120,18 @@ scenarios:
kind: recovery
layer: unit
test: tests/test_model_hub_usage.py::test_future_hourly_evidence_is_incomplete_on_read_and_after_a_write
+ - id: MH-USAGE-BACKEND-009
+ name: A ledger row whose context tier is not a size is dropped like any unusable row
+ status: covered
+ kind: compatibility
+ layer: unit
+ test: tests/test_model_hub_usage.py::test_a_row_whose_context_tier_is_not_a_size_is_dropped
+ - id: MH-USAGE-BACKEND-010
+ name: The usage writer reads the price table once before the loop serves and tiers every call when it is recorded
+ status: covered
+ kind: recovery
+ layer: unit
+ test: tests/test_model_hub_usage.py::test_the_writer_reads_the_price_table_before_serving_and_tiers_every_call_at_record
- id: MH-USAGE-E2E-001
name: Measured hourly and daily reports reconcile through HTTP and IPC after a controller restart
status: covered
@@ -1450,6 +1462,46 @@ scenarios:
- ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-PRICE-014
- ui/src/components/settings/models/UsageTab.test.tsx::MH-PRICE-014
- ui/src/components/settings/models/QuotaTab.test.tsx::MH-PRICE-014
+ - id: MH-PRICE-015
+ name: A models.dev context tier is parsed by the flat price's rules, with the legacy over-200K price only when no tier is usable
+ status: covered
+ kind: compatibility
+ layer: unit
+ test: tests/test_model_hub_pricing.py::test_model_price_reads_context_tiers_by_the_flat_price_rules
+ - id: MH-PRICE-016
+ name: A call is recorded in the tier its whole context input exceeds and valued at that tier's rates
+ status: covered
+ kind: contract
+ layer: unit
+ test: tests/test_model_hub_pricing.py::test_a_call_is_recorded_in_the_tier_its_context_exceeds_and_valued_at_its_rates
+ related_tests:
+ - tests/test_model_hub_pricing.py::test_cache_reads_and_writes_count_toward_the_context_tier
+ - id: MH-PRICE-017
+ name: A released ledger reads and values unchanged, and a tiered call lands on its own row beside it
+ status: covered
+ kind: compatibility
+ layer: unit
+ test: tests/test_model_hub_pricing.py::test_a_released_ledger_reads_unchanged_and_a_tiered_call_lands_beside_it
+ - id: MH-PRICE-018
+ name: Calls of different tiers never fold together, and every report sums them per model
+ status: covered
+ kind: contract
+ layer: unit
+ test: tests/test_model_hub_pricing.py::test_tiers_never_fold_together_and_every_read_sums_them_per_model
+ - id: MH-PRICE-020
+ name: A hosted response is priced by the one pricing owner as included, reported or list, and is unpriced rather than zero when anything is unknown
+ status: covered
+ kind: contract
+ 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
+ - 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
+ kind: recovery
+ layer: unit
+ test: tests/test_model_hub_pricing.py::test_a_tiered_row_is_valued_at_the_largest_listed_tier_it_exceeded
- id: MH-RES-LIVE-001
name: Live turn retries an eligible backup before streaming starts
status: covered
diff --git a/tests/test_model_hub_capability_evidence.py b/tests/test_model_hub_capability_evidence.py
index f0c32c905..fd0de77aa 100644
--- a/tests/test_model_hub_capability_evidence.py
+++ b/tests/test_model_hub_capability_evidence.py
@@ -91,6 +91,13 @@ def test_evidence_resolves_for_routing(feature, changes, engine, shape, age, sta
record = _record(source, feature, **changes)
view = resolve(record, source=source, engine=engine, shape=shape, now=NOW + age)
assert (view.status, view.stale) == (status, stale)
+ # When the reading changes on its own: an observed record expires, a fresh probe record ages.
+ if view.status == "unknown" and view.stale is None:
+ assert view.changes_at is None
+ elif record.basis == "observed":
+ assert view.changes_at == record.observed_at + timedelta(days=7)
+ else:
+ assert view.changes_at == (record.observed_at + timedelta(days=30) if stale is None else None)
def test_a_changed_source_identity_reads_as_unknown_and_is_pruned(tmp_path):
@@ -144,8 +151,12 @@ def test_persisted_records_match_the_schema_and_unreadable_ones_are_unknown(tmp_
{"observed_at": datetime(2026, 10, 13)},
{"shape": -1},
{"source_identity": ""},
+ {"observed_at": datetime(9999, 12, 31, tzinfo=timezone.utc)},
+ ],
+ ids=[
+ "observed-without-detail", "observed-positive", "long-detail", "naive-time", "negative-shape", "no-identity",
+ "expiry-out-of-range",
],
- ids=["observed-without-detail", "observed-positive", "long-detail", "naive-time", "negative-shape", "no-identity"],
)
def test_a_record_refuses_what_the_contract_forbids(changes):
with pytest.raises(ValueError):
diff --git a/tests/test_model_hub_evidence_rules.py b/tests/test_model_hub_evidence_rules.py
index 647776a9e..570b4ff6c 100644
--- a/tests/test_model_hub_evidence_rules.py
+++ b/tests/test_model_hub_evidence_rules.py
@@ -9,6 +9,7 @@ refused effort gets instead of another provider 400.
from __future__ import annotations
import json
+from datetime import timedelta
import pytest
from aiohttp import web
@@ -152,18 +153,22 @@ async def test_a_refused_effort_skips_its_hop_instead_of_another_provider_400(tm
assert second.value.data == {"effort": "ultra", "source_ids": ["src_evidence1"]}
assert len(calls) == 1
- # The chain read projects what routing just used, for the effort menu.
+ # The chain read and the Source read project what routing just used.
+ record = service.capability_evidence.records()[0]
+ refusal = {
+ "effort": "ultra",
+ "basis": "observed",
+ "observed_at": record.payload()["observed_at"],
+ "detail": "400 invalid_request_error",
+ "changes_at": (record.observed_at + timedelta(days=7)).isoformat().replace("+00:00", "Z"),
+ }
chain = service.agent_chain("codex", models["codex"])
_assert_valid("agent-chain.schema.json", chain)
[hop] = [hop for hop in chain["chain"] if hop["source_id"] == "src_evidence1"]
- assert hop["refused_efforts"] == [
- {
- "effort": "ultra",
- "basis": "observed",
- "observed_at": service.capability_evidence.records()[0].payload()["observed_at"],
- "detail": "400 invalid_request_error",
- }
- ]
+ assert hop["refused_efforts"] == [refusal]
+ [listed] = [item for item in service.list_sources() if item["id"] == "src_evidence1"]
+ assert listed["models"][0]["refused_efforts"] == [refusal]
+ _assert_valid("source.schema.json", listed)
served = await service.resolve_with_recovery(
backend="codex", model_id=models["codex"], request=request("high"), stream=False
@@ -276,6 +281,7 @@ async def test_no_request_path_reads_a_bundled_file_after_startup(tmp_path, monk
from pathlib import Path
from core.handlers.model_hub.adapter import RawOutcomeKind, UpstreamRejection
+ from core.handlers.model_hub.stream_wire import ProtocolUsageReport
from tests.test_model_hub_l3 import _canonicalize_fixed_test_routes, _outcome, _service
source = _source("src_startup01", "Startup", vendor="openai", protocol="openai_responses")
@@ -311,6 +317,14 @@ async def test_no_request_path_reads_a_bundled_file_after_startup(tmp_path, monk
service.hosted_tools_for_hop(config, source, "shared-model")
service.agent_chain("codex", model)
service.list_sources()
+ service.hosted_tools_status()
+ service.hosted_call_cost(
+ source,
+ "shared-model",
+ ("web_search",),
+ usage=ProtocolUsageReport.of(input_tokens=10, cached_input_tokens=0, output_tokens=1),
+ counts={"web_search_calls": 1},
+ )
assert reads == []
diff --git a/tests/test_model_hub_hosted_tools_config.py b/tests/test_model_hub_hosted_tools_config.py
index 31feb7fe7..69a22665b 100644
--- a/tests/test_model_hub_hosted_tools_config.py
+++ b/tests/test_model_hub_hosted_tools_config.py
@@ -120,6 +120,15 @@ def test_hosted_tools_never_hold_credential_material():
assert "web_search" not in config.hosted_tools
+def _validate_status(status):
+ from jsonschema import Draft7Validator
+
+ schema = json.loads(
+ (Path(__file__).parents[1] / "docs/plans/model-hub-contracts/hosted-tools-status.schema.json").read_text()
+ )
+ Draft7Validator(schema).validate(status)
+
+
def _api_service(tmp_path):
from config.v2_config import ModelHubSourceConfig
from tests.test_model_hub_api import _service
@@ -153,6 +162,17 @@ async def test_the_tools_api_reads_and_writes_one_tool_at_a_time(tmp_path):
assert [(c["source_id"], c["model_id"], c["call"]["status"]) for c in x_search["candidates"]] == [
("src_xai00001", "grok-4.6", "unknown")
]
+ # The cost hint: the overlay's dated list price and the Source's billing, never a computed zero.
+ assert x_search["bound"] is None
+ assert x_search["candidates"][0]["billing"] == "metered"
+ assert x_search["candidates"][0]["price"] == {
+ "unit": "post",
+ "usd_per_1k": 5,
+ "extra": [{"unit": "profile", "usd_per_1k": 10}],
+ "as_of": "2026-10-13",
+ "url": "https://docs.x.ai/developers/pricing",
+ }
+ _validate_status(status)
assert status["reverify"] == {"engine_upgraded": 0, "aged": 0}
executor = {"source_id": "src_xai00001", "model_id": "grok-4.6"}
diff --git a/tests/test_model_hub_hosted_tools_resolution.py b/tests/test_model_hub_hosted_tools_resolution.py
index 30b727601..b98c53b47 100644
--- a/tests/test_model_hub_hosted_tools_resolution.py
+++ b/tests/test_model_hub_hosted_tools_resolution.py
@@ -237,3 +237,9 @@ def test_status_lists_where_each_tool_can_run_and_counts_re_verifications(tmp_pa
]
assert by_name["image_generation"]["candidates"][0]["replay"] is None
assert status["reverify"] == {"engine_upgraded": 2, "aged": 1}
+ # What a turn would bind now: the age-stale verified XAI call still routes; wire-stale ones do not.
+ assert by_name["web_search"]["bound"] == {"source_id": "src_xai00001", "model_id": "grok-4.6"}
+ assert by_name["x_search"]["bound"] is None
+ # An aged probe record has nothing left to wait for; a wire-stale one waits for the user's re-verify.
+ assert by_name["web_search"]["candidates"][0]["call"]["changes_at"] is None
+ assert by_name["x_search"]["candidates"][0]["call"]["changes_at"] is None
diff --git a/tests/test_model_hub_pricing.py b/tests/test_model_hub_pricing.py
index 8e9af7b1b..986911f69 100644
--- a/tests/test_model_hub_pricing.py
+++ b/tests/test_model_hub_pricing.py
@@ -27,8 +27,8 @@ from core.handlers.model_hub.pricing import (
quota_values,
row_cost,
)
-from core.handlers.model_hub.stream_wire import ProtocolUsageReport
-from core.handlers.model_hub.usage import BoundedUsageLedger, SourceIdentity, UsageCall
+from core.handlers.model_hub.stream_wire import ProtocolUsageReport, extract_protocol_usage
+from core.handlers.model_hub.usage import BoundedUsageLedger, SourceIdentity, UsageCall, UsageWriter
# Shapes as models.dev publishes them (USD per million tokens), at 2026-09 prices.
CATALOG = {
@@ -67,6 +67,46 @@ def _table(overrides=None) -> PriceTable:
return PriceTable(catalog=CATALOG, vendor_map=VENDOR_MAP, overrides=overrides or {}, price_table_date="2026-09-23")
+def _context(size: int) -> dict:
+ return {"type": "context", "size": size}
+
+
+# Context tiers as models.dev publishes them: one tier, two tiers, a cache-write
+# vendor's tier, and a row that has only the legacy 200K object.
+TIERED_CATALOG = {
+ "openai": {
+ "models": {
+ "gpt-6-astra": {"cost": {
+ "input": 10, "output": 50, "cache_read": 1, "cache_write": 12.5,
+ "tiers": [{"input": 20, "output": 75, "cache_read": 2, "cache_write": 25, "tier": _context(272_000)}],
+ }},
+ "gpt-6-nova": {"cost": {
+ "input": 1, "output": 4, "cache_read": 0.1,
+ "tiers": [
+ {"input": 2, "output": 8, "cache_read": 0.2, "tier": _context(32_000)},
+ {"input": 3, "output": 12, "cache_read": 0.3, "tier": _context(128_000)},
+ ],
+ }},
+ }
+ },
+ "anthropic": {
+ "models": {
+ "claude-sonnet-6": {"cost": {
+ "input": 3, "output": 15, "cache_read": 0.3, "cache_write": 3.75,
+ "tiers": [{"input": 6, "output": 22.5, "cache_read": 0.6, "cache_write": 7.5, "tier": _context(200_000)}],
+ }},
+ }
+ },
+ "xai": {"models": {"grok-4.6": {"cost": {
+ "input": 2, "output": 6, "cache_read": 0.5, "context_over_200k": {"input": 4, "output": 12, "cache_read": 1},
+ }}}},
+}
+
+
+def _tiered_table() -> PriceTable:
+ return PriceTable(catalog=TIERED_CATALOG, vendor_map=VENDOR_MAP, overrides={}, price_table_date="2026-10-13")
+
+
def test_model_price_reads_models_dev_cost_and_fills_missing_cache_prices():
"""MH-PRICE-001: A missing cache price is input; a one-hour cache write is twice input unless listed."""
@@ -625,3 +665,283 @@ def test_a_degraded_ledger_read_values_nothing_as_exact(tmp_path):
assert value["week"]["api_cost_lower_bound"] is True
assert value["period"]["api_cost_lower_bound"] is True
assert totals["period"]["api_cost_lower_bound"] is True
+
+
+def test_model_price_reads_context_tiers_by_the_flat_price_rules():
+ """MH-PRICE-015: Context tiers come from `tiers[]`, else the legacy 200K object; a bad tier is ignored alone."""
+
+ rates = {"input": 2, "output": 8}
+ # A missing tier member falls back as the flat price's does, to the tier's own input.
+ tier_rates = ModelPrice(input=2, output=8, cache_read=2, cache_write=2, cache_write_1h=4)
+ assert model_price({"input": 1, "output": 4, "tiers": [{**rates, "tier": _context(32_000)}]}).context_tiers == (
+ (32_000, tier_rates),
+ )
+ assert model_price(TIERED_CATALOG["openai"]["models"]["gpt-6-astra"]["cost"]).context_tiers == ((
+ 272_000,
+ ModelPrice(input=20, output=75, cache_read=2, cache_write=25, cache_write_1h=40, charges_cache_writes=True),
+ ),)
+ assert [size for size, _ in model_price(TIERED_CATALOG["openai"]["models"]["gpt-6-nova"]["cost"]).context_tiers] == [
+ 32_000, 128_000,
+ ]
+ legacy = {"input": 1, "output": 4, "context_over_200k": rates}
+ assert model_price(legacy).context_tiers == ((200_000, tier_rates),)
+ # Listed tiers replace the legacy object, which repeats one of them at the wrong size.
+ assert model_price({**legacy, "tiers": [{**rates, "tier": _context(272_000)}]}).context_tiers == (
+ (272_000, tier_rates),
+ )
+ unusable = [
+ "not a tier", {**rates}, {**rates, "tier": {"type": "time", "size": 1}}, {**rates, "tier": _context(0)},
+ {**rates, "tier": _context(-1)}, {**rates, "tier": _context(True)}, {**rates, "tier": _context("272000")},
+ {**rates, "tier": _context(2.5e5)}, {"input": 2, "tier": _context(64_000)},
+ ]
+ assert model_price({**legacy, "tiers": unusable}).context_tiers == ((200_000, tier_rates),)
+ assert model_price({**legacy, "tiers": [*unusable, {**rates, "tier": _context(64_000)}]}).context_tiers == (
+ (64_000, tier_rates),
+ )
+ assert model_price({"input": 1, "output": 4, "tiers": {"not": "a list"}}).context_tiers == ()
+ # Tiers never price a model that has no flat price.
+ assert model_price({"tiers": [{**rates, "tier": _context(32_000)}]}) is None
+
+
+ ("recorded", "usd"),
+ [(0, 1.0), (16_000, 1.0), (32_000, 2.0), (64_000, 2.0), (128_000, 3.0), (500_000, 3.0)],
+)
+def test_a_tiered_row_is_valued_at_the_largest_listed_tier_it_exceeded(recorded, usd):
+ """MH-PRICE-019: A row is valued at its tier; a size the table no longer lists takes the largest tier below it."""
+
+ price = model_price(TIERED_CATALOG["openai"]["models"]["gpt-6-nova"]["cost"])
+ row = {"requests": 1, "token_reports": 1, "input_tokens": 1_000_000, "output_tokens": 0, "context_tier": recorded}
+ assert row_cost(row, price).api_cost_usd == pytest.approx(usd)
+
+
+# (model, tier) → (input, output) USD per million tokens, from TIERED_CATALOG.
+_TIER_RATES = {
+ ("gpt-6-astra", 0): (10, 50), ("gpt-6-astra", 272_000): (20, 75),
+ ("gpt-6-nova", 0): (1, 4), ("gpt-6-nova", 32_000): (2, 8), ("gpt-6-nova", 128_000): (3, 12),
+ ("grok-4.6", 0): (2, 6), ("grok-4.6", 200_000): (4, 12),
+}
+
+
+ ("model_id", "input_tokens", "tier"),
+ [
+ ("gpt-6-astra", 271_999, 0),
+ ("gpt-6-astra", 272_000, 0),
+ ("gpt-6-astra", 272_001, 272_000),
+ ("gpt-6-nova", 32_000, 0),
+ ("gpt-6-nova", 32_001, 32_000),
+ ("gpt-6-nova", 128_000, 32_000),
+ ("gpt-6-nova", 128_001, 128_000),
+ ("grok-4.6", 200_000, 0),
+ ("grok-4.6", 200_001, 200_000),
+ ],
+)
+async def test_a_call_is_recorded_in_the_tier_its_context_exceeds_and_valued_at_its_rates(
+ tmp_path, model_id, input_tokens, tier,
+):
+ """MH-PRICE-016: A call past a tier size is recorded in that tier and valued whole at its rates; at the size it is not.
+
+ The writer holds the price table from construction, so the first call is
+ tiered exactly like the next.
+ """
+
+ now = datetime(2026, 10, 13, 12, 0, tzinfo=timezone.utc)
+ ledger = BoundedUsageLedger(tmp_path / "usage.json", now=lambda: now)
+ writer = UsageWriter(ledger, price_table=_tiered_table)
+ usage = ProtocolUsageReport.of(input_tokens=input_tokens, cached_input_tokens=0, output_tokens=1_000)
+ for source_id in ("src_first", "src_held"):
+ writer.record(source_id=source_id, model_id=model_id, usage=usage, at=now)
+ assert await writer.drain(timeout=5) == 0
+
+ rows = json.loads(ledger.path.read_text(encoding="utf-8"))
+ assert [row.get("context_tier") for row in rows] == [tier or None] * 2
+ input_rate, output_rate = _TIER_RATES[(model_id, tier)]
+ summary = ledger.summary(days=1, now=now, prices=_tiered_table())
+ for source in summary["sources"]:
+ assert source["api_cost_usd"] == pytest.approx((input_tokens * input_rate + 1_000 * output_rate) / 1e6)
+
+
+async def test_cache_reads_and_writes_count_toward_the_context_tier(tmp_path):
+ """MH-PRICE-016: The tier threshold is the whole context: fresh input plus cache reads and writes."""
+
+ now = datetime(2026, 10, 13, 12, 0, tzinfo=timezone.utc)
+ ledger = BoundedUsageLedger(tmp_path / "usage.json", now=lambda: now)
+ writer = UsageWriter(ledger, price_table=_tiered_table)
+ # Anthropic reports only the 1,000 fresh tokens as `input_tokens`; the context is 201,000.
+ usage = extract_protocol_usage("anthropic", {"usage": {
+ "input_tokens": 1_000, "cache_read_input_tokens": 180_000, "cache_creation_input_tokens": 20_000,
+ "output_tokens": 1_000,
+ }})
+ for _ in range(2): # the first call and a later one, from the same held table
+ writer.record(source_id="src_a", model_id="claude-sonnet-6", usage=usage, at=now)
+ assert await writer.drain(timeout=5) == 0
+
+ [row] = json.loads(ledger.path.read_text(encoding="utf-8"))
+ assert (row["context_tier"], row["requests"]) == (200_000, 2)
+ # fresh 1k × 6 + read 180k × 0.6 + write 20k × 7.5 + out 1k × 22.5, twice
+ totals = ledger.summary(days=1, now=now, prices=_tiered_table())["totals"]
+ assert totals["api_cost_usd"] == pytest.approx(2 * 0.2865)
+
+
+# A ledger exactly as the release before context tiers wrote it: two calls of
+# 300K and 50K input in one row, neither recorded in a tier.
+RELEASED_LEDGER = (
+ '[{"day":"2026-09-25","source_id":"src_a","model_id":"gpt-6-astra","requests":2,"token_reports":2,'
+ '"input_tokens":350000,"cached_input_tokens":100000,"output_tokens":1500,"cache_write_input_tokens":0,'
+ '"cache_write_1h_input_tokens":0,"cache_write_uncaptured_reports":0,"last_metered_at":"2026-09-25T11:40:00+00:00",'
+ '"hours":[{"key":"2026-09-25T11:00:00+00:00","requests":2,"token_reports":2,"input_tokens":350000,'
+ '"cached_input_tokens":100000,"output_tokens":1500,"cache_write_input_tokens":0,"cache_write_1h_input_tokens":0,'
+ '"cache_write_uncaptured_reports":0,"last_metered_at":"2026-09-25T11:40:00+00:00"}],"hourly_history_complete":true,'
+ '"hourly_expired_totals":{"requests":0,"token_reports":0,"input_tokens":0,"cached_input_tokens":0,"output_tokens":0,'
+ '"cache_write_input_tokens":0,"cache_write_1h_input_tokens":0,"cache_write_uncaptured_reports":0},'
+ '"hourly_expired_before":null}]'
+)
+
+
+async def test_a_released_ledger_reads_unchanged_and_a_tiered_call_lands_beside_it(tmp_path):
+ """MH-PRICE-017: Released rows read as the base tier, are never rewritten, and take no tiered call into them."""
+
+ now = datetime(2026, 9, 25, 12, 0, tzinfo=timezone.utc)
+ path = tmp_path / "usage.json"
+ path.write_text(RELEASED_LEDGER, encoding="utf-8")
+ ledger = BoundedUsageLedger(path, now=lambda: now)
+ identities = [SourceIdentity("src_a", "A", ["gpt-6-astra"])]
+ # fresh 250k × 10 + read 100k × 1 + out 1.5k × 50, at base rates although the day's input passed 272K
+ released_usd = 2.675
+ documents = [ledger.summary(days=7, now=now, identities=identities, prices=_tiered_table())]
+ documents += [ledger.report(window=w, now=now, identities=identities, prices=_tiered_table()) for w in ("24h", "7d")]
+ for document in documents:
+ assert document["totals"]["requests"] == 2
+ assert document["totals"]["api_cost_usd"] == pytest.approx(released_usd)
+ assert document["totals"]["api_cost_lower_bound"] is False
+ assert path.read_text(encoding="utf-8") == RELEASED_LEDGER
+
+ writer = UsageWriter(ledger, price_table=_tiered_table)
+ writer.record(
+ source_id="src_a", model_id="gpt-6-astra", at=now,
+ usage=ProtocolUsageReport.of(input_tokens=300_000, cached_input_tokens=0, output_tokens=1_000),
+ )
+ assert await writer.drain(timeout=5) == 0
+
+ persisted = path.read_text(encoding="utf-8")
+ assert persisted.startswith(RELEASED_LEDGER[:-1] + ",")
+ tiered = json.loads(persisted)[1]
+ assert (tiered["context_tier"], tiered["requests"], tiered["input_tokens"]) == (272_000, 1, 300_000)
+ # 300k × 20 + 1k × 75 at the tier's rates
+ summary = ledger.summary(days=7, now=now, identities=identities, prices=_tiered_table())
+ assert summary["totals"]["requests"] == 3
+ assert summary["totals"]["api_cost_usd"] == pytest.approx(released_usd + 6.075)
+
+
+async def test_tiers_never_fold_together_and_every_read_sums_them_per_model(tmp_path):
+ """MH-PRICE-018: Calls in different tiers keep separate rows; each read publishes one row per Source and model."""
+
+ now = datetime(2026, 10, 13, 12, 30, tzinfo=timezone.utc)
+ ledger = BoundedUsageLedger(tmp_path / "usage.json", now=lambda: now)
+ writer = UsageWriter(ledger, price_table=_tiered_table)
+
+ def report(input_tokens: int) -> ProtocolUsageReport:
+ return ProtocolUsageReport.of(input_tokens=input_tokens, cached_input_tokens=0, output_tokens=0)
+
+ writer.record(source_id="src_a", model_id="gpt-6-astra", usage=report(1), at=now)
+ assert await writer.drain(timeout=5) == 0
+ for input_tokens in (100_000, 300_000, 100_000):
+ writer.record(
+ source_id="src_a", model_id="gpt-6-astra", usage=report(input_tokens), at=now,
+ )
+ assert len(writer._pending) == 2
+ assert await writer.drain(timeout=5) == 0
+
+ rows = json.loads(ledger.path.read_text(encoding="utf-8"))
+ assert [(row.get("context_tier", 0), row["requests"], row["input_tokens"]) for row in rows] == [
+ (0, 3, 200_001), (272_000, 1, 300_000),
+ ]
+ # base 200,001 × 10 + tier 300,000 × 20
+ usd = (200_001 * 10 + 300_000 * 20) / 1e6
+ identities = [SourceIdentity("src_a", "A", ["gpt-6-astra"])]
+ documents = [ledger.summary(days=7, now=now, identities=identities, prices=_tiered_table())]
+ documents += [ledger.report(window=w, now=now, identities=identities, prices=_tiered_table()) for w in ("24h", "7d")]
+ for document in documents:
+ _assert_valid("usage-summary.schema.json", document)
+ [model] = document["sources"][0]["models"]
+ assert (model["requests"], model["api_cost_usd"]) == (4, pytest.approx(usd))
+ assert document["totals"]["api_cost_usd"] == pytest.approx(usd)
+ assert sum(day["api_cost_usd"] for day in document["days"]) == pytest.approx(usd)
+ for document in documents[1:]:
+ [bucket] = [bucket for bucket in document["buckets"] if bucket["rows"]]
+ [row] = bucket["rows"]
+ assert (row["requests"], row["input_tokens"], row["api_cost_usd"]) == (4, 500_001, pytest.approx(usd))
+
+
+def _xai_price():
+ from vibe.backend_model_catalog import hosted_tool_spec
+
+ return hosted_tool_spec("xai", "openai_responses", "grok-4.6", "x_search").price
+
+
+ ("billing", "reported", "tool_prices", "counts", "expected"),
+ [
+ ("monthly", 0.5, {"x_search": None}, {}, ("included", None)),
+ ("metered", 0.0012, {"x_search": None}, {}, ("reported", 0.0012)),
+ # 1,000 fresh input at $2/M + 200 output at $6/M, plus 20 posts at $5/1k and 1 profile at $10/1k.
+ (
+ "metered",
+ None,
+ {"x_search": "xai"},
+ {"x_search_calls": 2, "x_posts_fetched": 20, "x_users_fetched": 1},
+ ("list", 0.002 + 0.0012 + 0.1 + 0.01),
+ ),
+ ("metered", None, {"x_search": "xai"}, {"x_posts_fetched": 20}, None),
+ ("metered", None, {"image_generation": None}, {}, None),
+ ],
+ ids=["subscription-included", "provider-reported", "list-tokens-plus-tool-fee", "missing-counter", "no-tool-price"],
+)
+def test_a_hosted_response_is_priced_by_the_one_pricing_owner(billing, reported, tool_prices, counts, expected):
+ """MH-PRICE-020: included, reported or list; anything unknown makes the whole response unpriced, never zero."""
+ from core.handlers.model_hub.pricing import hosted_response_cost
+
+ prices = {tool: (_xai_price() if price == "xai" else price) for tool, price in tool_prices.items()}
+ result = hosted_response_cost(
+ billing=billing,
+ reported_usd=reported,
+ model_price=_table().price("grok-4.6"),
+ usage=ProtocolUsageReport.of(input_tokens=1000, cached_input_tokens=0, output_tokens=200),
+ tool_prices=prices,
+ counts=counts,
+ )
+ if expected is None or expected[1] is None:
+ assert result == expected
+ else:
+ 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
+
+ parsed = []
+ original = pricing.model_price
+
+ def counting(cost):
+ parsed.append(cost)
+ return original(cost)
+
+ monkeypatch.setattr(pricing, "model_price", counting)
+ table = _table(overrides={"models": {"house-model": {"input": 1, "output": 2}, "relay-opus": {"alias": "claude-opus-5"}}})
+ built = len(parsed)
+ assert built > 0
+ for model_id in ("gpt-6-astra", "openai/gpt-5.5", "claude-opus-5[1m]", "house-model", "relay-opus", "unknown-model"):
+ table.price(model_id)
+ assert len(parsed) == built
diff --git a/tests/test_model_hub_usage.py b/tests/test_model_hub_usage.py
index 13a4b80a7..d3f60201c 100644
--- a/tests/test_model_hub_usage.py
+++ b/tests/test_model_hub_usage.py
@@ -37,6 +37,7 @@ from core.handlers.model_hub.identifiers import (
persisted_ledger_key,
usage_ledger_key,
)
+from core.handlers.model_hub.pricing import PriceTable
from core.handlers.model_hub.stream_wire import (
PROTOCOL_STREAM_TAXONOMY,
USAGE_REPORT_TOKEN_CEILING,
@@ -745,6 +746,49 @@ def test_usage_writer_preserves_daily_owners_inside_one_utc_hour(
time.tzset()
+def test_the_writer_reads_the_price_table_before_serving_and_tiers_every_call_at_record(
+ tmp_path: Path,
+) -> None:
+ """MH-USAGE-BACKEND-010: the writer reads the price table once when built, before the loop serves.
+
+ A price table parses the whole models.dev copy, so it is read when Model Hub's
+ service is built at controller startup, never on the loop and never per call.
+ Every call is then tiered when it is recorded, the first one included, and
+ calls of one tier fold together.
+ """
+
+ catalog = {"openai": {"models": {"gpt-6-astra": {"cost": {
+ "input": 10, "output": 50,
+ "tiers": [{"input": 20, "output": 75, "tier": {"type": "context", "size": 272_000}}],
+ }}}}}
+ vendor_map = {"families": [{"prefix": "gpt-", "vendor_id": "openai"}]}
+ reads: list[bool] = []
+
+ def price_table() -> PriceTable:
+ try:
+ asyncio.get_running_loop()
+ reads.append(True)
+ except RuntimeError:
+ reads.append(False)
+ return PriceTable(catalog=catalog, vendor_map=vendor_map, overrides={}, price_table_date="2026-10-13")
+
+ writer = UsageWriter(_ledger(tmp_path), price_table=price_table)
+ assert reads == [False]
+
+ async def exercise() -> None:
+ for input_tokens in (100_000, 300_000, 100_000, 300_000, 300_000):
+ writer.record(
+ source_id="src_a", model_id="gpt-6-astra", usage=ProtocolUsageReport(input_tokens=input_tokens), at=NOW,
+ )
+ assert len(writer._pending) == 2
+ assert await writer.drain(timeout=5) == 0
+
+ asyncio.run(exercise())
+ assert reads == [False]
+ rows = json.loads(_ledger(tmp_path).path.read_text(encoding="utf-8"))
+ assert [(row.get("context_tier", 0), row["requests"]) for row in rows] == [(0, 2), (272_000, 3)]
+
+
@pytest.mark.parametrize(
("capture_zone", "flush_zone", "switch_between_calls", "expected_days"),
[
@@ -3088,6 +3132,45 @@ def test_a_row_with_unusable_counters_loads_as_zero(tmp_path: Path) -> None:
assert row["output_tokens"] == 0
+ ("context_tier", "kept"),
+ [
+ pytest.param(0, True, id="base-spelled-out"),
+ pytest.param(272_000, True, id="tier"),
+ pytest.param(-1, False, id="negative"),
+ pytest.param(True, False, id="bool"),
+ pytest.param(1.5, False, id="float"),
+ pytest.param("272000", False, id="text"),
+ pytest.param(None, False, id="null"),
+ ],
+)
+def test_a_row_whose_context_tier_is_not_a_size_is_dropped(
+ tmp_path: Path, context_tier: object, kept: bool,
+) -> None:
+ """MH-USAGE-BACKEND-009: the context tier is part of a row's identity, so an unreadable one drops its row."""
+
+ ledger = _ledger(tmp_path)
+ ledger.path.parent.mkdir(parents=True, exist_ok=True)
+ row = {
+ "day": local_usage_day(NOW).isoformat(),
+ "source_id": "src_a",
+ "model_id": "model-x",
+ "requests": 1,
+ "token_reports": 0,
+ "input_tokens": 0,
+ "cached_input_tokens": 0,
+ "output_tokens": 0,
+ "last_metered_at": NOW.isoformat(),
+ }
+ ledger.path.write_text(
+ json.dumps([{**row, "model_id": "model-y"}, {**row, "context_tier": context_tier}]),
+ encoding="utf-8",
+ )
+
+ held = {row["model_id"]: row.get("context_tier", 0) for row in ledger.window(days=30, now=NOW)}
+ assert held == ({"model-x": context_tier, "model-y": 0} if kept else {"model-y": 0})
+
+
@pytest.mark.parametrize(
"persisted",
[