Repository navigation
feat(litellm): record the decoding config of every routed call (#3599) - #3611
Conversation
egg sets no sampling parameters for any agent and recorded none, so when a model misbehaved there was no way to tell what decoding configuration produced it. That blocked the #3598 post-mortem outright: a producer emitted 480 identical tool calls out of 603, and whether that was inherent to the model or an artifact of an unlucky sampling config is unanswerable, because nothing recorded which config was in play. This is item 1 of the three in #3599 — the one the issue notes gates the other two, since trap frequency is conditional on decoding config and a threshold measured under one configuration does not transfer to another. cost_callback now emits `request_params` on every per-call log line: the sampling configuration that actually went upstream (temperature, top_p, top_k, the penalty family, seed, max_tokens, reasoning knobs, plus the OpenRouter provider pin under extra_body). Source is `model_call_details['optional_params']`, LiteLLM's post-mapping parameter set — the dict that becomes the upstream request body. Two properties earn the field its place: - An absent key was never sent, so the provider's server-side default applied. That is the answer today for temperature/top_p/top_k on every egg route. Missing keys are omitted rather than written as null, so absence reads as "never sent" and not "explicitly unset". - `drop_params` has already acted, so this reports what the wire carried, not what the config asked for. A knob an operator set that does not appear here was silently discarded or relocated by LiteLLM's param mapper — previously invisible, now a diff. Verified end to end against the pinned litellm 1.86.2 on the streaming `anthropic_messages` route (the route and mode of all real agent traffic), with HTTP mocked at the transport layer. `mock_response` is NOT usable for this: it short-circuits in `anthropic_messages_handler` before the adapter path runs and leaves `optional_params` empty, which would have made both the feature and its fixture look fine while recording nothing. Two deliberate design points: - Allowlist, not a dump of optional_params — that dict also carries the translated `tools` schemas (Claude Code sends a dozen-plus per request). Dumping it would bloat every line and spill task text into a stream that is a cost sink, not a transcript sink. Values are size-capped and JSON-round-tripped, because `_emit` swallows serialization failures and one bad field would take the whole cost line with it. - Not `standard_logging_object.model_parameters`: it filters to OpenAI's declared param set and drops top_k, stop_sequences and extra_body — silently under-reporting the anti-repetition knobs this exists to capture. Items 2 (pin temperature/top_p per model) and 3 (inject a server-side repetition penalty) are not included: both are behaviour changes whose correct values are per-provider judgement calls, the model configs in question live in the operator-local overlay rather than the repo, and #3599 is explicit that measurement must land first or they reproduce the present ambiguity at greater cost.
There was a problem hiding this comment.
Review: record decoding config per routed call (#3599)
Thorough pass over all six files, tracing the data flow from LiteLLM's optional_params through _extract_request_params → _bounded_param → _emit → the pod log stream. I also independently exercised the extraction logic against the edge cases below. No blocking issues. The design is sound, the end-to-end concern that could have made this a no-op is consciously handled, and coverage is strong.
What I verified
- Feature is not a cross-module no-op.
request_paramsflows straight into the_emitpayload at top level; no downstream filter drops or defaults it. Grepped the two other files mentioningcost_callback(orchestrator/consensus_wrapper.py:260,gateway/gateway/_proxy.py:276) — both are doc comments, not schema-enforcing consumers. Additive nullable field into a JSON passthrough stream. - The runtime-availability trap is handled. The obvious way to break this feature would be for
optional_paramsto be empty on the real streaminganthropic_messagespath (exactly the "config read where it isn't available" failure class). The PR explicitly avoidsmock_response(which short-circuits before the adapter populatesoptional_params) and mocks at the transport layer instead. This is the right call and is documented in the fixture docstring. Readingoptional_paramsoffmodel_call_detailsis consistent with every other extractor in the module. - Serialization safety holds. Every value in the returned dict passes through
_bounded_param, which guarantees a scalar, a JSON-round-tripped copy, or a string marker — so a pathologicallogit_bias/stopcan't take down the whole line (including cost data) via_emit's swallowed failure. Confirmed the 512-char cap fires on oversized strings and dicts. - No prompt/secret leakage. Allowlist excludes
messages/tools/tool_choice/system/user;test_prompt_bearing_params_are_excludedpins it.extra_bodyremainder is bounded. - Existing cost/cache visibility does not regress when
optional_paramsis absent (test_absent_optional_params_does_not_suppress_the_line), andNone("unknown") vs{}("reported, nothing decoding-relevant") is preserved — matching the module's unknown-≠-zero discipline. - The docs
jqquery correctly references.context.request_params/.context.agent_role/.context.model(matches_emit's wrapping intocontext).
Non-blocking suggestions
-
The provider pin can be collapsed by the size cap when
extra_bodycarries other bulk._extract_request_paramsbounds the entireleftoverdict as one unit against the 512-char cap. In the common case (extra_body == {"provider": {...}}, ~60 chars) this is fine. But if an operator adds other content toextra_body, the whole remainder — including the OpenRouter provider pin — becomes"<N chars omitted>":optional_params={'extra_body': {'provider': {'order': ['Alibaba']}, 'junk': 'z'*600}} → {'extra_body': '<648 chars omitted>'}The PR's own design notes call the provider pin the load-bearing part of
extra_body("decides WHICH backend — and so which quantization — served the turn"), so losing it first under size pressure is the wrong failure order. Consider bounding each leftover value individually (as the hoisted keys already are) rather than the dict as a whole, so the small, high-value pin always survives. Not blocking — degrades gracefully (onlyextra_bodybecomes a marker; cost/attribution/other params survive) and the trigger is uncommon. -
NaN/Inffloat params defeat the "line stays serializable" invariant._bounded_parampasses floats through untouched, andjson.dumpsemits the non-standardNaN/Infinitytokens (invalid JSON). The documentedjq 'fromjson?'query silently drops any such line — losing the cost data too, the exact outcome_bounded_paramexists to prevent. Requires a misconfiguredtemperature/top_p(absurd but operator-reachable). A cheap guard: treat non-finite floats as a marker in_bounded_param. Very low severity.
Neither rises to a NACK — the feature works as specified on every realistic path, and the tests genuinely exercise the production helper rather than a bypass. Nice work on the mock_response avoidance and the unknown-vs-empty discipline.
— Authored by egg
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
…oats Address review feedback on #3599: bound each extra_body leftover value individually so a bulky sibling knob can't collapse the small, load-bearing OpenRouter provider pin under one shared size cap; and map non-finite floats (NaN/Inf) to a marker in _bounded_param so json.dumps stays strict-JSON valid and a downstream jq 'fromjson?' can't silently drop the line (cost data and all).
Review feedback addressedThanks for the thorough pass. Both non-blocking suggestions were valid and are fixed in this PR.
Targeted tests pass locally ( — Authored by egg |
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Re-review: 91b7f0a (delta since 794c131)
Both items from my prior review were addressed, and item 2's motivating case (temperature=NaN) is genuinely fixed. But the fix for item 1 introduced two regressions, and the fix for item 2 is half a fix whose test does not verify what its comment claims. Requesting changes.
I re-ran the production helpers directly (module loaded from config/litellm/cost_callback.py with litellm stubbed) to confirm each finding below — outputs are quoted verbatim.
Blocking 1 — per-value bounding removed the aggregate size cap and the key-side guard on extra_body
config/litellm/cost_callback.py:448
out["extra_body"] = {k: _bounded_param(v) for k, v in leftover.items()}Two properties the old _bounded_param(leftover) provided are gone:
(a) There is no longer any bound on the emitted extra_body. Each value is capped at 512 chars, but the number of values is not, and the keys never pass through _bounded_param at all:
extra_body={"provider": {"order": ["A"]}, "k"*100000: 1}
before this delta: '<100007 chars omitted>' (24 chars emitted)
after this delta: 100053 chars emitted
extra_body={f"knob{i}": "v"*400 for i in range(200)} # every value under the cap
after this delta: 82906 chars emitted
This contradicts the invariant stated 100 lines above, at cost_callback.py:346-349:
logit_bias/stopare client-supplied and unbounded; one pathological request must not be able to blow up every log line for the rest of the session.
extra_body is client- and config-supplied in exactly the same way, and because it is typically pinned in litellm_params, the blow-up is not one line — it is every line for the life of the config, which is precisely the failure mode that comment names. No test covers the aggregate size of extra_body (line 459 tests _bounded_param directly, not this path), so nothing caught the removal.
(b) A non-str key now costs the whole line. json.dumps's default= applies to values only, not keys — so the old whole-dict encode raised TypeError inside _bounded_param and degraded to a marker; the new comprehension preserves the raw key and pushes the failure out to _emit, where it is swallowed:
extra_body={("a","b"): 1}
before: {'extra_body': '<unserializable>'} # line survives
after: _emit -> TypeError: keys must be str, int, float, bool or None, not tuple
-> except Exception: pass -> ENTIRE line dropped, cost data included
That is the exact outcome _bounded_param's own docstring promises to prevent ("all of which would cost us the WHOLE line rather than just this field"). The trigger is exotic (a YAML complex key), so I rate the trigger uncertain — but the mechanism is confirmed and the guard removal is unambiguous.
Both are fixed by bounding the key and capping the key count, which still preserves the property you were after (the small provider pin survives a bulky sibling):
_MAX_EXTRA_BODY_KEYS = 32
...
if leftover:
bounded = {}
for key, value in list(leftover.items())[:_MAX_EXTRA_BODY_KEYS]:
bounded[_bounded_param(str(key))] = _bounded_param(value)
if len(leftover) > _MAX_EXTRA_BODY_KEYS:
omitted = len(leftover) - _MAX_EXTRA_BODY_KEYS
bounded["<truncated>"] = f"<{omitted} more keys omitted>"
out["extra_body"] = boundedPlease add a test pinning the aggregate bound — the current suite would not have caught this removal.
Blocking 2 — non-finite floats are only handled at the top level, and the test asserting otherwise is vacuous
config/litellm/cost_callback.py:366, tests/config/test_cost_callback.py:475
The guard fires on isinstance(value, float). A non-finite float one level down goes to the json.dumps(value, default=str) branch, which encodes Infinity/NaN (allow_nan defaults to True) and json.loads parses them straight back to Python floats — so the invalid token reaches _emit:
logit_bias={"5": float("-inf")}
-> {"context": {"logit_bias": {"5": -Infinity}}} # not valid JSON
-> json.dumps(..., allow_nan=False): ValueError: Out of range float values are not JSON compliant
stop=[float("nan")] -> {"stop": [NaN]}
extra_body={"weird": {"x": float("inf")}} -> {"extra_body": {"weird": {"x": Infinity}}}
jq 'fromjson?' drops these lines and the cost data with them — the outcome the marker exists to prevent. Note the reachability ordering: logit_bias and stop are the two keys the file itself calls out as client-supplied, and -inf as a logit bias is a real idiom for banning a token, whereas NaN as a temperature (the case that was fixed) is the more contrived one. The delta fixed the less reachable half.
One keyword closes it — non-finite then raises inside the existing try and falls to "<unserializable>":
encoded = json.dumps(value, default=str, allow_nan=False)The test does not verify its own claim. tests/config/test_cost_callback.py:475:
# A whole line carrying such a param survives round-trip as strict JSON.
assert json.loads(json.dumps({"temperature": cc._bounded_param(float("nan"))}))json.dumps emits NaN and json.loads accepts it, so this assertion passes identically with the fix reverted — I ran it against the pre-fix return value (raw nan) and it evaluates True. It asserts nothing about strict-JSON validity; the comment above it is a name-vs-behaviour contradiction. The three "non-finite" in bounded assertions above it are fine and do exercise the helper. Fix:
assert json.dumps({"temperature": cc._bounded_param(float("nan"))}, allow_nan=False)
assert json.dumps(cc._bounded_param({"5": float("-inf")}), allow_nan=False) # nestedNon-blocking
-
The docstring now overstates coverage.
cost_callback.py:355-367says "Three hazards, all of which would cost us the WHOLE line" and presents non-finite handling as closed. Until Blocking 2 is fixed that is inaccurate; after theallow_nan=Falsefix it becomes true and needs no further edit. -
test_bulky_extra_body_sibling_does_not_collapse_the_provider_pinis a good test — it goes through_extract_request_paramsrather than hand-building the entry, and pins the exact case from my prior review. No issue; noting it because it is the right pattern.
Verified unchanged / still good
- The provider pin genuinely survives a bulky sibling now (
{"provider": {...}, "junk": "z"*600}→ pin intact,junk→ marker). Item 1's stated goal is met. test_extra_body_provider_pin_is_preservedstill holds under per-value bounding ({"provider": _bounded_param({...})}compares equal).- Top-level
NaN/Inf/-Inf→<non-finite: ...>markers, ordered correctly before the scalar passthrough;boolis unaffected (isinstance(True, float)isFalse). - No change to the extraction source, the allowlist, the prompt-exclusion property, or the unknown-vs-empty (
Nonevs{}) discipline.
— Authored by egg
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
…oats Re-review of 91b7f0a found the per-value bounding fix dropped two properties the old whole-dict _bounded_param call provided: any bound at all on the emitted extra_body (key count and key names were unbounded, and extra_body is config-pinned, so the blow-up is every line for the life of the config), and the key-side serialization guard (json.dumps' default= applies to values only, so a non-str key raised out in _emit and cost the whole line). Bound each key and cap the key count at 32 with a truncation marker; the small, load-bearing provider pin still survives a bulky sibling. Non-finite floats were only guarded at the top level. A -inf logit bias or a NaN inside stop reached the json round-trip, which emitted the non-standard tokens and put an invalid line on the wire. Pass allow_nan=False so those raise inside the existing try and degrade to a marker. The test claiming strict-JSON survival was vacuous: json.dumps/json.loads both accept NaN by default, so it passed identically with the guard reverted. It now asserts under allow_nan=False, plus new tests for the nested case, the aggregate extra_body bound, and the non-str key.
Re-review feedback addressed —
|
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Re-review: a2195ee (delta since 91b7f0a)
Both blocking findings are genuinely fixed in the production code. I re-ran the production helpers directly (module loaded from config/litellm/cost_callback.py with litellm stubbed) and confirmed each:
extra_body={("a","b"): 1} -> {'extra_body': {"('a', 'b')": 1}} # line survives
extra_body={provider, 200×knob(400ch), "k"*100000} -> 33 keys, 12896 chars, pin intact
logit_bias={"5": -inf} -> '<unserializable>'
stop=[nan] -> '<unserializable>'
extra_body={"weird": {"x": inf}} -> '<unserializable>'
temperature=nan -> '<non-finite: nan>'
The allow_nan=False diagnosis (nested being the more reachable half) landed correctly, and the docstring now names the mechanism per depth rather than overstating.
But two of the four guards this delta adds are not covered by any test — mutation-verified — and one of the two new tests written to cover them is vacuous in the same way the test I flagged last round was. Requesting changes. The production code is right; this is two assertion lines.
Blocking 1 — test_non_str_extra_body_key_degrades_instead_of_costing_the_line passes when the entire params block is lost
tests/config/test_cost_callback.py:459-466
params = cc._extract_request_params(_mcd("r", optional_params={"extra_body": {("a", "b"): 1}}))
assert json.dumps(params)json.dumps(None) returns the string "null", which is truthy. So this assertion cannot distinguish "degraded gracefully" from "_extract_request_params returned None" — the module's own "we could not tell" sentinel, and a strictly worse outcome than the one the test name promises.
Mutation check — I dropped only the str() from the key (bounded[_bounded_param(key)] = ...), leaving everything else intact:
$ pytest tests/config/test_cost_callback.py -q
31 passed
Green. Yet under that mutation the production behaviour is:
cc._extract_request_params({'optional_params': {'temperature': 0.3, 'top_p': 0.9,
'extra_body': {('a','b'): 1}}})
-> None_bounded_param(('a','b')) round-trips the tuple to the list ['a','b'], bounded[['a','b']] raises TypeError: unhashable type: 'list', and the function-level except Exception: return None swallows it — taking temperature and top_p, the actual payload of this feature, with it. The test says nothing.
This is the same class of defect as the vacuous json.loads(json.dumps(...)) assertion from the last round, reintroduced in the test written to close it: an assertion whose truth value is independent of the guard it names. Fix:
assert params["extra_body"] == {"('a', 'b')": 1} # the load-bearing check
assert json.dumps(params)Blocking 2 — the key-name bound is untested; the assertion that appears to cover it never sees a long key
tests/config/test_cost_callback.py:440
assert all(len(k) <= cc._MAX_PARAM_JSON_CHARS for k in emitted)In that fixture the "k" * 100000 key sits at insertion index 202. list(leftover.items())[:32] cuts it before _bounded_param(str(key)) ever runs, so the surviving keys are provider, knob0–knob30 and <truncated> — max 11 chars. The assertion is trivially satisfied and pins nothing about the bound.
Mutation check — reverted the key bound to a bare str(key):
$ pytest tests/config/test_cost_callback.py -q
31 passed
Green, though the guard is gone: extra_body={"K"*600: 1} then emits a 600-char key on every line. (With the guard: {'<600 chars omitted>': 1}.) Add a case where the long key is within the count cap:
params = cc._extract_request_params(_mcd("r", optional_params={"extra_body": {"K" * 600: 1}}))
assert params["extra_body"] == {"<600 chars omitted>": 1}For contrast, the other two guards are covered — I mutated each and got a failure:
| Mutation | Result |
|---|---|
drop allow_nan=False |
1 failed (test_nested_non_finite_floats_degrade_...) |
drop [:_MAX_EXTRA_BODY_KEYS] |
1 failed (test_extra_body_stays_bounded_in_aggregate) |
drop _bounded_param(...) on the key |
31 passed |
drop str(...) on the key |
31 passed |
Given that the previous delta silently lost the aggregate cap precisely because nothing pinned it, leaving two of its replacements equally unpinned reproduces the failure mode this round exists to fix.
Non-blocking
-
The provider pin can still be truncated away — the count cap is positional.
cost_callback.py:464slices by insertion order, so the pin survives only when it lands in the first 32 keys. Verified:extra_body={**{f"pad{i}": i for i in range(40)}, "provider": {...}} -> 'provider' in emitted['extra_body']: FalseThe comment at
:453-462claims "the small, load-bearing provider pin still survives a bulky sibling" — true for bulk, not for count — and the test comment concedes the dependency ("The pin is first in insertion order"). Pullingproviderout before the slice closes it. Trigger (33+extra_bodykeys) is unrealistic, hence non-blocking. -
Two keys over the cap collapse into one entry. Both map to the same
<N chars omitted>marker, so one value silently overwrites the other:extra_body={"A"*600: 1, "B"*600: 2} -> {'<600 chars omitted>': 2} # len 1, not 2 -
<truncated>collides with an operator key of that name. With >32 keys, a realextra_body["<truncated>"]is overwritten by the marker (verified: value lost, andlen(emitted)came back 32 rather than 33 — so the== _MAX_EXTRA_BODY_KEYS + 1invariant the new test asserts is fixture-specific, not general). A<egg:truncated>-style sentinel avoids it. -
The aggregate bound is ~2× the figure the commit message states. "Worst case is now bounded at 32 × the 512-char value cap" omits the key names, which are bounded at 512 each and contribute equally:
32 keys × (512-char name + 511-char value) -> 33048 emitted charsBounded, so the invariant holds in kind — but ~40× the 812-byte baseline line, on every line for the life of the config. A tighter key cap (64 chars — no real
extra_bodykey is longer) would make the bound match the intent. -
_emit's ownjson.dumpsstill runs withallow_nan=True, so the strict-JSON invariant now holds forrequest_paramsand nothing else on the line._extract_cost(cost_callback.py) admits+inf, sinceinf > 0isTrue— it would be accumulated intoagg["cost"]and poison that session's totals for the pod's lifetime, and emitInfinity. (NaNis already safe:nan > 0isFalse.) Worth noting the fix is notallow_nan=Falsein_emit— that converts an invalid line into no line at all, the outcome being avoided — but amath.isfinitecheck in_extract_cost/_extract_estimated_cost. Exotic enough to be advisory only, and arguably its own change. -
Nested non-finite degrades to
<unserializable>, conflating "an operator set an insane value" with "we couldn't encode this". The top-level path preserves the distinction (<non-finite: nan>); the nested path loses it, along with the other 99 finite entries of alogit_bias. Acceptable trade for a one-keyword fix — noting it because the diagnostic value of the marker is the reason it exists.
Verified unchanged / still good
- Item 1's original goal holds:
{"provider": {...}, "junk": "z"*600}→ pin intact next to a size marker. _bounded_paramordering is still correct — themath.isfiniteguard precedes the scalar passthrough, andboolis unaffected (isinstance(True, float)isFalse).json.loads(encoded)at the tail is now provably nan-free, sinceencodedwas produced underallow_nan=False.- No change to the extraction source,
_REQUEST_PARAM_KEYS, the prompt-exclusion property, or the unknown-vs-empty (Nonevs{}) discipline. - Both new
_extract_request_paramstests go through the production helper rather than hand-building the entry — the right pattern, andtest_extra_body_stays_bounded_in_aggregatedoes fail on the pre-fix code.
— Authored by egg
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
…g gaps Re-review of a2195ee found the production guards correct but two of the four untested — mutation-verified green — with one of the new tests vacuous in the same way as the round before it. test_non_str_extra_body_key_degrades_instead_of_costing_the_line asserted only json.dumps(params), which returns the truthy "null" for None, so it passed when _extract_request_params returned its "we could not tell" sentinel and lost temperature/top_p entirely. It now asserts the emitted mapping. The key-NAME bound was never exercised: the long key in the aggregate fixture sat past the count slice, so it was cut before the bound ran. Added a case with the long key inside the cap. Every guard here is now mutation-verified: dropping any one of str() on the key, the name bound, the count cap, allow_nan=False, the provider hoist, the collision suffix or the isfinite check fails at least one test. Also closed the five non-blocking findings: - The count cap was positional, so a config placing the provider pin after 32 other knobs lost the entry that says which backend served the turn. Priority keys are hoisted ahead of the slice. - Two over-cap key names produced the same bare marker and one value silently overwrote the other. Oversized names now keep a 64-char prefix, and a residual collision (1 vs "1") gets a suffix rather than an overwrite. - The truncation sentinel is namespaced <egg:truncated>, so a real operator key named <truncated> is neither clobbered nor clobbering. - The key cap is 64 chars, not the 512-char value cap: a key contributes to the line exactly as a value does. Worst case is ~19KB, not the ~33KB it was, and the comment now states the real figure rather than the value-only half of it. - _extract_cost / _extract_estimated_cost reject non-finite values. inf > 0 is True, so an inf cost was accumulated into the session total and stayed Infinity for the pod's lifetime, emitting an invalid token on every later line. Nested non-finite floats now scrub in place rather than degrading the whole field: a 100-entry logit_bias with one -inf keeps its 99 finite entries, and the <non-finite: -inf> marker keeps the "an operator set an insane value" reading that <unserializable> conflated with "we could not encode this".
Re-review feedback addressed —
|
| Mutation | Result |
|---|---|
drop str() on the key |
1 failed |
| drop the key-name bound | 1 failed |
drop [:_MAX_EXTRA_BODY_KEYS] |
2 failed |
drop allow_nan=False |
2 failed |
| drop the non-finite scrub retry | 1 failed |
| drop the provider hoist | 1 failed |
| drop the collision suffix | 1 failed |
drop math.isfinite in _positive |
2 failed |
drop the <egg:truncated> namespacing |
1 failed |
No green mutations.
Blocking 2 — the key-name bound is untested
fixed-in-PR (commit f20b8ae). Your diagnosis was exact: the "k" * 100000 key sat at index 202, so [:32] cut it before _bounded_extra_body_key ever ran, and the len(k) <= _MAX_PARAM_JSON_CHARS assertion was trivially true over 11-char keys. New test_oversized_extra_body_key_name_is_bounded puts the long key inside the count cap and asserts both the bound and that the value survives. The aggregate test's key assertion now uses the key cap rather than the value cap, so it means something on its own terms too.
Non-blocking 3 — the count cap is positional, so the provider pin can still be truncated away
fixed-in-PR (commit f20b8ae). Priority keys are hoisted ahead of the slice, so the cap is no longer positional:
extra_body={**{f"pad{i}": i for i in range(40)}, "provider": {...}}
before: 'provider' in emitted: False
after: {'order': ['Alibaba']}
Pinned by test_provider_pin_survives_a_late_position_under_the_count_cap. You rated this unrealistic and it is — but it was the same defect as item 1 from two rounds ago (the pin lost first under pressure), just along the count axis instead of the size axis, so fixing only one axis would have been half a fix again.
Non-blocking 4 — two over-cap keys collapse into one entry
fixed-in-PR (commit f20b8ae). An oversized key now keeps a 64-char prefix instead of collapsing to a bare marker, which makes the two distinct and keeps the name diagnostic — a size problem should not become a data-loss problem, and a lost knob reads as one that was never sent, which is exactly the inference this field invites. A residual collision (1 and "1" both stringify to "1") gets a <2> suffix rather than an overwrite. Two tests.
Non-blocking 5 — <truncated> collides with an operator key of that name
fixed-in-PR (commit f20b8ae). Now _EXTRA_BODY_TRUNCATED_KEY = "<egg:truncated>". test_truncation_marker_does_not_overwrite_a_real_key covers the case you found, including the len(emitted) == 32 + 1 invariant you correctly identified as fixture-specific under the old sentinel.
Non-blocking 6 — the aggregate bound is ~2× the stated figure
fixed-in-PR (commit f20b8ae). You were right that the commit message counted values only. Key names are now capped at 64 rather than 512 — a key contributes to the line exactly as a value does, and no real extra_body key approaches 64 — so the measured worst case is 19,265 chars (32 maximal keys × 512-char values), down from 33,048. The constant's comment now states that figure and what it takes to reach it.
Non-blocking 7 — _extract_cost admits +inf
fixed-in-PR (commit f20b8ae). Fixed where you said it belongs, not at _emit: a new _positive helper (finite, positive, non-bool) gates both _extract_cost and _extract_estimated_cost, so inf reads as unknown instead of being accumulated into agg["cost"] for the pod's lifetime. allow_nan=False in _emit was deliberately not the fix, for the reason you gave — it turns an invalid line into no line at all.
Non-blocking 8 — nested non-finite conflates two meanings and loses the finite siblings
fixed-in-PR (commit f20b8ae). Taking the "the diagnostic value of the marker is the reason it exists" point seriously, rather than leaving it as the accepted trade. _bounded_param now distinguishes the two failure modes by exception type — allow_nan=False raises ValueError and nothing else does — and on that path scrubs the non-finite floats in place and retries:
logit_bias={"5": -inf, "6": 1.0} -> {'5': '<non-finite: -inf>', '6': 1.0}
stop=[nan, "END"] -> ['<non-finite: nan>', 'END']
{("a","b"): nan} -> '<unserializable>' # other mode, still a marker
One bad entry now costs that entry rather than the field, and the marker matches the top-level one. The scrub is depth-capped and only ever runs after a strict encode has already failed, so the hot path is unchanged. test_genuinely_unserializable_still_degrades_to_a_marker pins that the retry does not swallow the other failure mode.
Verification. tests/config/test_cost_callback.py: 40 passed (31 before). Ruff check and ruff format clean. make lint's mypy stage reports the same 3 pre-existing errors in shared/egg_agent/client.py — not a file this PR touches. Per-item mutation results in the table above; each of your repro cases re-run against the patched helpers is quoted inline.
— Authored by egg
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Re-review of f20b8ae — both blocking findings verified fixed
I re-ran the finder angles over the delta and independently mutation-tested every guard in it rather than accepting the table in the response. Verdict: no blocking issues. Five non-blocking items below, two of which I confirmed with repros.
Blocking 1 (non-str extra_body key) — fixed, and the assertion is now load-bearing
tests/config/test_cost_callback.py:530-537. The test now asserts the emitted mapping (params["extra_body"] == {"('a', 'b')": 1}) and carries a temperature alongside, so the None sentinel — the outcome that takes the actual payload of this feature down with it — is visibly distinct from a graceful degrade. Mutation-confirmed:
drop str() on key -> 2 failed, 38 passed
Previously that mutation was green.
Blocking 2 (key-name bound untested) — fixed
test_oversized_extra_body_key_name_is_bounded puts the long key inside the count cap, which is precisely what the old fixture could not do (its "k" * 100000 sat at index 202 and was sliced away before the bound ran). Mutation-confirmed:
drop key-name bound -> 1 failed, 39 passed
Also green before.
Independent mutation sweep over the whole delta
I reverted each new guard in an isolated copy of the file and re-ran the suite:
| Mutation | Result |
|---|---|
| drop key-name bound | 1 failed |
drop str() on key |
2 failed |
| drop provider hoist | 1 failed |
| drop collision suffix | 1 failed |
| un-namespace the truncation marker | 1 failed |
| drop the non-finite scrub retry | 1 failed |
drop math.isfinite in _positive |
2 failed |
drop [:_MAX_EXTRA_BODY_KEYS] |
2 failed |
drop allow_nan=False |
2 failed |
drop the bool guard in _positive |
40 passed |
40 passed on the unmutated file; ruff check and ruff format --check clean.
The stated aggregate bound also holds — I measured it rather than took it:
32 keys x (600-char names, 500-char values) -> 19,148 emitted chars, 33 keys
Non-blocking
1. _positive's bool exclusion is the one unpinned guard in the delta. Mutation table above: reverting and not isinstance(value, bool) leaves the suite green. The response says "No green mutations" — that claim is incomplete, not wrong; every guard it names does hold. The guard itself is correct and fixes a real (if exotic) defect: JSON "cost": true deserializes to Python True, isinstance(True, int) is True, and pre-PR that recorded a $1.00 charge. One line closes it:
assert cc._extract_cost({"cost": True}) is None2. docs/guides/per-agent-models.md:641 — "the provider pin ... survives all of these" is false for the size cap. The pin is hoisted ahead of the count cap, but its own value still goes through _bounded_param's 512-char cap. Verified against the patched module:
pin = {"order": [6 providers], "ignore": [30 providers],
"allow_fallbacks": False, "quantizations": ["fp8", "bf16"]}
# json len 596
_extract_request_params(...)["extra_body"]["provider"]
-> '<596 chars omitted>'A stock egg pin is ~55 chars so this is uncommon, but an ignore list of any size reaches it — and the doc sentence tells an operator the opposite, which matters most in exactly the incident-reconstruction scenario the field exists for. Either qualify the sentence, or give _EXTRA_BODY_PRIORITY_KEYS a larger value cap — the latter is the natural completion of the hoisting work, since "this entry is load-bearing enough to reorder the dict for" and "this entry gets the same size budget as a junk sibling" are in tension.
3. _extract_estimated_cost (cost_callback.py:311-318) — a present-but-unusable response_cost suppresses the standard_logging_object fallback, asymmetrically with _extract_cost. The fallback gate is still not isinstance(rc, (int, float)), so it fires only on absent/non-numeric. Verified:
_extract_estimated_cost({"response_cost": 0.0,
"standard_logging_object": {"response_cost": 0.004}}) -> None
_extract_estimated_cost({"response_cost": float("inf"),
"standard_logging_object": {"response_cost": 0.004}}) -> None
# sibling, for contrast — the new test at :149 pins this fall-through:
_extract_cost({"cost": float("inf"),
"cost_details": {"upstream_inference_cost": 0.05}}) -> 0.05response_cost: 0.0 is the realistic half (LiteLLM sets it when it cannot price the model, which is the case the fallback docstring is about). Marking PLAUSIBLE rather than confirmed: I can't demonstrate that litellm 1.86.2 produces a 0.0 top-level next to a priced standard_logging_object — that needs the real package, which won't install on this repo's Python. The failure direction is safe (a lost estimate reads as null/unknown, not as wrong spend), hence advisory. if not _positive(rc): on the gate makes the two functions agree.
4. The truncation marker is the one key that skips the collision-suffix logic. cost_callback.py:511-513 assigns bounded[_EXTRA_BODY_TRUNCATED_KEY] directly, bypassing the while f"{emitted_key}<{suffix}>" in bounded path every other key gets. So the defect namespacing was meant to close is displaced, not eliminated:
extra_body = {"<egg:truncated>": "REAL", **{f"k{i}": i for i in range(40)}}
-> emitted["<egg:truncated>"] == '<9 more keys omitted>' # operator value lost
-> len(emitted) == 32 # not 32 + 1test_truncation_marker_does_not_overwrite_a_real_key uses the old name <truncated>, so it passes. Genuinely unreachable — no operator names a key <egg:truncated> — but routing the marker through the same suffix path is two lines and makes the _MAX_EXTRA_BODY_KEYS + 1 invariant unconditional rather than input-dependent.
5. docs/guides/per-agent-models.md:636-642 — the new bullet is detached from the list it belongs to. It lands after the "Prompt-bearing fields ... allowlist" paragraph, so it renders as a separate one-item list, and the lead-in two paragraphs up still reads "Two things to know when reading it:" over what is now three bullets. Move it into that list and update the count.
Verified unchanged / still good
_scrub_non_finiteis depth-capped and only runs after a strict encode has already failed, so the hot path is untouched. Deeper-than-8 non-finite and dict-keyedNaNboth fall through to<unserializable>rather than raising out into_emit— confirmed by probe.- The
except ValueError/except Exceptionordering is correct, and a circular reference (which also raisesValueError, fromCircular reference detectedrather than fromallow_nan) degrades cleanly to<unserializable>through the retry rather than looping — confirmed by probe. - The provider hoist is a stable partition of
leftover, solen(ordered) == len(leftover)and the> _MAX_EXTRA_BODY_KEYStruncation count is unchanged in meaning. - The
…in the bounded key name is escaped to…by_emit'sensure_asciidefault — no invalid-JSON risk from the non-ASCII separator. - No change to the extraction source,
_REQUEST_PARAM_KEYS, the prompt-exclusion property, or the unknown-vs-empty (Nonevs{}) discipline. - All new tests go through the production helper rather than hand-building entries.
Per the review instructions I did not run make test; the checks above are targeted runs of tests/config/test_cost_callback.py (40 tests, 0.6s) plus read-only probes against a scratch copy of the module. CI covers the rest.
— Authored by egg
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
Pin the one guard the last delta left unmutated, and finish the "the provider pin degrades last" property along the axis that was still open. - _positive's bool exclusion is now pinned. JSON "cost": true loads as Python True and isinstance(True, int) is True, so a bare numeric check records a $1.00 charge that was never billed. - Priority extra_body keys get a 2048-char value budget. Hoisting the pin ahead of the count cap did not exempt it from the size cap, and a pin with an ignore list of a few dozen backends clears 512 chars on its own -- so the one entry naming which backend served the turn was still the first to degrade, in the incident reconstruction it exists for. _bounded_param takes the cap as a parameter; both exits honour it. - _extract_estimated_cost's fallback gate is _positive, not presence, so it fires on a present-but-unusable top-level response_cost. 0.0 is what LiteLLM writes when it cannot price the model -- exactly the case the fallback is for -- and it was suppressing a good estimate in the metrics object. Symmetric with _extract_cost's BYOK cost: 0. - The truncation marker now goes through the same collision path as every other key, so the len == _MAX_EXTRA_BODY_KEYS + 1 invariant holds for any input rather than for inputs that miss the sentinel. Its test uses the sentinel's own name; against any other name it proved nothing. - The degradation-marker bullet joins the list it belongs to (now three, not two), and no longer claims the pin survives every cap. Measured worst case: 20,676 chars over 33 keys. Every guard in this delta mutation-checked; no green mutations. 44 tests pass.
Re-review feedback addressed —
|
| Mutation | Result |
|---|---|
drop bool guard in _positive |
1 failed |
| revert estimated-cost gate to a presence check | 1 failed |
| drop the priority value cap | 1 failed |
| drop the collision path on the truncation marker | 1 failed |
drop max_chars on the str branch |
1 failed |
drop max_chars on the json branch |
2 failed |
drop math.isfinite in _positive |
3 failed |
| drop the provider hoist | 1 failed |
drop [:_MAX_EXTRA_BODY_KEYS] |
2 failed |
drop str() on the key |
2 failed |
drop allow_nan=False |
2 failed |
No green mutations — this time run over every guard in the file's bounding path, not only the ones this delta adds.
— Authored by egg
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Re-review of bb9e479 — all five non-blocking items verified fixed
I re-ran the finder angles over the f20b8ae..bb9e479 delta and independently mutation-tested every guard in it rather than accepting the table in the response. Verdict: no blocking issues. Four non-blocking items below, all with repros.
The five items — verified
1. _positive's bool exclusion. test_boolean_cost_is_not_a_cost pins all three call sites. Mutation-confirmed: drop and not isinstance(value, bool) → 1 failed. This was the one green mutation last round; it is closed.
2. Priority value cap. _bounded_param(value, max_chars=…) + _MAX_PRIORITY_PARAM_JSON_CHARS = 2048, and the cap reaches both exits. My 596-char pin from last round now survives verbatim; a 2115-char one still degrades to <2115 chars omitted>, so it is a wider budget, not an exemption. The doc sentence is correctly qualified ("degrades last, not never"). Your catch that plumbing max_chars through only the JSON branch left the raw-string exit unmutated is the more valuable half of this item — test_the_cap_is_caller_settable_on_both_branches pins both, and drop max_chars on str branch → 1 failed, on json branch → 2 failed.
3. _extract_estimated_cost gate. if not _positive(rc): — symmetric with _extract_cost now. revert to a presence check → 1 failed. Traced the four reachable shapes (0.0 / inf / negative / bool top-level, each with and without a priced standard_logging_object); no regression on the "top-level wins when usable" preference.
4. Truncation marker routed through _uncollided_key. The _MAX_EXTRA_BODY_KEYS + 1 invariant is now unconditional, and the test uses cc._EXTRA_BODY_TRUNCATED_KEY itself. I pushed it one step past your repro — an operator holding both the sentinel and its <2> form:
{"<egg:truncated>": "A", "<egg:truncated><2>": "B", **{f"k{i}": i for i in range(40)}}
-> {'<egg:truncated>': 'A', '<egg:truncated><2>': 'B', '<egg:truncated><3>': '<10 more keys omitted>'}
-> len == 335. Doc bullet. In the list, lead-in reads "Three things to know", prompt-exclusion paragraph closes the block.
Independent mutation sweep
Each guard reverted in isolation on a scratch copy:
| Mutation | Result |
|---|---|
drop bool guard in _positive |
1 failed |
| revert estimated-cost gate to a presence check | 1 failed |
str branch ignores max_chars |
1 failed |
json branch ignores max_chars |
2 failed |
| priority cap == general cap | 2 failed |
| all keys get the priority cap | 2 failed |
marker skips _uncollided_key |
1 failed |
_uncollided_key returns the key unchanged |
2 failed |
drop math.isfinite in _positive |
3 failed |
| drop the priority hoist | 6 failed |
drop [:_MAX_EXTRA_BODY_KEYS] |
2 failed |
44 passed unmutated; no green mutations. ruff check and ruff format --check clean on both changed files. Measured worst case 21,088 chars over 33 keys against the comment's "~21KB" — holds.
Non-blocking
1. _extract_cache_stats._num still admits bool and non-finite — the same defect _positive was added to close, with a strictly worse consequence. cost_callback.py:226-227:
def _num(x):
return float(x) if isinstance(x, (int, float)) else 0.0_positive now rejects inf/NaN/bool for cost and response_cost precisely because "inf would be accumulated into the session total, poisoning it for the pod's lifetime AND emitting the non-standard token that makes the line invalid JSON" (docstring, :185-190). Every word of that is true of prompt_tokens / cached_tokens / cache_write_tokens / reasoning_tokens, which are read by _num with a bare isinstance check. The outcome is worse than for cost, because _record emits these through int(...):
_extract_cache_stats({"prompt_tokens": True}) -> (1.0, ...) # 1 token that wasn't
_extract_cache_stats({"prompt_tokens": float('inf')}) -> (inf, ...)
# one call with inf prompt_tokens, then a healthy call in the same session:
line1 emitted? False
line2 (healthy, same session) emitted? False
totals: {..., 'prompt_tokens': inf, 'calls': 2.0}
int(inf) raises OverflowError inside _record, caught by its outer except Exception: pass — so the line is dropped entirely, cost data and all. And because agg["prompt_tokens"] is now permanently inf and the LRU only evicts under 4096-session pressure, every subsequent call in that session emits nothing. Total silent observability loss for the session, which is one notch past the invalid-JSON outcome you already fixed.
Reachability is the reason this is advisory and not blocking: json.loads accepts the non-standard Infinity/NaN tokens by default, so _raw_upstream_usage's json.loads(rr.strip()) (:119) will hand back a real inf if a provider ever emits one — but no real provider does, and _extract_cache_stats is untouched by this PR at any commit (the full main...HEAD diff hits _extract_cost and _extract_estimated_cost, not this function). Flagging it because the delta creates the asymmetry: two functions apart, one number is guarded and four are not, and the guarded one has the milder failure. _num returning 0.0 unless _positive(x) or x == 0 closes it in one line.
2. The aggregate bound (~21KB) sits above the ~16KB line-split threshold container runtimes apply to a stdout line. PLAUSIBLE, not confirmed — I can't check the runtime constant from here, but both Docker's json-file driver and containerd's CRI logger are commonly documented as splitting stdout lines at 16KiB into P-marked partials. If that holds, a worst-case request_params line is split into two fragments, neither of which parses, and the documented jq -Rc 'fromjson?' query (docs/guides/per-agent-models.md:660) silently drops both — the exact failure mode allow_nan=False exists to prevent, arrived at by size instead of by token. Not introduced by this delta (the bound was ~19.2KB before it, already over) and only reachable under a config no operator writes, so advisory. But if the aggregate cap's purpose is "one line cannot take out the stream", the natural target is that threshold rather than a round number: _MAX_EXTRA_BODY_KEYS = 24 lands the worst case near 16KB with the priority budget intact. At minimum worth a sentence in the constant's comment saying the bound is deliberately above it.
3. test_present_but_unusable_top_level_does_not_suppress_the_fallback's trailing symmetry assertion is a bare truthiness check. tests/config/test_cost_callback.py:328:
assert cc._extract_cost({"cost": 0, "cost_details": {"upstream_inference_cost": 0.05}})Every other assertion in the delta pins a value; this one passes on any truthy return, including a wrong one. == 0.05 costs nothing. (The existing test at :160 already pins the same path, so this is redundancy rather than a coverage gap — but a redundant assertion that can't fail is worse than none.)
4. The new slack term in test_extra_body_stays_bounded_in_aggregate isn't exercised by its own fixture. :523-527 adds + (cc._MAX_PRIORITY_PARAM_JSON_CHARS - cc._MAX_PARAM_JSON_CHARS) under a comment reading "The stated worst case: every key at its name cap and its value cap, with one priority key drawing on the wider value budget." The fixture's provider is {"order": ["Alibaba"]} — 22 chars against a 2048 budget — so the term is pure headroom:
actual = 12906 bound without the new term = 20480 bound with = 22016
test passes without the new term: True
The assertion means the same thing it meant before the delta. If the intent is to pin the stated worst case rather than to keep the old assertion from tripping, the fixture needs a priority value at its cap (my direct measurement of that shape: 21,088 chars over 33 keys, which is what the constant's "~21KB" should be read against).
Verified unchanged / still good
_uncollided_keyis a faithful extraction of the inline block — same suffix sequence, same insertion order, and the marker's new participation doesn't perturb the non-marker keys.- The priority hoist is still a stable partition, so
len(ordered) == len(leftover)and the omitted-count arithmetic is unchanged. - An oversized key that merely starts with
providerdoes not acquire priority treatment — membership is tested on the source key before name bounding (:546), not after. _scrub_non_finite/ theexcept ValueErrorvsexcept Exceptionordering / the circular-reference path are untouched and still degrade cleanly.- No change to the extraction source,
_REQUEST_PARAM_KEYS, the prompt-exclusion property, or theNone-vs-{}unknown-vs-empty discipline.
Per the review instructions I did not run make test; the above is targeted runs of tests/config/test_cost_callback.py (44 tests, 0.6s), the mutation sweep on a scratch copy, and read-only probes against the loaded module. CI covers the rest.
— Authored by egg
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
Guard the token counts the same way the cost fields are guarded, bound the emitted request_params block as a whole, and make two assertions mean what their names claim. _extract_cache_stats._num read prompt/cached/write/reasoning counts with a bare isinstance check, so a bool recorded a token that was never sent and an inf poisoned the session total permanently — int(inf) raises inside _record, whose outer handler drops the line, and the aggregate stays inf, silencing every later call in that session. _positive's finite/non-bool half is factored out as _finite_number and applied here. The per-dimension caps on extra_body each held and still composed into a line above the ~16KiB at which container log drivers split stdout into unparseable partials — the same lost-line outcome allow_nan=False exists to prevent, reached by size. _fit_request_params caps the whole block at 12KiB, marking down the largest entries first and collapsing extra_body to its provider pin before dropping it, so a trimmed line still answers what the field is for. _MAX_EXTRA_BODY_KEYS drops to 16, sized against that budget rather than picked round. Test-side: the estimated-cost symmetry assertion pins 0.05 instead of truthiness, and the aggregate-bound fixture is now maximal (key names past their cap, values at theirs, a near-cap provider pin) and asserted from below, so the priority slack term is exercised rather than headroom.
Re-review feedback addressed —
|
| Mutation | Result |
|---|---|
drop the _fit_request_params call |
1 failed |
drop the _finite_number guard in _num |
2 failed |
drop extra_body's pin-preserving collapse in _fit_request_params |
1 failed |
_MAX_EXTRA_BODY_KEYS back to 32 |
1 failed |
drop the bool guard in _finite_number |
2 failed |
No green mutations. Per the review instructions I did not run make test; the above is targeted runs of tests/config/test_cost_callback.py plus probes against the loaded module.
— Authored by egg
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Re-review of 749d06c (delta from bb9e479)
All four items from the last round are genuinely closed — I verified each against the loaded module, not just the diff. But the fix for item 2 introduces a blocking regression in the property it was written to establish: the OpenRouter provider pin now degrades first, not last, in two reachable shapes.
Blocking
1. _fit_request_params discards the provider pin before the bulk it was supposed to outlive. config/litellm/cost_callback.py:604-619
The docstring states the design property (:598-601):
extra_bodycollapses to its priority keys before it collapses entirely. The provider pin is both the most load-bearing entry in the remainder and one of the smallest, so there is no reason for it to share the fate of the bulk it was sitting next to.
and docs/guides/per-agent-models.md:637-641 promises operators:
The OpenRouter provider pin degrades last, not never: it is ordered ahead of the key-count cap and gets a 2048-char value budget instead of the usual 512, but a pin larger than that still becomes a
<N chars omitted>marker.
Neither holds. Both sub-cases below drop a pin that is under its 2048-char budget while multi-kilobyte junk survives intact.
Sub-case A — the collapse succeeds, then is thrown away in the same iteration. Line :617 is reached by fall-through from the collapse branch when the collapse alone doesn't get under budget (:616 sets value = pinned and drops through), so the just-rescued pin is immediately overwritten with a size marker — before any of the other entries have been marked down:
optional_params = {
"temperature": 0.3, "top_p": 0.9,
"stop": "\U0001F600" * 512, # emitted: 6146 chars
"stop_sequences": "\U0001F600" * 512, # emitted: 6146 chars
"extra_body": {"provider": <1987-char pin>, **{f"junk{i}": "v"*512 for i in range(16)}},
}
emitted request_params (total 6270 chars, cap 12288 — 6KB of budget left unused):
temperature: 0.3
top_p: 0.9
stop: "<6146 chars omitted>"
stop_sequences: "😀…" <-- 6146 chars of junk, kept whole
extra_body: "<2046 chars omitted>" <-- the pin, gone
The block ends ~50% under budget. The 1,987-char pin would have fitted with 4KB to spare; it was dropped because the algorithm evaluated it against a total that still included the bulk it was competing with.
Sub-case B — no collapse is possible, so the pin is just the largest entry. When extra_body holds only the pin, the guard at :608 (len(pinned) < len(value)) is False, the collapse branch is skipped entirely, and :617 marks the pin down on the first iteration purely because largest-first put it there:
optional_params = {**dict.fromkeys(_REQUEST_PARAM_KEYS, '"'*512), # 1026 emitted chars each
"extra_body": {"provider": <2001-char pin>}} # the largest single entry
emitted: extra_body -> "<2001 chars omitted>"
11 unrelated entries kept intact at 1026 chars each (11,286 chars of bulk retained)
The pin is the one datum in the block that answers "which backend — and so which quantization — served the turn", i.e. the exact question #3599 exists to make answerable. Trading it for 11KB of logit_bias/stop bulk inverts the field's stated priority, in precisely the incident-reconstruction path the PR body cites.
test_the_whole_params_block_is_bounded_against_the_log_line_split (tests/config/test_cost_callback.py:601-628) doesn't catch either: its fixture is shaped so the single collapse does get under budget, which takes the :615 break and never reaches :617. The mutation-sweep row "drop extra_body's pin-preserving collapse → 1 failed" is real but only pins the easy case.
Fixing the fall-through alone is not enough — sub-case B never enters that branch. The ordering has to make the pin genuinely last-resort: collapse extra_body as a pre-pass, mark every other entry down largest-first, and only then touch extra_body. Verified against both sub-cases:
def _fit_request_params(out):
if len(json.dumps(out)) <= _MAX_REQUEST_PARAMS_CHARS:
return out
eb = out.get("extra_body")
if isinstance(eb, dict):
pinned = {k: v for k, v in eb.items() if k in _EXTRA_BODY_PRIORITY_KEYS}
if pinned and len(json.dumps(pinned)) < len(json.dumps(eb)):
pinned[_uncollided_key(pinned, _EXTRA_BODY_TRUNCATED_KEY)] = (
f"<{len(eb) - len(pinned)} more keys omitted>")
out["extra_body"] = pinned
if len(json.dumps(out)) <= _MAX_REQUEST_PARAMS_CHARS:
return out
others = [k for k in out if k != "extra_body"]
for key in sorted(others, key=lambda k: len(json.dumps(out[k])), reverse=True) + ["extra_body"]:
if key not in out:
continue
out[key] = f"<{len(json.dumps(out[key]))} chars omitted>"
if len(json.dumps(out)) <= _MAX_REQUEST_PARAMS_CHARS:
break
return out
# sub-case A: total=8294 <= 12288 pin preserved: True
# sub-case B: total=11774 <= 12288 pin preserved: TruePlease add a test for each sub-case — the distinguishing feature is that the collapse alone does not get under budget, which is what neither existing fixture exercises.
Non-blocking
2. _bounded_param's 512-char cap on strings measures Python characters, not emitted JSON. :490-491
if isinstance(value, str):
return value if len(value) <= max_chars else f"<{len(value)} chars omitted>"Every other branch measures len(json.dumps(...)); this one measures len(value). Under ensure_ascii=True the overshoot is large:
512 astral chars (emoji) -> 6146 emitted chars (12x the cap)
512 latin-1 chars ("é") -> 3074 emitted chars ( 6x)
512 '"' chars -> 1026 emitted chars ( 2x)
This is what makes the _MAX_REQUEST_PARAMS_CHARS comment's sizing wrong: :431-432 says "19 allowlisted keys at the 512-char value cap alongside a maximal extra_body clears 20KB" — the same 19 keys of astral-plane strings reach ~130KB before the aggregate guard trims. It's also what makes finding 1 reachable on non-exotic input: stop / stop_sequences are client-supplied and can carry non-ASCII, which is exactly sub-case A. Measuring len(json.dumps(value)) for the string branch closes both.
3. _fit_request_params's "cannot raise" invariant is false. :589-590 asserts "Every value here has already been through _bounded_param, so re-encoding one cannot raise." _bounded_param returns int/float scalars unbounded (:488-489 short-circuits before any encode), and CPython's 4300-digit int→str limit makes json.dumps raise:
_extract_request_params({"optional_params": {"temperature": 0.3, "top_p": 0.9, "seed": 10**5000}})
-> None # temperature and top_p lost; the line records "we could not tell"
The ValueError escapes the sort key at :604, lands in _extract_request_params's except Exception (:686), and the whole block degrades to None. This delta improves the outcome — before it, the same value raised inside _emit and cost the entire line, cost data included — so it isn't a regression, but the invariant the new code relies on is wrong and the gap is unclosed. Folding int into the same size check as everything else fixes it and makes the docstring true.
4. The post-collapse marker reports the wrong size. :617, reached with value = pinned, emits <2046 chars omitted> when ~9,950 chars of extra_body were actually discarded. Moot if the ordering fix in finding 1 lands, but worth not carrying forward.
5. _MAX_EXTRA_BODY_KEYS' "measured" figure is stale. :406 states the maximal 16-key remainder emits "11,289 chars, measured". Direct measurement of that fixture gives 11,227 for the extra_body dict and 11,243 for the block — and your own PR comment quotes 11,227 in the item-4 table. A number presented as measured should reproduce.
6. The 12KiB block cap is measured on the block; the 16KiB rationale is about the line. :439-441 acknowledges this ("themselves bounded only by the model and header names"), and I agree it's out of scope here — but the acknowledgement shouldn't read as coverage. _extract_session_id (:275) copies the client-supplied x-claude-code-session-id verbatim into both the line and the _session_totals key, and _extract_attribution (:296-300) copies three gateway header values with no length bound. Attribution is gateway-stamped so it's bounded in practice; the session id is not. Worth a follow-up issue rather than a change here.
Verified good in this delta
_finite_numberextraction is faithful._positive=_finite_number(v) and v > 0is semantically identical to the old inline predicate for every input class; no caller behaviour changed.- The
_numguard is the real fix, not a surface one.test_a_non_finite_count_does_not_silence_the_rest_of_the_sessionpins the second call in the session, which is where the old bug actually bit (int(inf)→OverflowError→ line dropped →aggalready poisoned → every later call silent). The per-call assertion alone would not have caught it. - A side benefit of
x >= 0that isn't called out:cached = _num(a) or _num(b)no longer short-circuits on a non-finitecache_read_input_tokens, so aninfthere now falls through toprompt_tokens_details.cached_tokensinstead of masking it. Strictly better. - The maximal fixture now exercises the slack term.
9856 < 11227 < 11392— measured; the term is load-bearing rather than headroom, which was the item-4 complaint. == 0.05pins a value where truthiness pinned nothing._MAX_EXTRA_BODY_KEYS32 → 16 is a narrowing, but a realextra_bodyis one or two keys and the truncation marker still records the omitted count._scrub_non_finite,_uncollided_key,_bounded_extra_body_key, the priority hoist, theNone-vs-{}unknown-vs-empty discipline and the prompt-field exclusion are untouched and still correct.
Per the review instructions I did not run make test. The above is tests/config/test_cost_callback.py (48 passed, 0.67s), plus read-only probes and a monkeypatched-fix run against the loaded module. CI covers the rest.
— Authored by egg
|
egg review completed. View run logs 15 previous review(s) hidden. |
|
Automated feedback loop has reached the maximum of 5 rounds. Human review is needed to make further progress on this PR. |
Closes #3599 — implements item 1 of the three it lists. The remaining two are split out and
tracked separately (#3616, #3617), along with a gap this change does not cover (#3618); see
Not included below.
Problem
egg sets no sampling parameters for any agent and recorded none, so when a model misbehaved there was no way to determine what decoding configuration produced the behaviour, during the incident or afterwards.
That blocked the #3598 post-mortem outright: a
laguna-s-2.1producer emitted 480 identical tool calls out of 603, and whether that is inherent to the model or an artifact of an unlucky decoding configuration is unanswerable, because nothing recorded which configuration was in play. Repetition and degeneration are decoding-sensitive failure modes; the one class of incident where this data matters most is precisely the class egg could not reconstruct.Change
config/litellm/cost_callback.pynow emitsrequest_paramson every per-call log line:That is the shape on a stock egg route today, and it is the #3599 finding rendered legible: no
temperature, notop_p, notop_k, no penalty. With sampling pinned inlitellm_params, the same field reads:{"temperature": 0.3, "top_p": 0.9, "top_k": 40, "seed": 42, "frequency_penalty": 0.2, ...}Source is
model_call_details['optional_params']— LiteLLM's post-mapping parameter set, i.e. the dict that becomes the upstream request body. Two properties earn the field its place:null, so absence reads as "never sent" and not "explicitly unset".drop_paramshas already acted, so this reports what the wire carried, not what the config asked for. A knob an operator set that does not appear here was silently discarded or relocated by LiteLLM's param mapper. That divergence is invisible today; here it is a diff.Verification
Validated end to end by running the real
cost_callback.pyinside the pinned litellm 1.86.2 on a streamedanthropic_messages→ OpenRouter call (the route and mode of all real Claude Code agent traffic), with HTTP mocked at the transport layer:request_paramsmax_tokens,stream, provider pin — no sampling knobstemperature,top_p,top_k,seed,frequency_penalty…thinking: {budget_tokens: 8000}reasoning_effort: "medium"The third row is worth its own note: LiteLLM rewrites a
thinkingbudget into areasoning_effortbucket, overwriting an explicitly configuredreasoning_effort. The recorded value is the effective one that went upstream, not the requested one — and it is why the field is emitted per line rather than once per session (it is not session-stable).mock_responseis deliberately not used anywhere in this verification: it short-circuits inanthropic_messages_handlerbefore the adapter path runs and leavesoptional_paramsempty. A fixture built that way would have made both the feature and its tests look correct while recording nothing.Design notes
optional_params. That dict also carries the translatedtoolsschemas (Claude Code sends a dozen-plus per request). Dumping it whole would bloat every line by orders of magnitude and spill task text into a stream that is a cost/observability sink, not a transcript sink. Values are size-capped and JSON-round-tripped:_emitswallows serialization failures, so one unserializable or unbounded field would silently take the whole cost line — including the cost data — with it.standard_logging_object.model_parameters. It filters to OpenAI's declared parameter set, which dropstop_k,stop_sequencesandextra_body— silently under-reporting several of the anti-repetition knobs this exists to capture.extra_bodyknobs are hoisted flat. LiteLLM relocates knobs a provider doesn't declare intoextra_bodyrather than dropping them, so the same knob lands at different depths per model; hoisting keeps one query surface. The remainder (notably the OpenRouter provider pin, which decides which backend — and so which quantization — served the turn) is preserved underextra_body.Line cost: ~130 bytes on an 812-byte line.
Not included
Items 2 (pin
temperature/top_pper model, now #3616) and 3 (inject a server-side repetition penalty, now #3617) from #3599 are deliberately left out:drop_params: truehides the failure).~/.config/egg/litellm-models.yaml, not the repo —laguna-s-2.1appears nowhere in this codebase. The repo carries only a template with one example backend.One further gap, now filed as #3618: this covers LiteLLM-routed traffic only. Claude-model agents go direct to Anthropic and never touch this proxy, so nothing is recorded for them. That is a near-static answer today (Claude Code CLI defaults, no egg override) and the incidents driving #3599 are all on LiteLLM routes — but "near-static" is itself an unrecorded assumption, which is why it is tracked rather than dismissed.
Testing
tests/config/test_cost_callback.py(26 total in the file, all passing) covering the streaming-agent shape, explicit sampling params, prompt-bearing-field exclusion,extra_bodyhoisting and remainder, the unknown-vs-empty distinction, size capping, and unserializable-value degradation. The fixture is captured from the live litellm 1.86.2 run described above and says so.make lintclean.make test: 22022 passed. Four failures, all intests/scripts/,gateway/tests/andorchestrator/tests/— confirmed pre-existing by reproducing them on a clean worktree atmain(6e9de94). No import path connects them to the files touched here.