HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
fix(gateway): an unpriced table must not look like a free run
richard-epsillaf02fbd05792a
diff --git a/gateway/app.py b/gateway/app.pyindex 6097ba5a..76bd87ae 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -126,23 +126,51 @@ def _report_usage(org: str, metric: str, amount: float) -> None:# amount — and the AUTHORITATIVE charge still flows through the harvest's own priced consume._pricing_table: dict[str, dict[str, float]] = {}_pricing_fetched_at = 0.0+_pricing_warned = False # so a persistent failure warns once, not once per refresh_PRICING_TTL_S = 300.0async def _refresh_pricing_table() -> None:- global _pricing_table, _pricing_fetched_at+ """Load credits-per-unit prices, and SAY SO when it does not work.++ An unpriced table is indistinguishable from a free run: every _price_of() answers 0.0, the+ console shows 0 credits for every session, and nothing anywhere looks broken. That is exactly+ how this hid for months on the hosted deployment — the price endpoint was refusing with 403+ (its ingress is IP-locked and the gateway was not on the allowlist), the refusal was swallowed+ as "keep the stale table", and the table it was keeping had never been populated once.++ So: no pricing configured is silent, because that is a real and normal self-hosted state.+ Configured-but-not-working is LOUD, once per failure transition rather than every refresh.+ A 200 carrying an empty table counts as not working — accepting it would cache emptiness for+ the whole TTL and make a broken deployment look like a free one."""+ global _pricing_table, _pricing_fetched_at, _pricing_warnedif not ENGINE_URL or not BILLING_INTERNAL_KEY:- return+ return # billing not wired: prices are genuinely unset, not missingif time.time() - _pricing_fetched_at < _PRICING_TTL_S and _pricing_table:return+ why = ""try:r = await _client().get(f"{ENGINE_URL}/v1/billing/pricing/table",headers={"x-internal-key": BILLING_INTERNAL_KEY}, timeout=10)- if r.status_code < 400:- _pricing_table = (r.json() or {}).get("table") or {}- _pricing_fetched_at = time.time()- except Exception: # noqa: BLE001 — keep the stale table; credits are advisory, not the charge- pass+ if r.status_code >= 400:+ why = f"HTTP {r.status_code}"+ else:+ table = (r.json() or {}).get("table") or {}+ if table:+ _pricing_table = table+ _pricing_fetched_at = time.time()+ if _pricing_warned: # recovered — say that too, so the log has both edges+ print("[pricing] price table loaded; credit figures are real again", flush=True)+ _pricing_warned = False+ else:+ why = "the response carried no table"+ except Exception as e: # noqa: BLE001 — a refresh must never take a turn down with it+ why = f"{type(e).__name__}: {str(e)[:120]}"+ if why and not _pricing_warned:+ _pricing_warned = True+ print(f"[pricing] WARNING: could not load the price table ({why}). Every credit figure "+ f"will read 0 until this is fixed — that is a missing price list, NOT a free run.",+ flush=True)def _price_of(metric: str) -> float:diff --git a/gateway/tests/test_pricing_visibility.py b/gateway/tests/test_pricing_visibility.pynew file mode 100644index 00000000..877e18bb--- /dev/null+++ b/gateway/tests/test_pricing_visibility.py@@ -0,0 +1,85 @@+"""An unpriced table must never look like a free run.++On the hosted deployment the price endpoint refused with 403 for months. The refusal was swallowed+as "keep the stale table", the table had never been populated, every _price_of() answered 0.0, and+the console showed 0 credits per session while the harvest billed the real amount. Nothing looked+broken anywhere. These pin the three states apart.+"""+import pathlib+import sys++import pytest++sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))+import app as A # noqa: E402+++class _Resp:+ def __init__(self, status, payload=None):+ self.status_code = status+ self._payload = payload or {}++ def json(self):+ return self._payload+++def _arrange(monkeypatch, resp=None, boom=None):+ monkeypatch.setattr(A, "ENGINE_URL", "https://engine.example", raising=False)+ monkeypatch.setattr(A, "BILLING_INTERNAL_KEY", "k", raising=False)+ monkeypatch.setattr(A, "_pricing_table", {}, raising=False)+ monkeypatch.setattr(A, "_pricing_fetched_at", 0.0, raising=False)+ monkeypatch.setattr(A, "_pricing_warned", False, raising=False)++ class _Client:+ async def get(self, *_a, **_k):+ if boom:+ raise boom+ return resp++ monkeypatch.setattr(A, "_client", lambda: _Client())+++async def test_a_refusal_is_reported_not_swallowed(monkeypatch, capsys):+ _arrange(monkeypatch, resp=_Resp(403))+ await A._refresh_pricing_table()+ out = capsys.readouterr().out+ assert "could not load the price table" in out and "403" in out+ assert "NOT a free run" in out+++async def test_a_200_with_no_table_counts_as_a_failure(monkeypatch, capsys):+ """Caching an empty table would hold emptiness for the whole TTL and make a broken+ deployment indistinguishable from a free one."""+ _arrange(monkeypatch, resp=_Resp(200, {"table": {}}))+ await A._refresh_pricing_table()+ assert "could not load the price table" in capsys.readouterr().out+ assert A._pricing_fetched_at == 0.0, "an empty table must not be cached as valid"+++async def test_it_warns_once_not_every_refresh(monkeypatch, capsys):+ _arrange(monkeypatch, resp=_Resp(403))+ await A._refresh_pricing_table()+ capsys.readouterr()+ await A._refresh_pricing_table()+ assert "could not load" not in capsys.readouterr().out+++async def test_billing_not_wired_stays_silent(monkeypatch, capsys):+ """A self-hosted instance with no billing configured is a normal state, not a fault."""+ monkeypatch.setattr(A, "ENGINE_URL", "", raising=False)+ monkeypatch.setattr(A, "BILLING_INTERNAL_KEY", "", raising=False)+ await A._refresh_pricing_table()+ assert capsys.readouterr().out == ""+++async def test_a_real_table_loads_and_recovery_is_announced(monkeypatch, capsys):+ _arrange(monkeypatch, resp=_Resp(200, {"table": {"system": {"tokens": 1.5}}}))+ monkeypatch.setattr(A, "_pricing_warned", True, raising=False)+ await A._refresh_pricing_table()+ assert A._price_of("tokens") == 1.5+ assert "real again" in capsys.readouterr().out