diff --git a/config/litellm/cost_callback.py b/config/litellm/cost_callback.py index 49c1c6637..6044e6e96 100644 --- a/config/litellm/cost_callback.py +++ b/config/litellm/cost_callback.py @@ -66,6 +66,20 @@ non-obvious properties (absent key == provider default; post-``drop_params``, so config-vs-wire divergence becomes visible). +Each line also carries ``endpoint``: which physical build served the turn +(issue #3692). ``provider`` is per-call, read off the response body; +``name`` / ``quantization`` / ``context_length`` come from OpenRouter's +per-model endpoints metadata, fetched off the request path and cached. The +metadata row is selected by matching the call's provider, never by position +— see the block comment above ``_BUILD_URL``. Three knobs, mirroring +``openrouter_capabilities``: ``LITELLM_OPENROUTER_ENDPOINT_FETCH=0`` +disables the lookup, ``LITELLM_OPENROUTER_ENDPOINT_TTL`` (default 3600s) +sets how long a resolved list is trusted, and +``LITELLM_OPENROUTER_ENDPOINT_TIMEOUT`` (default 5s) the HTTP timeout. A +failed lookup is cached for a much shorter fixed interval and is reported +in the proxy log, so persistently-null fields are diagnosable rather than +indistinguishable from "the first fetch has not landed yet". + Each line additionally carries ``pipeline_id`` / ``agent_role`` / ``phase`` read from the gateway-stamped ``x-egg-*`` request headers (issue #3175), so per-role spend is a log query instead of a hand cross-reference against @@ -100,7 +114,11 @@ import datetime import json import math +import os import threading +import time +import urllib.parse +import urllib.request from litellm.integrations.custom_logger import CustomLogger @@ -110,20 +128,28 @@ # evicted). The single replica + tiny per-entry footprint make pressure # unlikely, but the pod was recently OOMKilled into a 1->2Gi bump, so we cap # defensively and drop the least-recently-updated session first. +# +# Values are float counters, except ``last_prompt_tokens``, which is a +# per-model map (see the prompt-delta comment in ``_record``) — hence the +# widened value type rather than ``dict[str, float]``. _MAX_SESSIONS = 4096 -_session_totals: collections.OrderedDict[str, dict[str, float]] = collections.OrderedDict() +_session_totals: collections.OrderedDict[str, dict[str, object]] = collections.OrderedDict() -def _raw_upstream_usage(mcd): - """Pull the upstream OpenRouter ``usage`` block out of - ``model_call_details['original_response']`` (the raw provider JSON). +def _original_response(mcd): + """Parse ``model_call_details['original_response']`` — the raw provider + JSON — exactly once per call. - Populated with full provider fidelity (cost, cost_details, cache - read/write counts) on the non-streaming path. For streaming, LiteLLM logs - only a type marker into ``original_response`` (see ``Logging.post_call``), - so this returns None and the caller falls back to the assembled response - object's usage. Returns the parsed ``usage`` dict, or None if anything's - missing / malformed.""" + Populated with full provider fidelity (top-level ``provider``, ``usage`` + with cost, cost_details, cache read/write counts) on the non-streaming + path. For streaming, LiteLLM logs only a type marker here (see + ``Logging.post_call``), so this returns None and the readers below fall + back to the assembled response object. + + Parsed here rather than inside each reader: the body is the whole upstream + response, and both ``_raw_upstream_usage`` and ``_extract_provider`` want a + field off it. Two ``json.loads`` of the same string per call, inside the + proxy's logging hook, is a cost nothing pays for.""" try: rr = (mcd or {}).get("original_response") if isinstance(rr, str): @@ -131,9 +157,21 @@ def _raw_upstream_usage(mcd): rr = json.loads(rr.strip()) except Exception: return None - if not isinstance(rr, dict): + return rr if isinstance(rr, dict) else None + except Exception: + return None + + +def _raw_upstream_usage(body): + """The upstream OpenRouter ``usage`` block off a parsed ``original_response``. + + Takes the already-parsed body from ``_original_response``. Returns the + ``usage`` dict, or None if anything's missing / malformed — in which case + the caller falls back to the assembled response object's usage.""" + try: + if not isinstance(body, dict): return None - usage = rr.get("usage") + usage = body.get("usage") return usage if isinstance(usage, dict) else None except Exception: return None @@ -366,6 +404,348 @@ def _extract_model(mcd): return None +def _extract_provider(body, response_obj): + """The UPSTREAM provider that actually served this turn, off the response. + + OpenRouter puts a top-level ``provider`` on the response ("Poolside", + "Alibaba", "DeepInfra"). It survives on the non-streaming path via + ``original_response``; on the streaming path we fall back to the assembled + object, which carries it only if litellm preserved the field across chunk + reassembly (it rebuilds a fresh ``ModelResponse`` from the fields it + enumerates, so ordinarily it does not). + + ``None`` means "we could not tell", consistent with the rest of this + module, and on the streaming path that is the honest and expected answer + today. What is deliberately NOT consulted is + ``_hidden_params['custom_llm_provider']``: that is litellm's *route* + provider — the literal string ``"openrouter"`` for every model egg + registers — not the upstream that served the turn. Reading it here would + make this field non-null on every streamed call while answering a + different question, so an operator filtering for + ``endpoint.provider == null`` to find "attribution isn't working" would + get zero rows and conclude it was. A confident wrong answer is worse than + the null.""" + try: + if isinstance(body, dict) and isinstance(body.get("provider"), str): + return body["provider"] + prov = getattr(response_obj, "provider", None) + if isinstance(prov, str) and prov.strip(): + return prov + except Exception: + pass + return None + + +# Build attribution (#3692). "Which build served this turn" is not answerable +# from the response body: it carries the provider NAME but not the endpoint's +# dated build id or its quantization, and two endpoints behind one provider can +# differ in both. Those live in OpenRouter's per-model endpoints metadata. +# +# Fetched at most once per model per TTL, on a daemon thread, and cached. Never +# on the request path: this runs in the proxy's logging hook, so a blocking +# lookup here would stall the event loop for every call. Until the first fetch +# resolves, the fields emit as null — "not yet known", which is the same +# unknown-is-not-zero discipline the cost fields follow. +# +# The metadata answers for a MODEL, not for a call, so selecting the right row +# out of it is the load-bearing part. `/models/{slug}/endpoints` is a public +# metadata route that takes no provider parameter: the `extra_body.provider` +# pin egg sends constrains which upstream the *completion* is routed to and has +# no effect whatsoever on this list or its order. So index 0 is whatever +# OpenRouter's default sort returns — for `z-ai/glm-4.6` that is a different +# provider, quantization AND context length than the one a pinned route +# actually talks to. We therefore match on `provider_name` against the provider +# read off this call's response, and emit nulls when no row matches. The one +# case where an unknown provider is still unambiguous is a model publishing +# exactly one endpoint: there is nothing else it could have been. +_BUILD_URL = "https://openrouter.ai/api/v1/models/{slug}/endpoints" + +# How long a resolved endpoint list is trusted. Builds are re-cut and endpoints +# are added/withdrawn on OpenRouter's schedule, not the pod's, and the proxy +# outlives both; a process-lifetime cache would report the build that was +# current when the pod started for as long as it runs. +DEFAULT_BUILD_TTL_SECONDS = 3600.0 + +# How long a FAILED lookup is trusted, deliberately far shorter. A failure has +# to be cached — otherwise a 404 slug fires an HTTP request per call — but +# caching it as durably as a success is what turns one DNS blip or one +# mis-spelled model alias into permanently null attribution with nothing +# anywhere saying why. +DEFAULT_BUILD_FAILURE_TTL_SECONDS = 300.0 + +DEFAULT_BUILD_TIMEOUT_SECONDS = 5.0 + +# slug -> (monotonic stamp, record). ``record`` is None for a failed lookup, +# which is a real state distinct from "absent" (never asked) and is what the +# shorter failure TTL applies to. A successful record is +# ``{"by_provider": {casefolded provider_name: build}, "sole": build | None}``, +# where ``sole`` is populated only when the model published exactly one +# endpoint. +_build_cache: dict[str, tuple[float, dict | None]] = {} +_build_pending: set[str] = set() +_build_lock = threading.Lock() + +# Slugs whose lookup failure has already been reported at warning level. The +# first failure is the one carrying information; repeats at this cadence would +# be one line per TTL forever. Cleared by a successful fetch, so a blip at +# startup does not permanently mute a real outage hours later. +_build_warned: set[str] = set() + +_TRUTHY = ("1", "true", "yes", "on") +_FALSY = ("0", "false", "no", "off") + + +def _log(level, message, *args): + """Log via litellm's ``verbose_logger``, deferring the import. + + Kept out of module scope so this file stays importable where litellm's + private logging module is not (the unit tests stub only + ``integrations.custom_logger``). Never raises: a diagnostic must not be + able to break a request. Returns whether the emit completed without + raising — see ``_log_build_failure`` for why the caller cares.""" + try: + from litellm._logging import verbose_logger + + getattr(verbose_logger, level)(message, *args) + return True + except Exception: + return False + + +def _log_build_failure(key, message, *args): + """First failure per ``key`` at warning, the rest at debug. + + Every failure path in the lookup below routes through here. Without it the + whole feature dies silently on an operator-side misconfiguration — a model + alias that is not a published slug 404s, and the operator sees ``"name": + null``, which is also what a lookup that simply has not landed yet looks + like. The two need to be distinguishable, and only the log can do it.""" + level = "debug" if key in _build_warned else "warning" + # Latched only once the emit did not raise: ``_log`` swallows its own + # failures, so marking "already warned" for a line nobody saw would demote + # every later failure to debug. + if _log(level, "cost_callback build attribution [%s]: " + message, key, *args): + _build_warned.add(key) + + +def _build_env_float(name, default): + """A positive float from the environment, or ``default``.""" + raw = os.environ.get(name) + if raw is None or not raw.strip(): + return default + try: + value = float(raw) + except (TypeError, ValueError): + _log_build_failure(name, "ignoring %s=%r: not a number; using %s", name, raw, default) + return default + if not math.isfinite(value) or value <= 0: + _log_build_failure(name, "ignoring %s=%r: not positive; using %s", name, raw, default) + return default + return value + + +def _build_fetch_enabled(): + """The operator kill switch, mirroring ``LITELLM_OPENROUTER_CAPABILITY_FETCH``. + + A near-miss spelling warns rather than being read as *enable*: silently + inverting a disable instruction is the one outcome a kill switch must not + have.""" + raw = (os.environ.get("LITELLM_OPENROUTER_ENDPOINT_FETCH") or "").strip().lower() + if not raw: + return True + if raw in _FALSY: + return False + if raw not in _TRUTHY: + _log_build_failure( + "LITELLM_OPENROUTER_ENDPOINT_FETCH", + "unrecognized value %r; leaving the lookup enabled", + raw, + ) + return True + + +def _upstream_slug(model): + """``openrouter/poolside/laguna-s-2.1`` -> ``poolside/laguna-s-2.1``. + + Also drops a trailing ``[...]`` context-window opt-in suffix. Claude Code + registers its custom model as ``qwen3-max[1m]`` and strips the suffix + client-side, but a handful of startup probes leak the suffixed name through + (see the paired-alias note in ``docs/guides/per-agent-models.md``), and + ``qwen3-max[1m]`` is not a published OpenRouter slug — it would 404 the + lookup for a name that denotes the same model. A ``:free``-style variant + suffix is deliberately NOT stripped: that names a different rate card and a + different endpoint set, so inheriting the base model's row would be exactly + the confident-wrong-answer this module refuses elsewhere.""" + if not isinstance(model, str) or not model: + return None + slug = model.split("/", 1)[1] if model.startswith("openrouter/") else model + head, sep, tail = slug.partition("[") + if sep and tail.endswith("]") and head: + slug = head + return slug or None + + +def _fetch_build_info(slug): + """Every endpoint OpenRouter publishes for ``slug``, keyed by provider name. + + ``None`` on any failure, and every failure path says so in the log first — + see ``_log_build_failure``.""" + if not _build_fetch_enabled(): + return None + timeout = _build_env_float("LITELLM_OPENROUTER_ENDPOINT_TIMEOUT", DEFAULT_BUILD_TIMEOUT_SECONDS) + url = _BUILD_URL.format(slug=urllib.parse.quote(slug, safe="/")) + try: + req = urllib.request.Request(url) + api_key = os.environ.get("OPENROUTER_API_KEY") + if api_key: + # ``add_unredirected_header``, not the ``headers=`` constructor + # argument. urllib's ``HTTPRedirectHandler.redirect_request`` + # copies every ordinary header onto the redirect target, cross-host + # included — ``requests`` strips ``Authorization`` there, urllib + # does not. Unredirected headers are sent on this request and + # dropped from any redirect, which is the behaviour a bearer token + # wants. openrouter.ai does not redirect this route today; this is + # the guard for the day it does, and for this being copied. + req.add_unredirected_header("Authorization", f"Bearer {api_key}") + with urllib.request.urlopen(req, timeout=timeout) as resp: + body = resp.read() + except Exception as exc: + _log_build_failure( + slug, "GET %s failed (%s: %s); endpoint fields stay null", url, type(exc).__name__, exc + ) + return None + try: + payload = json.loads(body) + except Exception: + _log_build_failure(slug, "GET %s returned a non-JSON body; endpoint fields stay null", url) + return None + return _parse_endpoints(slug, payload, url) + + +def _parse_endpoints(slug, payload, url): + """The published endpoints out of a decoded response body, keyed by provider. + + Split out from the transport so the shape handling is testable without a + socket, and so each way the body can disappoint us gets its own log line + rather than one ``except Exception`` standing in for all of them.""" + data = payload.get("data") if isinstance(payload, dict) else None + if not isinstance(data, dict): + _log_build_failure(slug, "GET %s returned no `data` object; endpoint fields stay null", url) + return None + endpoints = data.get("endpoints") + if not isinstance(endpoints, list) or not endpoints: + _log_build_failure(slug, "GET %s listed no endpoints; endpoint fields stay null", url) + return None + by_provider: dict[str, dict] = {} + parsed: list[dict] = [] + for endpoint in endpoints: + if not isinstance(endpoint, dict): + continue + # Recorded verbatim rather than parsed: the dated build id is inside + # the name string, and taking it apart here would make this module the + # thing that breaks when OpenRouter changes the format. + info = { + "name": endpoint.get("name"), + "quantization": endpoint.get("quantization"), + "context_length": endpoint.get("context_length"), + } + parsed.append(info) + name = endpoint.get("provider_name") + if isinstance(name, str) and name.strip(): + # First row wins for a repeated provider name. Two rows behind one + # name is not a shape OpenRouter publishes today, and picking + # between them by position would be the index-0 guess this + # function exists to remove. + by_provider.setdefault(name.strip().casefold(), info) + if not parsed: + _log_build_failure( + slug, "GET %s: no endpoint entry was parseable; endpoint fields stay null", url + ) + return None + # Re-arm the warning for this slug now that it has answered. + _build_warned.discard(slug) + return { + "by_provider": by_provider, + # Only a genuinely single-endpoint model gets the unambiguous fallback. + # ``len(parsed)`` alone would promote one survivor of a two-row list + # whose sibling failed to parse, which is a guess, not a certainty. + "sole": parsed[0] if len(endpoints) == 1 and len(parsed) == 1 else None, + } + + +def _select_build(record, provider): + """The endpoint row describing ``provider``, or None when it is not knowable.""" + if not isinstance(record, dict): + return None + if isinstance(provider, str) and provider.strip(): + hit = record.get("by_provider", {}).get(provider.strip().casefold()) + if isinstance(hit, dict): + return hit + # Either the provider is unknown (the streaming path, where the response + # body does not survive reassembly) or it names something not in the + # published list (a spelling drift). Both fall through to the single-row + # case, which is unambiguous regardless: a model with exactly one endpoint + # was served by that endpoint or by nothing. + sole = record.get("sole") + return sole if isinstance(sole, dict) else None + + +def _build_info(model, provider=None): + """Cached build identity for ``(model, provider)``; ``None`` when unknown. + + ``None`` covers all three ways this can have no answer, which the emitted + nulls do not distinguish and the log does: the first fetch has not landed, + the fetch failed, or the metadata has no row for this provider.""" + slug = _upstream_slug(model) + if not slug: + return None + # Gate the lookup on the credential the proxy is configured with. In the + # egg-litellm container it is always present (the route reads the same + # variable), so this is a no-op there; outside it — unit tests, an import + # of this module by tooling — it means we never reach for the network + # uninvited. Without it the logging hook of every test that exercises + # _record would fire a real HTTP request. + if not os.environ.get("OPENROUTER_API_KEY"): + return None + if not _build_fetch_enabled(): + return None + now = time.monotonic() + with _build_lock: + entry = _build_cache.get(slug) + if entry is not None: + stamp, record = entry + ttl = ( + _build_env_float("LITELLM_OPENROUTER_ENDPOINT_TTL", DEFAULT_BUILD_TTL_SECONDS) + if record is not None + else DEFAULT_BUILD_FAILURE_TTL_SECONDS + ) + if (now - stamp) < ttl: + return _select_build(record, provider) + if slug in _build_pending: + # A refresh is already in flight. Keep serving the record we have + # rather than reporting null for the duration of someone else's + # HTTP request — a stale build id is still the right answer far + # more often than no answer, and it becomes fresh the moment the + # in-flight fetch lands. + return _select_build(entry[1], provider) if entry else None + _build_pending.add(slug) + + def _work(): + info = _fetch_build_info(slug) + with _build_lock: + # Stamped on failure too, so an unreachable endpoint costs one + # attempt per failure TTL rather than one per call. + _build_cache[slug] = (time.monotonic(), info) + _build_pending.discard(slug) + + try: + threading.Thread(target=_work, name=f"build-info-{slug}", daemon=True).start() + except Exception: + with _build_lock: + _build_pending.discard(slug) + return _select_build(entry[1], provider) if entry else None + + # Decoding-relevant request parameters to record per call (#3599). # # An ALLOWLIST, not a dump of ``optional_params``: that dict also carries the @@ -400,8 +780,23 @@ def _extract_model(mcd): "reasoning", "thinking", "stream", + # Whether the model was *allowed* to call a tool on this turn. Small + # scalar ("auto"/"none"/"required") or a small object naming one tool, so + # unlike ``tools`` it is safe to record verbatim under the value cap. + "tool_choice", ) +# Key under which we record how many callable tools the request carried. +# ``tools`` itself stays off the allowlist above (a dozen-plus translated +# schemas per Claude Code request — the bloat the allowlist exists to avoid), +# but its *arity* is one integer and is the load-bearing part: tool presence +# is the strongest observed lever on whether this class of model reasons at +# all, and ``tools_count: 0`` vs ``tools_count: 14`` is the whole signal. +# Paired with ``tool_choice`` it distinguishes "no tools were offered" from +# "tools were offered but forbidden for this turn", which are different +# conditions that a bare presence flag would collapse. +_TOOLS_COUNT_KEY = "tools_count" + # Per-value size cap. Everything on the allowlist is normally a scalar or a # small object, but ``logit_bias`` / ``stop`` are client-supplied and # unbounded; one pathological request must not be able to blow up every log @@ -680,10 +1075,23 @@ def _extract_request_params(mcd): for key in _REQUEST_PARAM_KEYS: if key in params: out[key] = _bounded_param(params[key]) + # Arity only, never the schemas. Recorded from whichever depth LiteLLM + # left them at, and omitted entirely when the request carried no + # ``tools`` key at all — absent means "we could not tell", which is not + # the same claim as ``tools_count: 0`` ("no callable tools offered"). + tools = params.get("tools") extra = params.get("extra_body") + if not isinstance(tools, list) and isinstance(extra, dict): + tools = extra.get("tools") + if isinstance(tools, list): + out[_TOOLS_COUNT_KEY] = len(tools) if isinstance(extra, dict): leftover = {} for key, value in extra.items(): + # Never let the schemas through by the extra_body path either: + # the count above is the whole of what we want from them. + if key == "tools": + continue # LiteLLM's param mapper relocates knobs a provider doesn't # declare into extra_body rather than dropping them (e.g. # top_k on an OpenAI-shaped route), so the same knob lands at @@ -740,8 +1148,10 @@ def _record(self, mcd, response_obj): # Raw upstream JSON first (full provider fidelity: cost, # cost_details, cache_write counts) — the non-streaming path. For # streaming, original_response holds only a type marker, so fall - # back to the assembled response object's usage. - usage = _raw_upstream_usage(mcd) or _usage_from_response_obj(response_obj) + # back to the assembled response object's usage. Parsed once here + # and handed to both readers that want a field off it. + raw_body = _original_response(mcd) + usage = _raw_upstream_usage(raw_body) or _usage_from_response_obj(response_obj) cost = _extract_cost(usage) cost_estimated = _extract_estimated_cost(mcd) prompt, cached, cache_write, reasoning = _extract_cache_stats(usage) @@ -760,6 +1170,18 @@ def _record(self, mcd, response_obj): model = _extract_model(mcd) attribution = _extract_attribution(mcd) request_params = _extract_request_params(mcd) + provider = _extract_provider(raw_body, response_obj) + # The metadata row is selected BY the provider this call reported, + # not by position in OpenRouter's list — see the block comment on + # ``_BUILD_URL`` for why index 0 is a different endpoint than the + # one a pinned route talks to. + build = _build_info(model, provider) or {} + endpoint = { + "provider": provider, + "name": build.get("name"), + "quantization": build.get("quantization"), + "context_length": build.get("context_length"), + } with _lock: agg = _session_totals.get(sid) if agg is None: @@ -773,7 +1195,38 @@ def _record(self, mcd, response_obj): "cached_tokens": 0.0, "cache_write_tokens": 0.0, "reasoning_tokens": 0.0, + # model -> that model's last observed prompt length. + "last_prompt_tokens": {}, } + # Growth of the prompt between consecutive calls of the same + # session AND MODEL (#3595). A repetition-trapped agent + # re-sends its whole context plus one near-identical turn, so + # this lands on a small, near-constant value call after call — + # the livelock signature, visible on a single line instead of + # requiring the whole session's lines to be diffed against each + # other. Only the retrospective version needs that + # reconstruction, and it is impossible once the ~48h log + # retention has rolled. + # + # Keyed per model, unlike the cost totals above: summing spend + # across the models a session touched is meaningful, but + # differencing prompt LENGTH across them is not. Claude Code's + # paired ``[1m]`` alias puts short startup probes on the + # same session id as the main calls, and a session-wide key + # would inject a large negative delta followed by a large + # positive one into the exact signal this field carries. The + # map is bounded by the operator-registered model roster. + # + # ``None`` on a session's first observed call for a model: + # there is no predecessor to difference against, which is not a + # delta of 0. + last_prompts = agg.get("last_prompt_tokens") + if not isinstance(last_prompts, dict): + last_prompts = {} + agg["last_prompt_tokens"] = last_prompts + prev_prompt = last_prompts.get(model or "") + prompt_delta = None if prev_prompt is None else int(prompt - prev_prompt) + last_prompts[model or ""] = prompt if cost is not None: agg["cost"] += cost agg["cost_known_calls"] += 1 @@ -850,10 +1303,16 @@ def _record(self, mcd, response_obj): # request ran at the model's own reasoning depth, not that # the field failed to record. "request_params": request_params, + # Which physical build served the turn (#3692). ``provider`` + # is per-call off the response; ``name`` / ``quantization`` + # / ``context_length`` are per-model and cached, so they + # read null on the calls before the first lookup resolves. + "endpoint": endpoint, "call": { "cost": cost, "cost_estimated": cost_estimated, "prompt_tokens": int(prompt), + "prompt_tokens_delta": prompt_delta, "cached_tokens": int(cached), "cache_write_tokens": int(cache_write), "reasoning_tokens": int(reasoning), diff --git a/docs/guides/per-agent-models.md b/docs/guides/per-agent-models.md index f70e04757..ab37b6085 100644 --- a/docs/guides/per-agent-models.md +++ b/docs/guides/per-agent-models.md @@ -788,8 +788,57 @@ data: > first, so a `` on a *small* field means the block was > over budget rather than that field being oversized on its own. > -> Prompt-bearing fields (`messages`, `tools`, `tool_choice`) are excluded by -> allowlist: the cost stream is not a transcript sink. +> Prompt-bearing fields (`messages`, and the `tools` schemas themselves) are +> excluded by allowlist: the cost stream is not a transcript sink. The line +> the allowlist draws is payload vs selector, not "anything tool-shaped", so +> two small tool-related values *are* recorded (#3692): `tools_count`, the +> arity of the `tools` array without any of its schemas — tool presence is +> the strongest observed lever on whether these models reason, so `0` vs `14` +> is the whole signal — and `tool_choice`, the scalar mode selector +> (`"auto"` / `"none"` / `"required"`, or a small object naming one tool), +> which separates "no tools were offered" from "tools were offered but +> forbidden this turn". An **absent** `tools` key emits no `tools_count` at +> all rather than `0`: "we could not tell" is not "none offered". + +> **Which build served the turn, and did the prompt stop growing?** Two more +> fields land next to `request_params` on every `cost_callback` line (#3692). +> +> - **`endpoint`** — `{provider, name, quantization, context_length}`. +> `provider` is per-call, read off the response body ("Poolside", +> "Alibaba"); the other three come from OpenRouter's per-model +> `/models/{slug}/endpoints` metadata, fetched off the request path (a +> daemon thread, cached for an hour) because this code runs in the proxy's +> logging hook and a blocking lookup there would stall the event loop for +> every call. The metadata row is selected by **matching the call's +> provider**, never by position: the `extra_body.provider` pin routes the +> *completion* and has no effect on that public metadata route, whose index +> 0 is frequently a provider you never talked to (`z-ai/glm-4.6` lists +> Venice first at `fp4`/198000 while Z.AI serves `fp8`/202752). A provider +> with no published row reads `null` rather than borrowing a neighbour's +> build id. On the streaming path — all agent traffic — the response's +> provider usually does not survive litellm's chunk reassembly, so +> `provider` reads `null` and the build fields resolve only for a model +> publishing exactly one endpoint, where there is nothing to disambiguate. +> Knobs: `LITELLM_OPENROUTER_ENDPOINT_FETCH=0` disables the lookup, +> `LITELLM_OPENROUTER_ENDPOINT_TTL` (default 3600s) and +> `LITELLM_OPENROUTER_ENDPOINT_TIMEOUT` (default 5s). A failed lookup is +> cached briefly and **logged** (`cost_callback build attribution [slug]: +> ...`, first occurrence at warning), so persistently-null fields are +> diagnosable rather than indistinguishable from "the first fetch hasn't +> landed yet". +> - **`call.prompt_tokens_delta`** — how much the prompt grew since this +> session's previous call *on the same model*. A repetition-trapped agent +> re-sends its whole context plus one near-identical turn, so this lands on +> a small, near-constant value call after call: the livelock signature, +> readable on one line instead of by differencing a whole session's lines +> against each other (which is impossible anyway once the ~48h log +> retention has rolled). `null` on the first call seen for a +> `(session, model)` pair — no predecessor to difference against is not a +> delta of `0` — and negative across a compaction, which is what +> distinguishes a reseed from a flat stall. Keyed per model because the +> paired `[1m]` alias below puts short startup probes on the same +> session id, and differencing prompt length across models is not a +> meaningful quantity the way summing cost across them is. The `request_params` field on a stock (nothing pinned) OpenRouter route: diff --git a/orchestrator/routes/session_state.py b/orchestrator/routes/session_state.py index ec1f145d4..deda9013b 100644 --- a/orchestrator/routes/session_state.py +++ b/orchestrator/routes/session_state.py @@ -57,6 +57,33 @@ def _make_error(message: str, status_code: int = 400) -> tuple[Response, int]: return jsonify({"success": False, "message": message}), status_code +# Cap for the advisory provenance strings. The only one today is an ISO-8601 +# timestamp (~24 chars); this is generous room for that, and a bound on a +# client-supplied value that otherwise reaches the structured log stream +# unmeasured. +_MAX_PROVENANCE_STR = 64 + + +def _advisory_str(block: dict, key: str) -> str | None: + """A bounded string off the advisory block, or ``None``. + + The provenance block never gates the push, so a wrong-typed member is + dropped rather than rejected — but "dropped" has to mean it does not reach + the log line either, which is what a bare ``block.get(key)`` would let it + do.""" + value = block.get(key) + return value[:_MAX_PROVENANCE_STR] if isinstance(value, str) else None + + +def _advisory_int(block: dict, key: str) -> int | None: + """An integer off the advisory block, or ``None``. + + ``bool`` is excluded for the same reason it is everywhere else in egg: + ``isinstance(True, int)`` is True, and ``entries: true`` is not a count.""" + value = block.get(key) + return value if isinstance(value, int) and not isinstance(value, bool) else None + + @session_state_bp.route("//session-state", methods=["POST"]) def push_session_state(pipeline_id: str) -> tuple[Response, int]: """Persist (overwrite) a role's warm-resume record. @@ -68,7 +95,13 @@ def push_session_state(pipeline_id: str) -> tuple[Response, int]: "slice_id": "slice-3", # optional; null/absent → pipeline-level "session_id": "uuid", "window_occupancy": 123456, # optional - "transcript": "" # optional (pointer-only when absent) + "transcript": "", # optional (pointer-only when absent) + "transcript_provenance": { # optional; logged, not stored + "tail_timestamp": "2026-07-29T04:21:34.335Z", + "entries": 3472, + "assistant_turns": 1837, + "bytes": 4788605 + } } """ body = request.get_json(silent=True) @@ -95,6 +128,21 @@ def push_session_state(pipeline_id: str) -> tuple[Response, int]: if transcript is not None and not isinstance(transcript, str): return _make_error("transcript must be a string or null") + # Which transcript this push carried (#3692). The push is a single + # on-exit snapshot, so a record can be a faithful capture of an early + # moment while the session goes on working for another hour — the blob is + # well-formed JSONL either way, which is what makes a stale record and a + # current one indistinguishable by inspection. Logging the tail timestamp + # against the push time turns that gap into a readable number. Advisory + # and client-supplied: it describes the payload, it does not gate it, so a + # malformed block — or a malformed member of a well-formed block — is + # dropped rather than failing the push. Each member is type-checked on the + # way out, matching the handling of every other field on this route: these + # are the only client-supplied values here that reach a log line, and + # "advisory" is a reason not to reject the push, not a reason to forward + # arbitrary JSON into the structured log stream. + prov = body.get("transcript_provenance") + prov = prov if isinstance(prov, dict) else {} stored = get_session_state_store().put( pipeline_id, slice_id, @@ -112,6 +160,10 @@ def push_session_state(pipeline_id: str) -> tuple[Response, int]: role=role, stored=stored, has_transcript=transcript is not None, + transcript_tail_timestamp=_advisory_str(prov, "tail_timestamp"), + transcript_entries=_advisory_int(prov, "entries"), + transcript_assistant_turns=_advisory_int(prov, "assistant_turns"), + transcript_bytes=_advisory_int(prov, "bytes"), ) # ``stored=False`` is not an error: an empty session_id or oversized transcript # simply degrades to a cold reseed next event. Report it so the caller can log. diff --git a/orchestrator/tests/test_session_state_routes.py b/orchestrator/tests/test_session_state_routes.py index e4125eeaa..a2c4856c1 100644 --- a/orchestrator/tests/test_session_state_routes.py +++ b/orchestrator/tests/test_session_state_routes.py @@ -149,6 +149,71 @@ def test_pull_requires_role(self, client): assert r.status_code == 400 +class TestTranscriptProvenance: + """The advisory block describing which transcript a push carried (#3692). + + Advisory means it never gates the push. It does NOT mean the values reach + the structured log line unchecked — every other field on this route is + type-checked, and these are the only client-supplied ones that end up in a + log stream.""" + + def test_a_well_formed_block_is_accepted(self, client): + r = client.post( + _URL, + json={ + "role": "coder", + "session_id": "a", + "transcript": '{"l": 1}\n', + "transcript_provenance": { + "tail_timestamp": "2026-07-29T04:21:34.335Z", + "entries": 3472, + "assistant_turns": 1837, + "bytes": 4788605, + }, + }, + ) + assert r.status_code == 200 + assert r.get_json()["stored"] is True + + def test_a_malformed_block_does_not_fail_the_push(self, client): + # The transcript is the thing worth keeping; a bad description of it + # must not be able to cost us the record. + r = client.post( + _URL, + json={ + "role": "coder", + "session_id": "a", + "transcript": '{"l": 1}\n', + "transcript_provenance": "not an object", + }, + ) + assert r.status_code == 200 + assert r.get_json()["stored"] is True + + def test_wrong_typed_members_are_dropped_not_forwarded(self): + from routes.session_state import _advisory_int, _advisory_str + + block = { + "tail_timestamp": {"nested": "object"}, + "entries": "3472", + "assistant_turns": True, + "bytes": 12, + } + assert _advisory_str(block, "tail_timestamp") is None + assert _advisory_int(block, "entries") is None + # `isinstance(True, int)` is True, and `assistant_turns: true` is not + # a count. + assert _advisory_int(block, "assistant_turns") is None + assert _advisory_int(block, "bytes") == 12 + assert _advisory_str({}, "tail_timestamp") is None + + def test_an_unbounded_string_is_capped(self): + from routes.session_state import _MAX_PROVENANCE_STR, _advisory_str + + value = _advisory_str({"tail_timestamp": "x" * 10_000}, "tail_timestamp") + assert value is not None and len(value) == _MAX_PROVENANCE_STR + + class TestEvict: """#3537 DELETE - operator-facing eviction of a poisoned warm-resume record.""" diff --git a/sandbox/egg_lib/cli_session_state.py b/sandbox/egg_lib/cli_session_state.py index 2ff908f73..b34513ed5 100644 --- a/sandbox/egg_lib/cli_session_state.py +++ b/sandbox/egg_lib/cli_session_state.py @@ -140,9 +140,13 @@ def cmd_session_state_push(args: argparse.Namespace) -> int: file=sys.stderr, ) return 0 + prov = body.get("transcript_provenance") or {} print( f"session-state push: persisted {role} slice={slice_id or 'none'} " - f"(transcript={'yes' if body.get('transcript') else 'no'})", + f"(transcript={'yes' if body.get('transcript') else 'no'} " + f"tail={prov.get('tail_timestamp') or 'none'} " + f"entries={prov.get('entries', 0)} turns={prov.get('assistant_turns', 0)} " + f"bytes={prov.get('bytes', 0)})", file=sys.stderr, ) return 0 diff --git a/sandbox/egg_lib/session_state_sync.py b/sandbox/egg_lib/session_state_sync.py index 2301a6950..18a1b101d 100644 --- a/sandbox/egg_lib/session_state_sync.py +++ b/sandbox/egg_lib/session_state_sync.py @@ -33,6 +33,7 @@ "resolve_config_dir", "resolve_repo_path", "transcript_path", + "transcript_provenance", "write_pulled_state", ] @@ -144,6 +145,50 @@ def write_pulled_state( return False +def transcript_provenance(transcript: str | None) -> dict[str, Any]: + """Describe *which* transcript this push is carrying, so a stored record can + be checked for staleness without re-deriving it from the blob. + + The push is a single on-exit snapshot: a record whose content stopped at + 04:21 while the session went on calling until 05:17 is not corrupt, it is + simply the last snapshot anyone took. Nothing on the record said so, which + is what made that gap invisible — the blob is well-formed JSONL either way, + so "complete" and "stale" are indistinguishable by inspection. Recording the + tail timestamp and the entry counts makes the staleness a readable field. + + ``tail_timestamp`` is the last entry that carries one (entries such as the + trailing ``mode`` marker do not). All keys are ``None``/absent-safe: a + missing or unparseable transcript yields zeros and a null tail rather than + raising into the push, which is best-effort by contract. + """ + if not transcript: + return {"tail_timestamp": None, "entries": 0, "assistant_turns": 0, "bytes": 0} + tail: str | None = None + entries = 0 + assistant_turns = 0 + for line in transcript.split("\n"): + if not line.strip(): + continue + entries += 1 + try: + obj = json.loads(line) + except ValueError: + continue + if not isinstance(obj, dict): + continue + if obj.get("type") == "assistant": + assistant_turns += 1 + stamp = obj.get("timestamp") + if isinstance(stamp, str) and stamp: + tail = stamp + return { + "tail_timestamp": tail, + "entries": entries, + "assistant_turns": assistant_turns, + "bytes": len(transcript.encode("utf-8")), + } + + def read_state_for_push( *, repo_path: str, @@ -182,4 +227,5 @@ def read_state_for_push( ) except OSError: body["transcript"] = None + body["transcript_provenance"] = transcript_provenance(body["transcript"]) return body diff --git a/sandbox/tests/test_session_state_sync.py b/sandbox/tests/test_session_state_sync.py index b02b742ab..61b7717c4 100644 --- a/sandbox/tests/test_session_state_sync.py +++ b/sandbox/tests/test_session_state_sync.py @@ -155,6 +155,12 @@ def test_reads_pointer_and_transcript(self, tmp_path): "session_id": "sid-1", "window_occupancy": 7, "transcript": '{"l":1}\n', + "transcript_provenance": { + "tail_timestamp": None, + "entries": 1, + "assistant_turns": 0, + "bytes": 8, + }, } def test_missing_transcript_yields_pointer_only_body(self, tmp_path): @@ -188,6 +194,51 @@ def test_pointer_without_session_id_returns_none(self, tmp_path): ) +class TestTranscriptProvenance: + """What a push is carrying, recorded so a stored record's staleness is a + readable field rather than something you have to reconstruct from a + separate ledger (#3692).""" + + def test_tail_timestamp_is_the_last_entry_that_has_one(self): + # The real tail is often a trailing marker with no timestamp (a + # ``mode`` line), so "last entry" and "last timestamp" differ. + transcript = ( + '{"type":"assistant","timestamp":"2026-07-29T04:20:00.000Z"}\n' + '{"type":"user","timestamp":"2026-07-29T04:21:34.335Z"}\n' + '{"type":"mode","mode":"normal"}\n' + ) + prov = sync.transcript_provenance(transcript) + assert prov["tail_timestamp"] == "2026-07-29T04:21:34.335Z" + assert prov["entries"] == 3 + assert prov["assistant_turns"] == 1 + assert prov["bytes"] == len(transcript.encode("utf-8")) + + def test_absent_transcript_is_zeroed_not_raised(self): + for empty in (None, ""): + assert sync.transcript_provenance(empty) == { + "tail_timestamp": None, + "entries": 0, + "assistant_turns": 0, + "bytes": 0, + } + + def test_unparseable_lines_are_counted_but_do_not_abort_the_scan(self): + # Best-effort by contract: a torn line must not cost us the tail. + transcript = ( + '{"type":"assistant","timestamp":"2026-07-29T01:00:00.000Z"}\n' + "{not json at all\n" + '{"type":"assistant","timestamp":"2026-07-29T02:00:00.000Z"}\n' + ) + prov = sync.transcript_provenance(transcript) + assert prov["tail_timestamp"] == "2026-07-29T02:00:00.000Z" + assert prov["entries"] == 3 + assert prov["assistant_turns"] == 2 + + def test_bytes_counts_utf8_not_characters(self): + prov = sync.transcript_provenance('{"t":"éé"}\n') + assert prov["bytes"] == len('{"t":"éé"}\n'.encode()) + + class TestRoundTrip: def test_pull_then_push_is_stable(self, tmp_path): """A pulled record read back for push reproduces the same body.""" @@ -197,4 +248,8 @@ def test_pull_then_push_is_stable(self, tmp_path): record = {"session_id": "sid-1", "window_occupancy": 42, "transcript": '{"l":1}\n'} sync.write_pulled_state(record, repo_path=repo, config_dir=cfg, session_state_file=str(ssf)) body = sync.read_state_for_push(repo_path=repo, config_dir=cfg, session_state_file=str(ssf)) - assert body == record + # ``transcript_provenance`` describes the payload rather than being part + # of it — it is logged at push time, never stored — so the round-tripped + # state is the body minus that descriptor. + assert {k: v for k, v in body.items() if k in record} == record + assert body["transcript_provenance"]["entries"] == 1 diff --git a/tests/config/test_cost_callback.py b/tests/config/test_cost_callback.py index 5e1e28768..2056612b4 100644 --- a/tests/config/test_cost_callback.py +++ b/tests/config/test_cost_callback.py @@ -21,9 +21,12 @@ import importlib.util import json import sys +import time import types from pathlib import Path +import pytest + def _load_cost_callback(): """Load ``cost_callback`` from disk with a stubbed ``litellm`` so it @@ -146,6 +149,45 @@ def _mcd( return mcd +@pytest.fixture(autouse=True) +def _hermetic_build_lookup(monkeypatch): + """Keep every test in this file off the network, and off each other's caches. + + ``_build_info`` gates its lookup on ``OPENROUTER_API_KEY``, so ANY test + that reaches ``_record`` — not only the build-attribution ones — spawns a + real HTTP request on a machine that happens to export the key. That is + exactly the machine someone editing ``config/litellm/`` is likely to be + sitting at, which makes the failure mode "hermetic on CI, chatty in the one + place it matters". Clearing the caches at both ends keeps a resolved + endpoint list from one test out of the next one's assertions. + + Tests that want the lookup set the variable themselves; ``monkeypatch`` + applies fixture and test in that order, so the local ``setenv`` wins.""" + monkeypatch.delenv("OPENROUTER_API_KEY", raising=False) + monkeypatch.delenv("LITELLM_OPENROUTER_ENDPOINT_FETCH", raising=False) + monkeypatch.delenv("LITELLM_OPENROUTER_ENDPOINT_TTL", raising=False) + monkeypatch.delenv("LITELLM_OPENROUTER_ENDPOINT_TIMEOUT", raising=False) + for store in (cc._build_cache, cc._build_pending, cc._build_warned): + store.clear() + yield + for store in (cc._build_cache, cc._build_pending, cc._build_warned): + store.clear() + + +def _endpoints_payload(*endpoints: dict) -> dict: + """An OpenRouter ``/models/{slug}/endpoints`` body carrying ``endpoints``.""" + return {"data": {"endpoints": list(endpoints)}} + + +def _endpoint(provider: str, *, name: str, quantization: str, context_length: int) -> dict: + return { + "provider_name": provider, + "name": name, + "quantization": quantization, + "context_length": context_length, + } + + _ATTRIBUTION_HEADERS = { "x-egg-pipeline-id": "pipeline-20260612-abc", "x-egg-agent-role": "reviewer_code", @@ -333,6 +375,377 @@ def test_mixed_session_sums_only_known_costs(self, monkeypatch): assert session["cost"] == 0.0123 +class TestPromptTokensDelta: + """Per-call growth of the prompt within a session (#3595) — the livelock + signature, made readable from one line instead of by differencing a whole + session's lines against each other after the fact.""" + + def setup_method(self): + cc._session_totals.clear() + + def _capture(self, monkeypatch) -> list[dict]: + emitted: list[dict] = [] + monkeypatch.setattr(cc, "_emit", lambda payload: emitted.append(payload)) + return emitted + + def _usage(self, prompt_tokens: int) -> dict: + return {"prompt_tokens": prompt_tokens, "completion_tokens": 10, "cost": 0.001} + + def test_first_call_has_no_delta(self, monkeypatch): + emitted = self._capture(monkeypatch) + cc.LiteLLMCostLogger()._record(_mcd("d1", raw_usage=self._usage(1000)), None) + # No predecessor to difference against. That is not a delta of zero, + # which would read as "the prompt did not grow". + assert emitted[0]["call"]["prompt_tokens_delta"] is None + + def test_repetition_trap_shows_a_small_constant_delta(self, monkeypatch): + emitted = self._capture(monkeypatch) + logger = cc.LiteLLMCostLogger() + # The observed #3595 shape: each turn re-sends the whole context plus + # one near-identical increment. + for prompt in (460_000, 460_527, 461_054, 461_581): + logger._record(_mcd("d2", raw_usage=self._usage(prompt)), None) + deltas = [e["call"]["prompt_tokens_delta"] for e in emitted] + assert deltas == [None, 527, 527, 527] + + def test_deltas_are_tracked_per_session_not_globally(self, monkeypatch): + emitted = self._capture(monkeypatch) + logger = cc.LiteLLMCostLogger() + logger._record(_mcd("a", raw_usage=self._usage(1000)), None) + logger._record(_mcd("b", raw_usage=self._usage(50_000)), None) + logger._record(_mcd("a", raw_usage=self._usage(1200)), None) + # Session b's much larger prompt must not contaminate session a's + # delta; interleaved sessions are the normal case on a busy proxy. + assert emitted[1]["call"]["prompt_tokens_delta"] is None + assert emitted[2]["call"]["prompt_tokens_delta"] == 200 + + def test_a_shrinking_prompt_reads_as_negative_not_as_zero(self, monkeypatch): + emitted = self._capture(monkeypatch) + logger = cc.LiteLLMCostLogger() + logger._record(_mcd("c", raw_usage=self._usage(400_000)), None) + # A compaction / reseed drops the prompt. Recording that as a real + # negative is what distinguishes it from a stalled-but-flat session. + logger._record(_mcd("c", raw_usage=self._usage(12_000)), None) + assert emitted[-1]["call"]["prompt_tokens_delta"] == -388_000 + + def test_deltas_are_tracked_per_model_within_a_session(self, monkeypatch): + # Summing COST across the models one session touched is meaningful; + # differencing prompt LENGTH across them is not. Claude Code's paired + # `[1m]` alias puts short startup probes on the same session id + # as the main calls, so a session-wide key would inject a large + # negative delta followed by a large positive one into the exact signal + # this field carries. + emitted = self._capture(monkeypatch) + logger = cc.LiteLLMCostLogger() + main = _mcd("s", raw_usage=self._usage(460_000)) + probe = _mcd("s", raw_usage=self._usage(40)) + probe["model"] = "openrouter/qwen/qwen3-max[1m]" + logger._record(main, None) + logger._record(probe, None) + logger._record(_mcd("s", raw_usage=self._usage(460_527)), None) + deltas = [e["call"]["prompt_tokens_delta"] for e in emitted] + # The probe is the first call for ITS model, so it has no delta of its + # own, and it leaves the main model's series undisturbed. + assert deltas == [None, None, 527] + + +class TestBuildAttribution: + """Which physical build served the turn (#3692): provider per call off the + response, endpoint name + quantization selected out of cached per-model + metadata BY that provider.""" + + def setup_method(self): + cc._session_totals.clear() + + def _capture(self, monkeypatch) -> list[dict]: + emitted: list[dict] = [] + monkeypatch.setattr(cc, "_emit", lambda payload: emitted.append(payload)) + return emitted + + def _settle(self, slug: str) -> None: + """Join the daemon lookup thread by polling the cache.""" + for _ in range(200): + if slug in cc._build_cache: + return + time.sleep(0.01) + pytest.fail(f"lookup for {slug} never landed") + + def test_no_network_without_a_configured_key(self, monkeypatch): + # The logging hook must never reach for the network uninvited; without + # the credential the proxy runs with, the lookup is not attempted. + monkeypatch.setattr( + cc, "_fetch_build_info", lambda slug: pytest.fail("fetched without a key") + ) + assert cc._build_info("openrouter/poolside/laguna-s-2.1", "Poolside") is None + + def test_the_kill_switch_stops_the_lookup(self, monkeypatch): + monkeypatch.setenv("OPENROUTER_API_KEY", "k") + monkeypatch.setenv("LITELLM_OPENROUTER_ENDPOINT_FETCH", "0") + monkeypatch.setattr(cc, "_fetch_build_info", lambda slug: pytest.fail("fetched when off")) + assert cc._build_info("openrouter/poolside/laguna-s-2.1", "Poolside") is None + + def test_slug_strips_the_openrouter_prefix(self): + assert cc._upstream_slug("openrouter/poolside/laguna-s-2.1") == "poolside/laguna-s-2.1" + assert cc._upstream_slug("poolside/laguna-s-2.1") == "poolside/laguna-s-2.1" + assert cc._upstream_slug(None) is None + + def test_slug_strips_the_context_window_opt_in_suffix(self): + # Claude Code's `[1m]` alias leaks through on startup probes and is not + # a published OpenRouter slug — left on, it 404s the lookup for a name + # that denotes the same model. + assert cc._upstream_slug("openrouter/qwen/qwen3-max[1m]") == "qwen/qwen3-max" + # A `:free`-style variant IS a different endpoint set, so it stays. + assert cc._upstream_slug("openrouter/qwen/qwen3-max:free") == "qwen/qwen3-max:free" + + def test_the_endpoint_is_matched_on_provider_not_on_list_position(self, monkeypatch): + # The `extra_body.provider` pin routes the completion; it has no effect + # on this public metadata route, which takes no provider parameter. So + # index 0 is whatever OpenRouter's default sort returns — a real + # `z-ai/glm-4.6` lookup puts a provider we never talked to there, with + # its own quantization and context length. + monkeypatch.setenv("OPENROUTER_API_KEY", "k") + monkeypatch.setattr( + cc, + "_fetch_build_info", + lambda slug: cc._parse_endpoints( + slug, + _endpoints_payload( + _endpoint( + "Venice", + name="Venice | z-ai/glm-4.6", + quantization="fp4", + context_length=198000, + ), + _endpoint( + "Z.AI", + name="Z.AI | z-ai/glm-4.6", + quantization="fp8", + context_length=202752, + ), + ), + "https://example.invalid", + ), + ) + assert cc._build_info("openrouter/z-ai/glm-4.6", "Z.AI") is None + self._settle("z-ai/glm-4.6") + info = cc._build_info("openrouter/z-ai/glm-4.6", "Z.AI") + assert info == { + "name": "Z.AI | z-ai/glm-4.6", + "quantization": "fp8", + "context_length": 202752, + } + # Case and surrounding whitespace in the response's provider name must + # not decide whether attribution works. + assert cc._build_info("openrouter/z-ai/glm-4.6", " z.ai ") == info + + def test_a_provider_with_no_published_row_reports_nothing(self, monkeypatch): + # Silence beats naming a build belonging to a provider we never talked + # to: the whole point of the field is post-mortems that turn on the + # quantization. + monkeypatch.setenv("OPENROUTER_API_KEY", "k") + monkeypatch.setattr( + cc, + "_fetch_build_info", + lambda slug: cc._parse_endpoints( + slug, + _endpoints_payload( + _endpoint( + "Venice", name="Venice | m", quantization="fp4", context_length=198000 + ), + _endpoint( + "Novita", name="Novita | m", quantization="bf16", context_length=204800 + ), + ), + "https://example.invalid", + ), + ) + cc._build_info("openrouter/m", "Alibaba") + self._settle("m") + assert cc._build_info("openrouter/m", "Alibaba") is None + # Same for a call whose provider never survived stream reassembly: + # with more than one endpoint published there is nothing to infer. + assert cc._build_info("openrouter/m", None) is None + + def test_a_single_endpoint_model_answers_even_without_a_provider(self, monkeypatch): + # The streaming path (all agent traffic) usually cannot name the + # provider. A model publishing exactly one endpoint is still + # unambiguous — it was served by that endpoint or by nothing — so this + # is an inference, not a guess. + monkeypatch.setenv("OPENROUTER_API_KEY", "k") + monkeypatch.setattr( + cc, + "_fetch_build_info", + lambda slug: cc._parse_endpoints( + slug, + _endpoints_payload( + _endpoint( + "Poolside", + name="Poolside | poolside/laguna-s-2.1-20260720", + quantization="bf16", + context_length=1048576, + ) + ), + "https://example.invalid", + ), + ) + cc._build_info("openrouter/poolside/laguna-s-2.1", None) + self._settle("poolside/laguna-s-2.1") + info = cc._build_info("openrouter/poolside/laguna-s-2.1", None) + assert info["quantization"] == "bf16" + assert info["name"].endswith("20260720") + + def test_metadata_is_fetched_once_per_model_then_cached(self, monkeypatch): + monkeypatch.setenv("OPENROUTER_API_KEY", "k") + calls = [] + + def fake_fetch(slug): + calls.append(slug) + return { + "by_provider": { + "poolside": { + "name": "Poolside | poolside/laguna-s-2.1-20260720", + "quantization": "bf16", + "context_length": 1048576, + } + }, + "sole": None, + } + + monkeypatch.setattr(cc, "_fetch_build_info", fake_fetch) + # Runs on a daemon thread, so the first sighting returns None; join by + # polling the cache rather than sleeping a fixed interval. + assert cc._build_info("openrouter/poolside/laguna-s-2.1", "Poolside") is None + self._settle("poolside/laguna-s-2.1") + info = cc._build_info("openrouter/poolside/laguna-s-2.1", "Poolside") + assert info["quantization"] == "bf16" + # A second and third sighting must not re-fetch — including one for a + # different provider, which is answered out of the same cached list. + cc._build_info("openrouter/poolside/laguna-s-2.1", "Poolside") + cc._build_info("openrouter/poolside/laguna-s-2.1", "Venice") + assert calls == ["poolside/laguna-s-2.1"] + + def test_a_failed_lookup_is_cached_so_it_is_not_retried_per_call(self, monkeypatch): + monkeypatch.setenv("OPENROUTER_API_KEY", "k") + calls = [] + monkeypatch.setattr(cc, "_fetch_build_info", lambda slug: calls.append(slug) or None) + cc._build_info("openrouter/m", "P") + self._settle("m") + cc._build_info("openrouter/m", "P") + cc._build_info("openrouter/m", "P") + assert calls == ["m"] + + def test_a_cached_failure_expires_where_a_success_does_not(self, monkeypatch): + # A failure must be cached — otherwise a 404 slug fires an HTTP request + # per call — but caching it as durably as a success is what turns one + # DNS blip into permanently null attribution for the pod's lifetime. + monkeypatch.setenv("OPENROUTER_API_KEY", "k") + calls = [] + monkeypatch.setattr(cc, "_fetch_build_info", lambda slug: calls.append(slug) or None) + cc._build_info("openrouter/m", "P") + self._settle("m") + # Age the cached failure past its (shorter) TTL. + stamp, record = cc._build_cache["m"] + cc._build_cache["m"] = (stamp - cc.DEFAULT_BUILD_FAILURE_TTL_SECONDS - 1, record) + cc._build_info("openrouter/m", "P") + for _ in range(200): + if len(calls) > 1: + break + time.sleep(0.01) + assert calls == ["m", "m"] + assert cc.DEFAULT_BUILD_FAILURE_TTL_SECONDS < cc.DEFAULT_BUILD_TTL_SECONDS + + def test_every_failure_path_is_reported(self, monkeypatch): + # The operator-visible symptom of a bad slug and of a lookup that has + # simply not landed yet is the same null. Only the log tells them + # apart, so silence on any of these branches is the defect. + monkeypatch.setenv("OPENROUTER_API_KEY", "k") + logged: list[tuple] = [] + + # Returns True, like the real ``_log`` does on a successful emit: the + # warn-once latch is deliberately conditional on that, so a fake that + # returned None would never latch and would hide the demotion. + def _fake_log(level, msg, *a): + logged.append((level, msg % a)) + return True + + monkeypatch.setattr(cc, "_log", _fake_log) + + class _Boom: + def __enter__(self): + raise OSError("HTTP Error 404: Not Found") + + def __exit__(self, *exc): + return False + + monkeypatch.setattr(cc.urllib.request, "urlopen", lambda *a, **k: _Boom()) + assert cc._fetch_build_info("qwen3-max") is None + assert len(logged) == 1 + level, message = logged[0] + # First failure at warning — the one worth seeing — and it names both + # the slug and the URL that produced it. + assert level == "warning" + assert "qwen3-max" in message and "404" in message + # Repeats drop to debug rather than one line per TTL forever. + cc._fetch_build_info("qwen3-max") + assert logged[1][0] == "debug" + + def test_a_non_json_body_is_reported_rather_than_swallowed(self, monkeypatch): + monkeypatch.setenv("OPENROUTER_API_KEY", "k") + logged: list[tuple] = [] + + # Returns True, like the real ``_log`` does on a successful emit: the + # warn-once latch is deliberately conditional on that, so a fake that + # returned None would never latch and would hide the demotion. + def _fake_log(level, msg, *a): + logged.append((level, msg % a)) + return True + + monkeypatch.setattr(cc, "_log", _fake_log) + + class _Body: + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def read(self): + return b"gateway timeout" + + monkeypatch.setattr(cc.urllib.request, "urlopen", lambda *a, **k: _Body()) + assert cc._fetch_build_info("m") is None + assert logged and "non-JSON" in logged[0][1] + + def test_provider_is_read_off_the_nonstreaming_response_body(self): + body = json.loads(json.dumps({"provider": "Poolside", "usage": {}})) + assert cc._extract_provider(body, None) == "Poolside" + + def test_provider_falls_back_to_the_assembled_object(self): + obj = types.SimpleNamespace(provider="Poolside") + assert cc._extract_provider(None, obj) == "Poolside" + + def test_unknown_provider_is_none_not_a_guess(self): + assert cc._extract_provider(None, None) is None + + def test_the_litellm_route_provider_is_not_reported_as_the_upstream(self): + # `_hidden_params["custom_llm_provider"]` is the literal string + # "openrouter" on every model egg registers — litellm's ROUTE, not the + # upstream that served the turn. Reading it would make this field + # non-null on every streamed call while answering a different + # question, so `endpoint.provider == null` would find nothing and an + # operator would conclude attribution was working. + obj = types.SimpleNamespace(_hidden_params={"custom_llm_provider": "openrouter"}) + assert cc._extract_provider(None, obj) is None + + def test_endpoint_block_is_emitted_with_nulls_before_the_lookup_lands(self, monkeypatch): + emitted = self._capture(monkeypatch) + cc.LiteLLMCostLogger()._record(_mcd("b1", raw_usage=_usage_with_cost()), None) + ep = emitted[0]["endpoint"] + # Null means "not yet known", never a fabricated default. + assert set(ep) == {"provider", "name", "quantization", "context_length"} + assert ep["name"] is None and ep["quantization"] is None + + class TestEstimatedCost: """LiteLLM's pricing-map ``response_cost``, surfaced as ``cost_estimated`` — strictly separate from the billed ``cost`` and under the same @@ -539,11 +952,19 @@ def test_explicit_sampling_params_are_recorded(self): assert params["repetition_penalty"] == 1.05 assert params["reasoning_effort"] == "high" - def test_prompt_bearing_params_are_excluded(self): + def test_prompt_payloads_are_excluded_while_the_mode_selector_is_kept(self): # optional_params also carries the translated tool schemas (Claude Code # sends a dozen-plus per request). Dumping it whole would bloat every # line and spill task text into a cost stream. The allowlist is the # guard; this pins it. + # + # The line the allowlist draws is payload vs selector, not "anything + # tool-shaped": ``tools`` is recorded by ARITY only (``tools_count``) + # because tool presence is the strongest observed lever on whether the + # model reasons, while the schemas it counts are exactly the bloat the + # allowlist exists to keep out; ``tool_choice`` is a small scalar mode + # selector carrying no prompt text, and is recorded verbatim. What + # stays out either way is the schema bodies and the messages. params = cc._extract_request_params( _mcd( "r", @@ -556,7 +977,38 @@ def test_prompt_bearing_params_are_excluded(self): }, ) ) - assert params == {"temperature": 0.3} + assert params == {"temperature": 0.3, "tools_count": 1, "tool_choice": "auto"} + # The schema body and the prompt text are the things that must never + # reach this stream, whatever else the allowlist grows to carry. + rendered = json.dumps(params) + assert "y" * 100 not in rendered + assert "secret task text" not in rendered + + def test_tools_arity_is_recorded_without_the_schemas(self): + # 0 vs many is the signal the 2x2 turned on, so the count has to + # survive a realistic dozen-plus-tool Claude Code request intact. + params = cc._extract_request_params( + _mcd( + "r", + optional_params={ + "tools": [ + {"name": f"tool{i}", "input_schema": {"x": "y" * 400}} for i in range(14) + ], + "tool_choice": "none", + }, + ) + ) + assert params["tools_count"] == 14 + assert params["tool_choice"] == "none" + assert "y" * 100 not in json.dumps(params) + + def test_absent_tools_key_is_not_reported_as_zero(self): + # "we could not tell" and "no callable tools were offered" are + # different claims; only the latter may read as 0. + params = cc._extract_request_params(_mcd("r", optional_params={"temperature": 0.3})) + assert "tools_count" not in params + empty = cc._extract_request_params(_mcd("r", optional_params={"tools": []})) + assert empty["tools_count"] == 0 def test_extra_body_hoists_known_knobs_and_keeps_the_provider_pin(self): # LiteLLM relocates knobs a provider doesn't declare into extra_body