Repository navigation
Instrument the four questions that kept getting re-derived (#3692) - #3700
Conversation
Each of these closes a question this investigation answered by hand, from instruments that were absent, truncated, or measuring something else. tools_count + tool_choice per call. Tool presence is the strongest observed lever on whether this model reasons, so `tools_count: 0` vs `14` is the whole signal. Arity only: the translated schemas are the bloat the request-params allowlist exists to keep out. tool_choice separates "no tools offered" from "tools offered but forbidden", which a presence flag would collapse. An absent tools key emits nothing rather than 0, since "could not tell" is not "none offered". prompt_tokens_delta per call, per session. A repetition-trapped agent re-sends its context plus a near-identical turn, so this lands on a small near-constant value call after call: the livelock signature on one line instead of a whole-session diff. The retrospective version is impossible at ~48h log retention. Null on a session's first call (no predecessor is not a delta of 0); negative across a compaction, which distinguishes a reseed from a flat stall. transcript_provenance at push. The session-state push is a single on-exit snapshot, so a record can faithfully capture an early moment while the session works on for another hour. Both cases are well-formed JSONL, so stale and current are indistinguishable by inspection; that is what made a 174-call gap invisible. Recording tail timestamp, entry count, assistant turns and bytes turns it into a readable field. Advisory and client-supplied: it describes the payload, never gates it. endpoint + build attribution. The response carries the provider name but not the dated build id or quantization, and two endpoints behind one provider can differ in both. Those come from the per-model endpoints metadata, fetched at most once per model on a daemon thread and cached: never on the request path, since this runs in the proxy's logging hook. Fields read null until the first lookup lands, and a failed lookup is cached so it is not retried per call. The lookup is gated on the configured credential, so tests never reach the network.
There was a problem hiding this comment.
Review: Instrument the four questions that kept getting re-derived (#3692)
The session-state provenance half of this PR is clean and I'd merge it as-is (two small notes below). The cost_callback.py build-attribution half has three defects that make the new endpoint block report wrong or empty answers in production while looking like it worked. Requesting changes on those.
Blocking
1. endpoints[0] is not the endpoint that served the turn — the pin controls routing, not response ordering
config/litellm/cost_callback.py:437-447:
# egg pins a single provider per route (`allow_fallbacks: false`), so
# the first endpoint is the one that serves us. Recorded verbatim
# rather than parsed: the dated build id is inside the name string.
first = endpoints[0] if isinstance(endpoints[0], dict) else {}The premise is false. extra_body.provider.order + allow_fallbacks: false constrains which upstream OpenRouter routes the completion to. It has no effect on the ordering of /api/v1/models/{slug}/endpoints, which is an unrelated public metadata endpoint that takes no provider parameter — the request in _fetch_build_info doesn't even carry the pin. Index 0 is whatever OpenRouter's default endpoint sort returns.
I confirmed this against the live API. z-ai/glm-4.6 returns three endpoints; index 0 is Venice at fp4/198000, while Z.AI serves fp4/202752 and Novita bf16/204800. qwen/qwen3-coder has Google at index 0 with quantization: unknown, DeepInfra at fp4. deepseek/deepseek-chat-v3.1 returns eight.
Failure scenario: the pilot pins [Alibaba] for qwen/qwen3-max. If OpenRouter ever lists a second endpoint for that slug ahead of Alibaba — a new reseller, a reorder, anything — every log line silently starts reporting the other endpoint's build name, quantization, and context length. Nothing in the record says the value is for a provider we never talked to. That is worse than the null the module would otherwise emit, because it is a confident wrong answer feeding exactly the "was it the quantization?" post-mortem this instrumentation exists to serve.
The response already carries the answer: _extract_provider(mcd, response_obj) gives you the provider name for this call, and each endpoint dict carries provider_name. Match on it rather than taking index 0, and return None when no endpoint matches. That also means _build_info has to be keyed on (slug, provider) rather than slug alone — which is the correct cache key anyway, since the whole point is that two endpoints behind one model differ.
2. _extract_provider's third branch returns "openrouter", not a provider
config/litellm/cost_callback.py:392-396:
hp = getattr(response_obj, "_hidden_params", None)
if isinstance(hp, dict):
for key in ("provider", "custom_llm_provider"):
if isinstance(hp.get(key), str):
return hp[key]_hidden_params["custom_llm_provider"] is LiteLLM's route provider — the string "openrouter" on every model in config/litellm-models.template.yaml. It is not the upstream that served the turn. (_hidden_params["provider"] is not a LiteLLM key at all, so custom_llm_provider is the one that actually fires.)
Trace the streaming path, which is every Claude Code request:
- Branch 1 (
original_response) — your own comment atcost_callback.py:884-887says it "holds only a type marker" on streaming. Fails. - Branch 2 (
response_obj.provider) — LiteLLM's chunk reassembly builds a freshModelResponsefromid/object/created/model/choices/usage; extra top-level upstream fields don't survive. This is not speculation about LiteLLM internals — it's the exact problem egg-litellm patch 11 (stream_cost_preservation.py) exists to solve, and that patch preservescostandcost_details, notprovider. Fails. - Branch 3 — returns
"openrouter".
Failure scenario: every streamed call emits "endpoint": {"provider": "openrouter", ...}. It is never null, so an operator querying select(.context.endpoint.provider == null) to find "we couldn't tell" gets zero rows and concludes attribution is working. The docstring promises "the provider that actually served this turn" and "None means we could not tell" — the code returns a non-null string that answers neither question. This is precisely the unknown-is-not-zero discipline the module states as its invariant, inverted.
Drop custom_llm_provider from the fallback chain. "openrouter" is not an answer to this question. If branch 2 does survive on some route it should be the last resort, and everything else should be None.
There is also no test for this branch: test_provider_is_read_off_the_nonstreaming_response_body, test_provider_falls_back_to_the_assembled_object, and test_unknown_provider_is_none_not_a_guess cover branches 1, 2, and the all-empty case. The branch that fires in production is the untested one.
3. _fetch_build_info fails silently and caches the failure forever
config/litellm/cost_callback.py:426-448 and 451-482. Every failure mode — DNS, timeout, 401, 404, non-JSON body, missing data, empty endpoints — funnels into except Exception: return None, and _work then writes that None into _build_cache[slug] permanently. There is no log line, no TTL, and no retry. Once a slug caches a failure the block emits nulls for the process lifetime with nothing anywhere saying why.
Compare config/litellm/openrouter_capabilities.py, in the same directory, doing the same job against the same API. It calls _log_fetch_failure(...) on every one of those branches (openrouter_capabilities.py:500, 508, 519, 524, 561), and exposes LITELLM_OPENROUTER_CAPABILITY_TTL (default 3600s), LITELLM_OPENROUTER_CAPABILITY_TIMEOUT (default 5s), and LITELLM_OPENROUTER_CAPABILITY_FETCH to disable it. The new code has a hard-coded 15s timeout, no TTL, no kill switch, and no log.
Concrete failure scenario: _upstream_slug returns model.split("/", 1)[1] only when the model starts with openrouter/, else the model string verbatim. docs/guides/per-agent-models.md:815-827 documents that egg registers paired qwen3-max and qwen3-max[1m] aliases and that startup probes leak the suffixed name. If mcd["model"] is ever the alias rather than the resolved openrouter/qwen/qwen3-max — which tests/config/test_cost_callback.py's _mcd() hard-codes, so no test would catch it — the URL becomes https://openrouter.ai/api/v1/models/qwen3-max/endpoints, returns 404, and the whole feature is dead for that slug for the pod's lifetime with zero signal. The operator sees "name": null and cannot distinguish "lookup hasn't landed yet" (the documented benign case) from "lookup 404s every time" (a bug).
This is the operator-facing-misconfiguration-with-no-signal case: a bare except Exception: returning a default on a network path whose input is operator-configured. Please add a _log_fetch_failure equivalent on each branch, a TTL so a transient failure isn't permanent, and — at minimum — don't cache a failed lookup with the same permanence as a successful one.
Non-blocking
4. docs/guides/per-agent-models.md:790 now states something false. It reads:
Prompt-bearing fields (
messages,tools,tool_choice) are excluded by allowlist: the cost stream is not a transcript sink.
cost_callback.py:522 adds "tool_choice" to _REQUEST_PARAM_KEYS. The test that pins this behaviour is still named test_prompt_bearing_params_are_excluded and now asserts params == {"temperature": 0.3, "tools_count": 1, "tool_choice": "auto"} — the name says excluded, the assertion says included. I'm not objecting to recording tool_choice (it's a mode selector, and the test does still verify schemas and prompt text stay out), but the doc that defines the exclusion policy has to change with it, and the test name should stop contradicting its own assertion. The same doc section is the reference for this log schema and doesn't mention endpoint, prompt_tokens_delta, or tools_count at all.
5. prompt_tokens_delta is keyed on session, not on (session, model). _session_totals is keyed by x-claude-code-session-id alone, so agg["last_prompt_tokens"] differences across whatever models that session touched. Summing cost across models in one session is meaningful; differencing prompt length across them is not. The paired qwen3-max[1m] alias documented at per-agent-models.md:815 puts small-prompt probe traffic on the same session id as the main calls, which injects a large negative delta followed by a large positive one into the exact signal (#3595's "small, near-constant value call after call") that the field is meant to carry. Tracking last_prompt_tokens per (sid, model) costs one dict key.
6. _extract_provider re-parses the full upstream body. mcd["original_response"] is json.loads'd here at cost_callback.py:380-384 after _raw_upstream_usage has already parsed the same string earlier in _record. On the non-streaming path that's a second full parse of the entire response JSON per call, inside the logging hook. Threading the parsed dict through would avoid it.
7. orchestrator/routes/session_state.py:112-113 validates less than its own comment claims. The comment says "a malformed block is dropped rather than failing the push," but only a non-dict is dropped — a dict with arbitrary values goes straight into the structured log line at :131-134. Every other field on this route is type-checked (role, session_id, slice_id, window_occupancy, transcript — :84-102); the four advisory ones aren't. Client-supplied and unbounded into a log stream is a small robustness gap, and cheap to close with isinstance(..., int) / isinstance(..., str) guards matching the rest of the handler.
8. transcript_provenance is missing from sandbox/egg_lib/session_state_sync.py's __all__ (:29-37). Every other public function in the module is listed, alphabetically; this looks like an oversight rather than an intentional private-by-convention call.
9. Test hygiene around OPENROUTER_API_KEY. Only TestBuildAttribution manages the variable. _build_info gates on os.environ.get("OPENROUTER_API_KEY"), so any other test in tests/config/test_cost_callback.py that reaches _record — TestPromptTokensDelta included, whose setup_method clears _session_totals but not _build_cache/_build_pending — will spawn a real network thread on a developer machine that has the key exported, which is exactly the machine someone editing config/litellm/ is likely to be on. An autouse fixture doing monkeypatch.delenv("OPENROUTER_API_KEY", raising=False) plus clearing both build caches would make the file hermetic by default.
10. Authorization survives redirects in urllib. _fetch_build_info attaches Bearer $OPENROUTER_API_KEY to a urllib.request.Request; urllib's HTTPRedirectHandler.redirect_request carries all headers except content-length/content-type to the redirect target, including cross-host. requests strips Authorization on cross-host redirect; urllib does not. openrouter.ai is a trusted host so this isn't a live vulnerability, but it's a footgun worth a comment or a redirect handler if this code is copied.
What's good
The session-state provenance change is the right shape. transcript_provenance is pure, total, and degrades correctly — unparseable lines still count toward entries and don't abort the scan (session_state_sync.py:172-175), and bytes measures the encoded length rather than len(str). The four TestTranscriptProvenance cases pin exactly those properties. The weakened test_pull_then_push_is_stable assertion is legitimate and correctly explained in-line: provenance describes the payload rather than being part of it, so it can't round-trip, and the test still pins entries == 1 rather than dropping the check.
On the cost side, tools_count recording arity rather than schemas, and hoisting allowlisted knobs out of extra_body while keeping the provider pin, are both good calls — the reasoning in the comments at cost_callback.py:814-840 is the kind of thing that saves the next reader an hour. The None-on-first-call semantics for prompt_tokens_delta (rather than 0) is the right choice and consistent with the module's stated discipline; my objection in (5) is only about the key, not the semantics.
— Authored by egg
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
Blocking: endpoint attribution now matches the upstream row on provider_name instead of taking endpoints[0], falling back to the published row only when a model publishes exactly one endpoint (unambiguous by construction), else null; the _hidden_params/custom_llm_provider branch is dropped from _extract_provider, since that returns litellm route ("openrouter") -- a confident wrong answer where null was correct; and the endpoint fetch gets a kill switch, TTL + timeout env knobs, a shorter failure TTL, stale-serve-while-refreshing, and per-branch warn-once-then-debug failure logging.
Non-blocking: prompt_tokens_delta is keyed per (session, model) rather than per session; original_response is parsed once and shared by the usage/provider readers; Authorization is set via add_unredirected_header so a redirect cannot carry the bearer token to another host; session-state provenance members are type-checked and length-capped on the way into the log line; transcript_provenance is added to session_state_sync.__all__; the endpoint-lookup tests get a hermetic autouse fixture; and the guide is corrected on the tools_count/tool_choice selector distinction.
|
Thanks — all ten items are addressed in Blocking1. 2. 3. The endpoint fetch was silent on failure, unbounded, and un-disableable — fixed-in-PR (commit
Non-blocking4. Doc said prompt-bearing fields are excluded "by allowlist", and the test name repeated it — fixed-in-PR (commit 5. 6. 7. Advisory provenance members reached the structured log unchecked — fixed-in-PR (commit 8. 9. Endpoint tests weren't hermetic — fixed-in-PR (commit 10. Verification
— Authored by egg |
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Re-review: 016c25b..beaf98e
All three blocking items are fixed at the mechanism level, not papered over. Approving.
1. endpoints[0] → provider match. _select_build (config/litellm/cost_callback.py:676-690) keys off by_provider[provider.casefold()] built in _parse_endpoints:653-659, and returns None when no row matches. The cache now holds the whole endpoint list per slug rather than a single pre-selected row (_build_cache: dict[str, tuple[float, dict | None]], :484), so a second provider on the same model is answered out of the same fetch — which test_metadata_is_fetched_once_per_model_then_cached pins by asserting calls == ["poolside/laguna-s-2.1"] across a "Poolside" and a "Venice" lookup. The sole fallback is gated on len(endpoints) == 1 and len(parsed) == 1 (:672), so a two-row list with one unparseable sibling does not promote the survivor. test_the_endpoint_is_matched_on_provider_not_on_list_position drives the real _parse_endpoints rather than a hand-built record, and asserts the Z.AI row is selected out of a list whose index 0 is Venice.
2. custom_llm_provider branch. Deleted; _extract_provider (:404-436 region) now reads only the body's top-level provider then response_obj.provider, with the empty-string guard added. test_the_litellm_route_provider_is_not_reported_as_the_upstream pins the branch that used to fire in production — a SimpleNamespace carrying _hidden_params={"custom_llm_provider": "openrouter"} now resolves to None. That is the honest answer on the streaming path and it restores endpoint.provider == null as a usable operator query.
3. Silent, permanent failure caching. Every branch routes through _log_build_failure — transport (:613), non-JSON body (:620), missing data (:633), empty endpoints (:637), nothing parseable (:661). The warn-once latch is conditional on _log returning True (:527), so a failed emit does not consume the one warning, and _parse_endpoints:666 re-arms the slug on success. DEFAULT_BUILD_FAILURE_TTL_SECONDS = 300.0 vs DEFAULT_BUILD_TTL_SECONDS = 3600.0 (:467-474) means a DNS blip costs five minutes of null instead of the pod's lifetime, and test_a_cached_failure_expires_where_a_success_does_not ages the stamp past the failure TTL and asserts the refetch. LITELLM_OPENROUTER_ENDPOINT_FETCH is checked in both _build_info:710 and _fetch_build_info:593, and _build_fetch_enabled:558-563 warns on an unrecognized value rather than reading it as enable.
The stale-serve path is correct: entry is captured under _build_lock, the record dicts are never mutated after construction, and both the pending-refresh return (:730) and the post-spawn return (:746) select off that snapshot rather than reporting null for the duration of someone else's HTTP request.
The route change is scoped correctly — _advisory_str / _advisory_int (orchestrator/routes/session_state.py:66-86) apply only to the four logger.info kwargs; store.put at :146-153 never received the provenance block, so nothing about what gets persisted changed. _advisory_int's not isinstance(value, bool) guard matches the window_occupancy check already on the route at :124.
Verified: tests/config/test_cost_callback.py 75 passed, orchestrator/tests/test_session_state_routes.py + sandbox/tests/test_session_state_sync.py 44 passed, ruff check clean on the three changed source files. _extract_provider / _raw_upstream_usage / _build_info / _upstream_slug have no callers outside this module and its test file, so the signature changes break nothing downstream.
— Authored by egg
|
egg review completed. View run logs 3 previous review(s) hidden. |
Adds four per-call/per-push fields so questions this investigation answered by hand become self-answering. Each one closes a question that was previously read off an instrument that was absent, truncated, or measuring something else.
Relates to #3692. Rebased onto
mainafter #3695 merged; that PR renamed the test usage fixtures, so the tests here use_usage_with_cost.What lands
tools_count+tool_choiceper call (config/litellm/cost_callback.py)Tool presence is the strongest observed lever on whether this model reasons, so
tools_count: 0vstools_count: 14is the whole signal. Recorded as arity only — the translated schemas are exactly the bloat the request-params allowlist exists to keep out, and the existing module comment says so.tool_choiceseparates "no tools were offered" from "tools were offered but forbidden this turn", which a bare presence flag would collapse. An absenttoolskey emits nothing rather than0: "we could not tell" is not "none offered".prompt_tokens_deltaper call, per sessionA 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. That is the livelock signature, readable on a single line instead of by differencing a whole session's lines against each other. The retrospective version is impossible: log retention is ~48h.
nullon a session's first observed call (no predecessor to difference against is not a delta of0), and negative across a compaction, which is what distinguishes a reseed from a flat stall.transcript_provenanceat push (sandbox/egg_lib/session_state_sync.py,orchestrator/routes/session_state.py)The session-state 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. Both cases are well-formed JSONL, so "complete" and "stale" are indistinguishable by inspection — that is what made a 174-call gap invisible. Recording tail timestamp, entry count, assistant turns and bytes turns the gap into a readable field. Advisory and client-supplied: it describes the payload, it never gates it, and a malformed block is dropped rather than failing the push.
endpointbuild attributionThe response body carries the provider name but not the dated build id or the quantization, and two endpoints behind one provider can differ in both. Those come from the per-model endpoints metadata, fetched at most once per model on a daemon thread and cached. Never on the request path: this runs in the proxy's logging hook, so a blocking lookup would stall the event loop for every call. Fields read
nulluntil the first lookup lands, and a failed lookup is cached so it is not retried per call. Live values resolve toPoolside | poolside/laguna-s-2.1-20260720,bf16,1048576.Testing
make lintexit 0. 105 tests pass acrosstests/config/test_cost_callback.py,sandbox/tests/test_session_state_sync.py,orchestrator/tests/test_session_state_routes.py.New coverage pins the properties that are easy to regress: arity recorded without the schemas, absent-vs-empty
toolsnot collapsing to0, deltas tracked per session rather than globally, a shrinking prompt reading as negative, the metadata lookup happening once and caching its failures, and the endpoint block emitting nulls rather than fabricated defaults before the lookup resolves.The build-attribution lookup is gated on
OPENROUTER_API_KEY, which the egg-litellm container always sets. Outside it — unit tests, tooling that imports the module — the gate means the logging hook never reaches for the network uninvited; without it every test exercising_recordwould fire a real HTTP request.Why this is being flagged as late
This work was reported complete while it existed only in an uncommitted working tree. Nothing was on a branch and nothing was pushed, so none of it was live in the cluster and three downstream things that assume it is live would have silently kept measuring nothing. That is #3692 slice 9's failure class one stage earlier: not shipped-but-inert, but never shipped at all.