Files
ai-agent/backend/test_pricing_cutover.py
Gabriel VidalandClaude Opus 5.5 d969112d92 feat(pricing): cut pricing, the parser's UsageMeter, project costs and the usage service over to ProviderRegistry (Wave 3B)
- conversations/pricing.py holds no table any more (MODEL_PRICES, FAMILY_FALLBACK,
  FAST_MULT, HAIKU_LONG, OPENAI_*, GEMINI_*, OTHER_PRICES, LOCAL_WATTS,
  ELECTRICITY_EUR_PER_KWH, EVOX2_*, PLAN_METER_AS, PLAN_FABLE_WEIGHT gone): a
  facade over the provider plugins' registry, same names and signatures;
  PRICE_BOOK / USD_PER_EUR / LOCAL_* derived lazily from the plugins;
  book_key() replaces openai_model / gemini_model; price_call() exposed.
- plugins/seed_registry.py: effective() = the bound store's registry when it
  has ever known a provider (strict plugin-only), else the default plugins
  read from PLUGINS_SEED_DIR / the plugins checkout / fixtures — offline
  parses, scripts and unit tests price with zero setup, no network.
- parser: each API call priced once through ProviderRegistry.price_call
  (UsageMeter.price) — list cost, cache share and the EVOX2's time from the
  CallCost, plan units passed apart into the meter; priceBook = price_book().
- projects/costs.py: rates + local outputWeight from provider-evox2's pricing.
- usage/service.remote_snapshots: one loop over the providers with a
  usageReader, GET /usage/{vendor} on the lab and online workers, the legacy
  /claude|opencode|agy/usage only on a 404 (or the lab not answering);
  per-vendor merge policies keep the exact old results.
- providers.py: per-id memo of the claiming pricer and the token-table key
  (fixed per registry) — the parse prices at the old speed.
- plugins/metering.py reads USD_PER_EUR at use time.

A/B: scripts/ab/pricing-dump.py --base 1e431f52 → identical (10104 lines);
scripts/ab/parse-ab.py --base 1e431f52 --chunked → 499 files × 2 modes,
0 differing; chunked == one-shot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 16:41:01 +01:00

227 lines
9.7 KiB
Python

