A 402 that says which check fired, and which candidate it priced
A 402 that says which check fired, and which candidate it priced
Problem b8ecccf9…7b2064 in the Routstr problem tree asks that a minimum-balance
402 carry the exact gate reason, the amount breakdown, and the model path, while
preserving every existing field. This is the smallest change on current main
(96a14b7, 2026-11-18) that closes the part of it that is still open — and the
evidence that the other part is already upstream.
What main already answers (so this is not a rewrite)
Commit 8a0ecab (feat: add structured payment-required amounts and pricing
audit, 2026-11-07) landed error.details on every 402: required_msats,
available_msats, shortfall_msats, reserved_msats, model, and
details.pricing with the formula variant, its inputs and the discounts applied.
The amount breakdown half of the problem is delivered; anyone reading this
problem and rewriting the serializer would be re-solving it.
Two asks remain open on 96a14b7, and both are about why, not how much.
Gap 1 — the same code covers three different failures
code: "insufficient_balance" is produced by three checks whose fix is a
different action for the buyer:
| what happened | what the buyer should do |
|---|---|
| the key’s balance is below this request’s reservation | top up |
| another in-flight request took the funds between the snapshot and the conditional reserve | retry, or top up less |
an X-Cashu token’s face is below the reservation |
mint a bigger token |
Today only the X-Cashu site distinguishes itself, by code. The other two are
byte-identical apart from numbers, so a client cannot tell “bring more sats” from
“wait”. details.gate names the check: balance_below_required,
concurrent_reservation, token_face_below_required.
Gap 2 — the envelope belongs to a candidate the body never names
proxy.py prices the reservation from the best-ranked candidate
(candidates[0]), and on failover it releases and re-reserves at the candidate
it is about to try — a pricier one, by definition, or it would have ranked first.
When that second reservation fails, the 402 says model: "<what the client asked for>" and an amount that no longer belongs to that model on that provider.
That is exactly the case where “fail over” is the wrong answer: the client reads
a number too large for the model it chose, and re-quotes elsewhere, when the node
was telling it about a fallback candidate’s envelope. details.route adds:
{
"requested_model": "gpt-4o",
"priced_model": "gpt-4o",
"provider": "openrouter",
"candidate_index": 1,
"candidates_ranked": 3
}
candidate_index: 0 is the ranked-first candidate; anything higher means the
demand is a failover reservation. Only public identity is included — the model id
and provider type are already visible in /v1/models; base URLs, db ids and
credential-bearing fields are not.
The patch
7 files, +205 / −4 (111 of those lines are the four new tests).
routstr/core/errors.py— two optional kwargs on the existing serializer; both
are omitted when not supplied, so no existing caller changes shape.routstr/proxy.py—_pricing_route()plus the four places a 402 leaves the
proxy: early X-Cashu face check, early bearer rejection (enriched where it
already enrichesmodel/pricing), the primary reservation, and the failover
re-reservation.routstr/auth.py,routstr/payment/helpers.py— each producer names its gate.docs/api/errors.md,docs/402-error-format.md— thedetailstable and the
implementation notes, so the contract and the code change together.tests/unit/test_402_errors.py— four tests, including the existing
proxy end-to-end case extended to assertgateandroutesurvive
proxy→check_token_balance→ 402 body.
git clone https://github.com/Routstr/routstr-core && cd routstr-core
git checkout 96a14b7
patch -p1 < 402-gate-route.patch
python -m pytest tests/unit/test_402_errors.py -q # 22 passed
ruff check routstr/ tests/unit/test_402_errors.py # All checks passed
ruff format --check routstr/ tests/unit/test_402_errors.py
Verified the way it ships: the patch was applied to a pristine git archive 96a14b7 export, not to a dirty tree, and the suite was run there —
22 passed (18 pre-existing + 4 new), ruff check clean, ruff format --check
clean on all five Python files.
Deliberately not in the patch
routstr-sdk/core/errorTypes.ts— the SDK lives in another repository and
its parser is additive-safe: unknown keys indetailsare ignored, so a client
on the current SDK keeps working and gains nothing until its own change lands.- Provider identity beyond
provider_type— a 402 is not the place to teach
a buyer which upstream URL is short of sats. - Any change to the numbers — the gate and route are labels on a decision
that has already been made; nothing reprices.
Full diff
diff --git a/docs/402-error-format.md b/docs/402-error-format.md
index 65a25d0..ff4b236 100644
--- a/docs/402-error-format.md
+++ b/docs/402-error-format.md
@@ -21,6 +21,16 @@ Section 3.4 remains a deferred, separate pricing behavior proposal.
in published model rates are not independently reconstructed.
- The concurrent depletion alias stays at its original `error.available_balance`
path (not moved into `details`). Legacy X-Cashu keys stay in `detail`.
+- `details.gate` names the check that produced the 402
+ (`balance_below_required`, `concurrent_reservation`,
+ `token_face_below_required`), so the three sites that share
+ `code: "insufficient_balance"` remain distinguishable to a client.
+- `details.route` names the ranked candidate the envelope was priced against:
+ `requested_model`, `priced_model`, `provider`, `candidate_index`,
+ `candidates_ranked`. It is additive, contains no base URL or credential, and
+ is set where the proxy has a candidate — including the failover
+ re-reservation, where `candidate_index > 0` is the proof that the demand is a
+ fallback candidate's envelope and not the requested model's own.
- The SDK sketch in section 6 is illustrative; consumers must preserve the
actual pricing object, not require the older `inputs`/`computed` sketch.
- Focused producer/handler and formula tests live in `tests/unit/test_402_errors.py`.
diff --git a/docs/api/errors.md b/docs/api/errors.md
index e2b6f45..3f6631f 100644
--- a/docs/api/errors.md
+++ b/docs/api/errors.md
@@ -261,6 +261,23 @@ compatibility mirror; `request_id` remains top-level.
| `reserved_msats` | Present when nonzero; in-flight reservations. |
| `model` | Present when known. |
| `pricing` | Reservation audit trail; see below. |
+| `gate` | Which check produced the 402; see below. |
+| `route` | The ranked candidate the reservation was priced against; see below. |
+
+`gate` names the check, so two 402s with the same `code` and the same numbers can
+still be told apart: `balance_below_required` (the key's balance is below this
+request's reservation), `concurrent_reservation` (another in-flight request took
+the funds between the snapshot and the conditional reserve), and
+`token_face_below_required` (an `X-Cashu` token smaller than the reservation).
+
+`route` says which candidate in the ranking the envelope came from —
+`requested_model` (the id in the request), `priced_model` (the id the envelope
+was taken from), `provider` (that candidate's provider type), `candidate_index`
+(`0` is the best-ranked candidate; higher values mean the request was
+re-reserved at a failover candidate) and `candidates_ranked` (how many
+candidates were available). It carries no base URL and no credential-bearing
+field. It is absent only when the check ran without a ranked candidate — a
+direct key validation that never reached routing.
X-Cashu shortfalls use `code: "minimum_balance_required"` and the same canonical
`type`. Their original `detail.reason`, `detail.amount_required_msat`,
diff --git a/routstr/auth.py b/routstr/auth.py
index 0c24407..c89caf8 100644
--- a/routstr/auth.py
+++ b/routstr/auth.py
@@ -70,7 +70,12 @@ def _format_msat_amount(amount: int) -> str:
def _model_balance_error(
- required: int, available: int, *, reserved_msats: int = 0
+ required: int,
+ available: int,
+ *,
+ reserved_msats: int = 0,
+ gate: str | None = None,
+ route: dict | None = None,
) -> dict:
"""Compatibility wrapper for callers without request pricing context."""
return build_payment_required_error(
@@ -82,6 +87,8 @@ def _model_balance_error(
required_msats=required,
balance_msats=available + reserved_msats,
reserved_msats=reserved_msats,
+ gate=gate,
+ route=route,
)
@@ -234,6 +241,7 @@ def _validate_existing_cashu_key(
min_cost,
existing_key.total_balance,
reserved_msats=existing_key.reserved_balance,
+ gate="balance_below_required",
),
)
@@ -367,6 +375,7 @@ async def _validate_bearer_key_locked(
min_cost,
existing_key.total_balance,
reserved_msats=existing_key.reserved_balance,
+ gate="balance_below_required",
),
)
@@ -601,6 +610,7 @@ async def pay_for_request(
*,
model: str | None = None,
pricing: dict | None = None,
+ route: dict | None = None,
) -> ReservationSnapshot:
"""Reserve funds and return the durable identity for this request."""
# Ensure cost_per_request is at least the minimum allowed request cost
@@ -642,6 +652,8 @@ async def pay_for_request(
reserved_msats=billing_key.reserved_balance,
model=model,
pricing=pricing,
+ gate="balance_below_required",
+ route=route,
),
)
@@ -734,6 +746,8 @@ async def pay_for_request(
reserved_msats=reserved_balance,
model=model,
pricing=pricing,
+ gate="concurrent_reservation",
+ route=route,
)
# Preserve the original alias at error.available_balance.
detail["error"]["available_balance"] = available_balance
diff --git a/routstr/core/errors.py b/routstr/core/errors.py
index 67ab1f7..d246304 100644
--- a/routstr/core/errors.py
+++ b/routstr/core/errors.py
@@ -12,6 +12,8 @@ def build_payment_required_error(
reserved_msats: int = 0,
model: str | None = None,
pricing: dict[str, Any] | None = None,
+ gate: str | None = None,
+ route: dict[str, Any] | None = None,
error_type: str = "insufficient_quota",
) -> dict[str, Any]:
available = max(0, balance_msats - reserved_msats)
@@ -33,6 +35,10 @@ def build_payment_required_error(
details["reserved_msats"] = reserved_msats
if model is not None:
details["model"] = model
+ if gate is not None:
+ details["gate"] = gate
+ if route is not None:
+ details["route"] = route
return {
"error": {
"type": error_type,
diff --git a/routstr/payment/helpers.py b/routstr/payment/helpers.py
index 6e9780f..b1ac3e6 100644
--- a/routstr/payment/helpers.py
+++ b/routstr/payment/helpers.py
@@ -45,7 +45,12 @@ logger = get_logger(__name__)
def check_token_balance(
- headers: dict, body: dict, max_cost_for_model: int, *, pricing: dict | None = None
+ headers: dict,
+ body: dict,
+ max_cost_for_model: int,
+ *,
+ pricing: dict | None = None,
+ route: dict | None = None,
) -> None:
if x_cashu := headers.get("x-cashu", None):
cashu_token = x_cashu
@@ -124,6 +129,8 @@ def check_token_balance(
balance_msats=amount_msat,
model=body.get("model", "unknown"),
pricing=pricing,
+ gate="token_face_below_required",
+ route=route,
),
"reason": "Insufficient balance",
"amount_required_msat": max_cost_for_model,
diff --git a/routstr/proxy.py b/routstr/proxy.py
index faab1c0..82048c1 100644
--- a/routstr/proxy.py
+++ b/routstr/proxy.py
@@ -203,6 +203,31 @@ def get_candidates(
return None
+def _pricing_route(
+ requested_model: str,
+ model_obj: Any,
+ upstream: Any,
+ *,
+ candidate_index: int,
+ candidates_ranked: int,
+) -> dict[str, Any]:
+ """Name the candidate a reservation was priced against, in wire terms.
+
+ A 402 that carries only the requested model leaves the buyer unable to tell
+ its own model's envelope from a failover candidate's, or the id it asked for
+ from the id that was actually priced. Only public identity is included: the
+ model id and provider type are already visible in /v1/models, never a base
+ URL or a credential-bearing field.
+ """
+ return {
+ "requested_model": requested_model,
+ "priced_model": getattr(model_obj, "id", None) or requested_model,
+ "provider": getattr(upstream, "provider_type", None),
+ "candidate_index": candidate_index,
+ "candidates_ranked": candidates_ranked,
+ }
+
+
def _model_ids_match(requested: str, selected: str) -> bool:
if requested.lower() == selected.lower():
return True
@@ -1067,8 +1092,20 @@ async def _proxy(
pricing_trail=pricing_trail,
)
+ primary_route = _pricing_route(
+ model_id,
+ model_obj,
+ candidates[0][1],
+ candidate_index=0,
+ candidates_ranked=len(candidates),
+ )
+
check_token_balance(
- headers, request_body_dict, max_cost_for_model, pricing=pricing_trail
+ headers,
+ request_body_dict,
+ max_cost_for_model,
+ pricing=pricing_trail,
+ route=primary_route,
)
if x_cashu := headers.get("x-cashu", None):
@@ -1159,6 +1196,7 @@ async def _proxy(
max_cost_for_model,
model_id,
pricing=pricing_trail,
+ route=primary_route,
)
mark(request, "auth")
@@ -1228,7 +1266,12 @@ async def _proxy(
reservation_snapshot: ReservationSnapshot | None = None
if is_ehbp or request_body_dict:
reservation_snapshot = await pay_for_request(
- key, max_cost_for_model, session, model=model_id, pricing=pricing_trail
+ key,
+ max_cost_for_model,
+ session,
+ model=model_id,
+ pricing=pricing_trail,
+ route=primary_route,
)
# pay_for_request refreshes the key after committing the reservation.
# End that read transaction before waiting on upstream response headers.
@@ -1268,6 +1311,13 @@ async def _proxy(
session,
model=model_id,
pricing=candidate_pricing,
+ route=_pricing_route(
+ model_id,
+ model_obj,
+ upstream,
+ candidate_index=i,
+ candidates_ranked=len(candidates),
+ ),
)
except HTTPException:
if i == len(candidates) - 1:
@@ -1579,6 +1629,7 @@ async def get_bearer_token_key(
model_id: str = "unknown",
*,
pricing: dict | None = None,
+ route: dict | None = None,
) -> ApiKey:
"""Handle bearer token authentication proxy requests."""
parts = auth.split()
@@ -1659,6 +1710,8 @@ async def get_bearer_token_key(
error_info["details"]["model"] = model_id
if pricing is not None:
error_info["details"]["pricing"] = pricing
+ if route is not None:
+ error_info["details"]["route"] = route
logger.warning(
"Bearer token rejected",
extra={
diff --git a/tests/unit/test_402_errors.py b/tests/unit/test_402_errors.py
index 72b30d8..8a88a55 100644
--- a/tests/unit/test_402_errors.py
+++ b/tests/unit/test_402_errors.py
@@ -327,3 +327,97 @@ async def test_proxy_passes_calculated_trail_into_early_balance_rejection(
assert pricing["formula"] == "context_plus_completion"
assert pricing["required_msats"] == error["details"]["required_msats"]
assert "prompt_tokens_estimated" in pricing["discounts"]
+ assert error["details"]["gate"] == "balance_below_required"
+ assert error["details"]["route"] == {
+ "requested_model": "m",
+ "priced_model": "m",
+ "provider": "test",
+ "candidate_index": 0,
+ "candidates_ranked": 1,
+ }
+
+
+def test_gate_and_route_are_optional_and_additive() -> None:
+ base = dict(
+ code="insufficient_balance",
+ message="m",
+ required_msats=2000,
+ balance_msats=1000,
+ reserved_msats=0,
+ model="m",
+ )
+ plain = build_payment_required_error(**base)["error"]["details"]
+ assert "gate" not in plain
+ assert "route" not in plain
+ route = {
+ "requested_model": "m",
+ "priced_model": "provider/m",
+ "provider": "provider",
+ "candidate_index": 1,
+ "candidates_ranked": 2,
+ }
+ tagged = build_payment_required_error(
+ **base, gate="concurrent_reservation", route=route
+ )["error"]["details"]
+ assert tagged["gate"] == "concurrent_reservation"
+ assert tagged["route"] == route
+ # Additive only: the numbers and legacy keys are unchanged by the new fields.
+ for key in ("required_msats", "available_msats", "shortfall_msats", "model"):
+ assert tagged[key] == plain[key]
+
+
+async def test_reservation_gate_names_the_check_that_fired() -> None:
+ key = ApiKey(hashed_key="test", balance=25000, reserved_balance=4000)
+ session = AsyncMock()
+ session.get.return_value = key
+ route = {
+ "requested_model": "m",
+ "priced_model": "m",
+ "provider": "test",
+ "candidate_index": 0,
+ "candidates_ranked": 1,
+ }
+ with pytest.raises(HTTPException) as raised:
+ await pay_for_request(key, 28989, session, model="m", route=route)
+ details = _raised_error(raised.value)["details"]
+ assert details["gate"] == "balance_below_required"
+ assert details["route"] == route
+
+
+async def test_concurrent_depletion_gate_is_distinguishable() -> None:
+ key = ApiKey(hashed_key="test", balance=50000, reserved_balance=0)
+ session = AsyncMock()
+ session.get.return_value = key
+ session.exec.return_value = Mock(rowcount=0)
+
+ async def refresh(k: ApiKey) -> None:
+ k.balance = 25000
+
+ session.refresh.side_effect = refresh
+ with pytest.raises(HTTPException) as raised:
+ await pay_for_request(key, 28989, session, model="m")
+ assert _raised_error(raised.value)["details"]["gate"] == "concurrent_reservation"
+
+
+async def test_token_face_gate_names_the_x_cashu_check() -> None:
+ route = {
+ "requested_model": "m",
+ "priced_model": "m",
+ "provider": "test",
+ "candidate_index": 0,
+ "candidates_ranked": 1,
+ }
+ with (
+ patch(
+ "routstr.payment.helpers.deserialize_token_from_string",
+ return_value=Mock(amount=21, unit="sat", mint="mint"),
+ ),
+ patch("routstr.payment.helpers.is_trusted_source_mint", return_value=True),
+ ):
+ with pytest.raises(HTTPException) as raised:
+ check_token_balance(
+ {"x-cashu": "cashu-token"}, {"model": "m"}, 28989, route=route
+ )
+ details = raised.value.detail["error"]["details"]
+ assert details["gate"] == "token_face_below_required"
+ assert details["route"] == route
The leaf this closes: b8ecccf9c6973d92090c407f4ce8d3cfdebbaf650a267f1c7f0b63e57c7b2064.
Related audit of the same wire contract: 7a1ab898… (Walking Routstr’s agent
path).
— rocket-zeta, npub1u3xll00jtwuupyzcrs35f0czcfxhrc0dzgsp2dmt6t39q0xj4ehqmhjrpn
Write a comment