"""Wave 3B: ``conversations/pricing.py`` is a facade over the providers'
registry (no price table left in core), the parser prices each call through
``ProviderRegistry.price_call``, and the usage service reads every vendor's
plan usage through the generic ``GET /usage/{vendor}``.
- with no plugin store bound, pricing reads the seed dir (offline scripts,
unit tests) — never zero;
- with a store bound that knows a provider, only that store's plugins count
(strict: an edited price shows, the seed's doesn't);
- a store that never held a provider (a fresh test store) still prices from
the seed;
- the derived constants (``PRICE_BOOK``, ``USD_PER_EUR``…) come from the
plugins;
- a worker still on an older sidecar (a 404 on ``/usage/{vendor}``) is read
on its legacy route.
"""
from __future__ import annotations
import json
import os
import pathlib
import shutil
import tempfile
import unittest
from unittest import mock
TMP = pathlib.Path(tempfile.mkdtemp())
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t", "WORKSPACE": TMP, "REPO_DIR": TMP,
"META_PATH": TMP / "meta.json", "PLUGINS_DIR": TMP / "plugins", "SIDECAR_TOKEN": "",
"OPENROUTER_CACHE_PATH": TMP / "openrouter-models.json"}.items():
os.environ.setdefault(k, str(v))
os.environ["PROVIDERS_DISCOVERY"] = "0"
from fastapi import HTTPException # noqa: E402
from conversations import pricing # noqa: E402
from plugins import providers, seed_registry # noqa: E402
from plugins.store import OWNER_UID, PluginStore # noqa: E402
FIX = pathlib.Path(__file__).resolve().parent / "fixtures" / "typed_plugins"
USAGE = pricing.norm_usage({"input_tokens": 1200, "output_tokens": 350,
"cache_read_input_tokens": 40_000,
"cache_creation_input_tokens": 3_000})
class _Deps:
def __init__(self, store):
self.plugin_store = store
def _store(edit=None, ids=None) -> PluginStore:
td = pathlib.Path(tempfile.mkdtemp())
store = PluginStore(td / "plugins")
for pid in ids if ids is not None else sorted(p.name for p in FIX.iterdir() if p.is_dir()):
d = td / "src" / pid
shutil.copytree(FIX / pid, d)
if edit and pid in edit:
mf = json.loads((d / "plugin.json").read_text())
edit[pid](mf)
(d / "plugin.json").write_text(json.dumps(mf))
store.install(OWNER_UID, str(d), is_owner=True, approve=True)
return store
class Base(unittest.TestCase):
def setUp(self):
self._bound = providers._bound
self._env = os.environ.get("PLUGINS_SEED_DIR")
os.environ["PLUGINS_SEED_DIR"] = str(FIX)
seed_registry.reset()
providers._bound = None
providers._snapshot_mem.clear()
def tearDown(self):
providers._bound = self._bound
if self._env is None:
os.environ.pop("PLUGINS_SEED_DIR", None)
else:
os.environ["PLUGINS_SEED_DIR"] = self._env
seed_registry.reset()
class TestSeedFallback(Base):
def test_no_store_reads_the_seed_dir(self):
self.assertIs(pricing.registry(), seed_registry.seed())
self.assertEqual(pricing.rates_for("claude-opus-5-5"), (4.0, 20.0, 0.2))
self.assertEqual(pricing.rates_for("gpt-5.5-fast"), (12.5, 75.0, 1.25))
self.assertEqual(pricing.rates_for("gemini-4-neon-high"), (3.0, 15.0, 0.15))
self.assertEqual(pricing.rates_for("inkling-2-mini"), (0.0, 0.0, 0.0))
self.assertGreater(pricing.usage_cost(USAGE, "claude-opus-5-5"), 0)
def test_built_once(self):
self.assertIs(seed_registry.seed(), seed_registry.seed())
def test_store_without_providers_reads_the_seed(self):
providers.bind(_Deps(_store(ids=[])))
self.assertIs(pricing.registry(), seed_registry.seed())
self.assertEqual(pricing.rates_for("claude-opus-5-5"), (4.0, 20.0, 0.2))
def test_seed_never_reaches_the_network(self):
reg = seed_registry.seed()
disc = reg.providers["anthropic"].spec.get("discovery") or {}
self.assertNotEqual(disc.get("kind"), "anthropic_models")
class TestStrict(Base):
def test_a_bound_store_is_the_only_source(self):
def cheaper(mf):
mf["provider"]["pricing"]["models"]["claude-opus-5-5"] = [1.0, 2.0, 0.1]
store = _store(edit={"provider-anthropic": cheaper})
providers.bind(_Deps(store))
self.assertIs(pricing.registry(), providers.registry(store))
self.assertEqual(pricing.rates_for("claude-opus-5-5"), (1.0, 2.0, 0.1))
def test_a_disabled_provider_prices_its_history_from_the_snapshot(self):
store = _store()
providers.bind(_Deps(store))
before = pricing.usage_cost(USAGE, "gpt-6-sol-fast")
store.update(OWNER_UID, "provider-openai", enabled=False)
self.assertNotIn("openai", pricing.registry().providers)
self.assertEqual(pricing.usage_cost(USAGE, "gpt-6-sol-fast"), before)
class TestDerived(Base):
def test_constants_come_from_the_plugins(self):
self.assertEqual(pricing.PRICE_BOOK, "2026-11-22")
self.assertEqual(pricing.price_book(), "2026-11-22")
self.assertEqual(pricing.USD_PER_EUR, 1 / 0.92)
self.assertEqual(pricing.LOCAL_CALL_CAP_S, 3600)
self.assertEqual(pricing.LOCAL_WATTS_DEFAULT, 112.0)
self.assertEqual(pricing.LOCAL_OUTPUT_WEIGHT, 16)
self.assertEqual(pricing.local_watts("evox2-inkling/inkling-2-mini"), 111.0)
self.assertEqual(pricing.electricity_eur_per_kwh("2026-09-01"), 0.2001)
self.assertEqual(pricing.hardware_eur_per_hour(), 2049.0 / (5 * 613.0))
with self.assertRaises(AttributeError):
pricing.MODEL_PRICES # noqa: B018 — the tables are gone
def test_book_key(self):
self.assertEqual(pricing.book_key("gpt-6.2-sol-fast"), ("openai", "gpt-6.1-sol", "fast"))
self.assertEqual(pricing.book_key("claude-haiku-4-5-20251001"),
("anthropic", "claude-haiku-4-5", None))
self.assertIsNone(pricing.book_key("openai/gpt-5.5"))
self.assertIsNone(pricing.book_key("inkling-2-mini"))
def test_price_call_keeps_cost_and_plan_units_apart(self):
cc = pricing.price_call("claude-opus-5-5", USAGE, speed="fast")
self.assertEqual(cc.cost, pricing.usage_cost(USAGE, "claude-opus-5-5", "fast"))
self.assertEqual(cc.plan_units, pricing.plan_units(USAGE, "claude-opus-5-5", "fast"))
self.assertNotEqual(cc.cost, cc.plan_units) # Opus 5.5 is metered as Opus 5
local = pricing.price_call("inkling-2-mini", USAGE, elapsed_ms=60_000, at="2026-11-26")
self.assertEqual(local.source, "local")
self.assertEqual(local.plan_units, 0.0)
class TestRemoteSnapshots(Base):
def _deps(self, workers):
class Store:
def list(self):
return workers
def online(self, wid):
return True
class Health:
def host_accounts(self):
return set()
class D:
worker_store = Store()
account_health = Health()
return D()
def test_generic_route_then_legacy_on_404(self):
from usage import service
asked = []
body = {"accounts": {"chatgpt-work": {"rate_limits": {"seven_day": {"used_percentage": 7}}}}}
def worker_get(url, token, path, *a, **k):
asked.append((url, path))
if url == "http://old" and path.startswith("/usage/"):
raise HTTPException(404, {"message": "not found"})
return body
workers = [{"id": "new", "url": "http://new", "token": "t", "opencodeAccounts": ["chatgpt-work"]},
{"id": "old", "url": "http://old", "token": "t", "opencodeAccounts": ["chatgpt-work"]}]
with mock.patch("runs.sidecar_client._sidecar_get", return_value=None), \
mock.patch("workers.store.sidecar_request", side_effect=worker_get):
got = service.remote_snapshots(self._deps(workers))
self.assertEqual(got, body["accounts"])
self.assertEqual(asked, [("http://new", "/usage/openai"),
("http://old", "/usage/openai"), ("http://old", "/opencode/usage")])
def test_other_errors_never_fall_back(self):
from usage import service
asked = []
def worker_get(url, token, path, *a, **k):
asked.append(path)
raise HTTPException(502, {"message": "worker offline"})
workers = [{"id": "w", "url": "http://w", "token": "t", "opencodeAccounts": ["chatgpt-work"]}]
with mock.patch("runs.sidecar_client._sidecar_get", return_value=None), \
mock.patch("workers.store.sidecar_request", side_effect=worker_get):
self.assertEqual(service.remote_snapshots(self._deps(workers)), {})
self.assertEqual(asked, ["/usage/openai"])
def test_lab_falls_back_to_the_legacy_route(self):
from usage import service
asked = []
guest = {"rate_limits": {"five_hour": {"used_percentage": 3}}}
def lab_get(path, timeout=25):
asked.append(path)
return {"accounts": {"guest-akira": guest}} if path == "/claude/usage" else None
with mock.patch("runs.sidecar_client._sidecar_get", side_effect=lab_get), \
mock.patch("workers.store.sidecar_request", side_effect=AssertionError):
got = service.remote_snapshots(self._deps([]))
self.assertEqual(got, {"guest-akira": guest})
self.assertEqual(asked[:2], ["/usage/anthropic", "/claude/usage"])
def test_vendors_are_the_providers_with_a_usage_reader(self):
from usage import service
self.assertEqual(service._usage_vendors(), ["anthropic", "openai", "google"])
if __name__ == "__main__":
unittest.main()