Skip to content

feat(litellm): record the decoding config of every routed call (#3599) - #3611

Merged
jwbron merged 6 commits into
mainfrom
egg/litellm-record-request-params
Jul 25, 2026
Merged

jwbron merged 6 commits into
mainfrom
egg/litellm-record-request-params

Conversation

@jwbron

@jwbron jwbron commented Jul 25, 2026 •

Copy link
Copy Markdown
Owner

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.1 producer 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.py now emits request_params on every per-call log line:

"request_params": {
  "max_tokens": 32000,
  "stream": true,
  "extra_body": {"provider": {"order": ["Alibaba"], "allow_fallbacks": false}}
}

That is the shape on a stock egg route today, and it is the #3599 finding rendered legible: no temperature, no top_p, no top_k, no penalty. With sampling pinned in litellm_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:

  • An absent key was never sent, so the provider's own server-side default applied, and that default can change under us with no egg change. 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. That divergence is invisible today; here it is a diff.

Verification

Validated end to end by running the real cost_callback.py inside the pinned litellm 1.86.2 on a streamed anthropic_messages → OpenRouter call (the route and mode of all real Claude Code agent traffic), with HTTP mocked at the transport layer:

Scenario Emitted request_params
egg as shipped max_tokens, stream, provider pin — no sampling knobs
sampling pinned in config temperature, top_p, top_k, seed, frequency_penalty …
client sends thinking: {budget_tokens: 8000} reasoning_effort: "medium"

The third row is worth its own note: LiteLLM rewrites a thinking budget into a reasoning_effort bucket, overwriting an explicitly configured reasoning_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_response is deliberately not used anywhere in this verification: it short-circuits in anthropic_messages_handler before the adapter path runs and leaves optional_params empty. A fixture built that way would have made both the feature and its tests look correct while recording nothing.

Design notes

  • 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 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: _emit swallows serialization failures, so one unserializable or unbounded field would silently take the whole cost line — including the cost data — with it.
  • Not standard_logging_object.model_parameters. It filters to OpenAI's declared parameter set, which drops top_k, stop_sequences and extra_body — silently under-reporting several of the anti-repetition knobs this exists to capture.
  • extra_body knobs are hoisted flat. LiteLLM relocates knobs a provider doesn't declare into extra_body rather 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 under extra_body.

Line cost: ~130 bytes on an 812-byte line.

Not included

Items 2 (pin temperature/top_p per model, now #3616) and 3 (inject a server-side repetition penalty, now #3617) from #3599 are deliberately left out:

  • Both are behaviour changes whose correct values are per-provider judgement calls requiring each provider's published recommended sampling, and item 3 additionally requires verifying the provider honours it (drop_params: true hides the failure).
  • The model configs in question live in the operator-local ~/.config/egg/litellm-models.yaml, not the repo — laguna-s-2.1 appears nowhere in this codebase. The repo carries only a template with one example backend.
  • Sampling params are neither set nor recorded, making model-behaviour incidents unanalysable #3599 is explicit that ordering matters: trap frequency is conditional on decoding config, so a threshold measured under one configuration does not transfer to another. Landing 2 or 3 before this measurement exists reproduces the present ambiguity at greater cost.

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

  • 12 new tests in 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_body hoisting 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 lint clean.
  • make test: 22022 passed. Four failures, all in tests/scripts/, gateway/tests/ and orchestrator/tests/ — confirmed pre-existing by reproducing them on a clean worktree at main (6e9de94). No import path connects them to the files touched here.

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.

@egg-reviewer egg-reviewer Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_params flows straight into the _emit payload at top level; no downstream filter drops or defaults it. Grepped the two other files mentioning cost_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_params to be empty on the real streaming anthropic_messages path (exactly the "config read where it isn't available" failure class). The PR explicitly avoids mock_response (which short-circuits before the adapter populates optional_params) and mocks at the transport layer instead. This is the right call and is documented in the fixture docstring. Reading optional_params off model_call_details is 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 pathological logit_bias/stop can'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_excluded pins it. extra_body remainder is bounded.
  • Existing cost/cache visibility does not regress when optional_params is absent (test_absent_optional_params_does_not_suppress_the_line), and None ("unknown") vs {} ("reported, nothing decoding-relevant") is preserved — matching the module's unknown-≠-zero discipline.
  • The docs jq query correctly references .context.request_params / .context.agent_role / .context.model (matches _emit's wrapping into context).

Non-blocking suggestions

  1. The provider pin can be collapsed by the size cap when extra_body carries other bulk. _extract_request_params bounds the entire leftover dict 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 to extra_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 (only extra_body becomes a marker; cost/attribution/other params survive) and the trigger is uncommon.

  2. NaN/Inf float params defeat the "line stays serializable" invariant. _bounded_param passes floats through untouched, and json.dumps emits the non-standard NaN/Infinity tokens (invalid JSON). The documented jq 'fromjson?' query silently drops any such line — losing the cost data too, the exact outcome _bounded_param exists to prevent. Requires a misconfigured temperature/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

@james-in-a-box

This comment has been minimized.

@james-in-a-box

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).
@james-in-a-box

Copy link
Copy Markdown
Contributor

Review feedback addressed

Thanks for the thorough pass. Both non-blocking suggestions were valid and are fixed in this PR.

  1. Provider pin collapsing under extra_body size pressure — fixed-in-PR (commit 91b7f0a). _extract_request_params now bounds each extra_body leftover value individually ({k: _bounded_param(v) for k, v in leftover.items()}) instead of the whole leftover dict as one unit. A bulky sibling knob degrades to a size marker on its own; the small, load-bearing OpenRouter provider pin always survives. New test test_bulky_extra_body_sibling_does_not_collapse_the_provider_pin pins the provider={...} + junk="z"*600 case from your example.

  2. NaN/Inf floats defeating the "line stays serializable" invariant — fixed-in-PR (commit 91b7f0a). _bounded_param now maps non-finite floats to a <non-finite: ...> marker before the scalar passthrough, so json.dumps no longer emits the non-standard NaN/Infinity tokens and a downstream jq 'fromjson?' can't silently drop the line (cost data and all). New test test_non_finite_floats_become_markers verifies the marker and that a line carrying such a param round-trips as strict JSON.

Targeted tests pass locally (TestBoundedParam, TestExtractRequestParams, TestRequestParamsInPayload — 14 passed); make lint clean.

— Authored by egg

@james-in-a-box

This comment has been minimized.

@egg-reviewer egg-reviewer Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 / stop are 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"] = bounded

Please 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)   # nested

Non-blocking

  1. The docstring now overstates coverage. cost_callback.py:355-367 says "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 the allow_nan=False fix it becomes true and needs no further edit.

  2. test_bulky_extra_body_sibling_does_not_collapse_the_provider_pin is a good test — it goes through _extract_request_params rather 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_preserved still holds under per-value bounding ({"provider": _bounded_param({...})} compares equal).
  • Top-level NaN/Inf/-Inf → <non-finite: ...> markers, ordered correctly before the scalar passthrough; bool is unaffected (isinstance(True, float) is False).
  • No change to the extraction source, the allowlist, the prompt-exclusion property, or the unknown-vs-empty (None vs {}) discipline.

— Authored by egg

@james-in-a-box

This comment has been minimized.

@james-in-a-box

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.
@james-in-a-box

Copy link
Copy Markdown
Contributor

Re-review feedback addressed — a2195ee

Both blocking findings were correct, including the diagnosis that the previous delta's item-2 fix covered the less reachable half. Fixed in this PR.

Blocking 1 — per-value bounding removed the aggregate cap and the key-side guard

fixed-in-PR (commit a2195ee). Both properties are restored, using the shape you suggested:

_MAX_EXTRA_BODY_KEYS = 32
...
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:
    bounded["<truncated>"] = f"<{len(leftover) - _MAX_EXTRA_BODY_KEYS} more keys omitted>"

Your two repro cases, run against the patched helper:

extra_body={"provider": {...}, **{f"knob{i}": "v"*400 for i in range(200)}, "k"*100000: 1}
  before: 100053+ chars emitted
  after:  12819 chars, 33 keys (32 + "<truncated>": "<170 more keys omitted>"), pin intact

extra_body={("a","b"): 1}
  after:  {'extra_body': {"('a', 'b')": 1}}   # line survives, cost data intact

Worst case is now bounded at 32 × the 512-char value cap rather than unbounded. Item 1's original goal still holds — {"provider": {...}, "junk": "z"*600} still yields an intact pin next to a size marker, pinned by the existing test_bulky_extra_body_sibling_does_not_collapse_the_provider_pin.

You were right that no test would have caught the removal. Two added: test_extra_body_stays_bounded_in_aggregate (asserts the key count, the truncation marker, per-key name length, and total emitted size — it fails on the pre-fix code, which emitted 100k+ chars) and test_non_str_extra_body_key_degrades_instead_of_costing_the_line.

Blocking 2 — non-finite floats only handled at the top level, and a vacuous test

fixed-in-PR (commit a2195ee). json.dumps(value, default=str, allow_nan=False) in _bounded_param, so a nested non-finite raises inside the existing try and falls to "<unserializable>":

logit_bias={"5": -inf}         -> "<unserializable>"
stop=[nan]                     -> "<unserializable>"
extra_body={"weird": {"x": inf}} -> "<unserializable>"

The point about reachability ordering is well taken — -inf as a logit bias is a real idiom for banning a token, and that was the half left open.

On the vacuous test: confirmed, json.dumps/json.loads both accept NaN by default, so the assertion carried no information. It now asserts under allow_nan=False, with a comment saying why that keyword is what makes the check mean anything (so the next edit doesn't quietly drop it again), and a new test_nested_non_finite_floats_degrade_rather_than_emit_invalid_json covers the nested cases you listed.

Non-blocking 3 — docstring overstated coverage

fixed-in-PR (commit a2195ee). Rather than leave it to become true by implication, the _bounded_param docstring now names the nesting explicitly and says which mechanism handles it — the top-level math.isfinite guard for scalars, allow_nan=False on the round-trip for anything deeper, with the logit_bias case as the worked example.

Non-blocking 4 — the new test is the right pattern

No change needed; noted. The two aggregate-bound tests added here follow it — both go through _extract_request_params rather than hand-building the entry.


Verification. tests/config/test_cost_callback.py: 31 passed. Ruff check and ruff format clean. make lint's mypy stage reports 3 errors in shared/egg_agent/client.py — pre-existing and unrelated; this PR touches config/litellm/, docs/, k8s/ and tests/config/ only, and config/litellm/cost_callback.py is outside the project's mypy scope (not among the 278 files checked).

— Authored by egg

@james-in-a-box

This comment has been minimized.

@egg-reviewer egg-reviewer Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. The provider pin can still be truncated away — the count cap is positional. cost_callback.py:464 slices 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']: False
    

    The comment at :453-462 claims "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"). Pulling provider out before the slice closes it. Trigger (33+ extra_body keys) is unrealistic, hence non-blocking.

  2. 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
    
  3. <truncated> collides with an operator key of that name. With >32 keys, a real extra_body["<truncated>"] is overwritten by the marker (verified: value lost, and len(emitted) came back 32 rather than 33 — so the == _MAX_EXTRA_BODY_KEYS + 1 invariant the new test asserts is fixture-specific, not general). A <egg:truncated>-style sentinel avoids it.

  4. 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 chars
    

    Bounded, 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_body key is longer) would make the bound match the intent.

  5. _emit's own json.dumps still runs with allow_nan=True, so the strict-JSON invariant now holds for request_params and nothing else on the line. _extract_cost (cost_callback.py) admits +inf, since inf > 0 is True — it would be accumulated into agg["cost"] and poison that session's totals for the pod's lifetime, and emit Infinity. (NaN is already safe: nan > 0 is False.) Worth noting the fix is not allow_nan=False in _emit — that converts an invalid line into no line at all, the outcome being avoided — but a math.isfinite check in _extract_cost / _extract_estimated_cost. Exotic enough to be advisory only, and arguably its own change.

  6. 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 a logit_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_param ordering is still correct — the math.isfinite guard precedes the scalar passthrough, and bool is unaffected (isinstance(True, float) is False).
  • json.loads(encoded) at the tail is now provably nan-free, since encoded was produced under allow_nan=False.
  • No change to the extraction source, _REQUEST_PARAM_KEYS, the prompt-exclusion property, or the unknown-vs-empty (None vs {}) discipline.
  • Both new _extract_request_params tests go through the production helper rather than hand-building the entry — the right pattern, and test_extra_body_stays_bounded_in_aggregate does fail on the pre-fix code.

— Authored by egg

@james-in-a-box

This comment has been minimized.

@james-in-a-box

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".
@james-in-a-box

Copy link
Copy Markdown
Contributor

Re-review feedback addressed — f20b8ae

Both blocking findings were correct, and the mutation table was the useful part: the production code was right and the tests were not pinning it. All eight items are fixed in this PR.

Blocking 1 — test_non_str_extra_body_key_degrades_instead_of_costing_the_line passes when the params block is lost

fixed-in-PR (commit f20b8ae). Confirmed: json.dumps(None) is the truthy "null", so the assertion could not tell a graceful degrade from _extract_request_params returning its "we could not tell" sentinel — the strictly worse outcome, and the one that takes temperature/top_p down with it. The test now asserts the emitted mapping, and carries a temperature alongside so the sentinel case is visibly distinct:

params = cc._extract_request_params(
    _mcd("r", optional_params={"temperature": 0.3, "extra_body": {("a", "b"): 1}})
)
assert params["temperature"] == 0.3
assert params["extra_body"] == {"('a', 'b')": 1}
assert json.dumps(params)

This is the second round the same shape has appeared in, so I mutation-checked every guard in the delta rather than only the two you named:

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

@james-in-a-box

This comment has been minimized.

@egg-reviewer egg-reviewer Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 None

2. 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.05

response_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 + 1

test_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_finite is 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-keyed NaN both fall through to <unserializable> rather than raising out into _emit — confirmed by probe.
  • The except ValueError / except Exception ordering is correct, and a circular reference (which also raises ValueError, from Circular reference detected rather than from allow_nan) degrades cleanly to <unserializable> through the retry rather than looping — confirmed by probe.
  • The provider hoist is a stable partition of leftover, so len(ordered) == len(leftover) and the > _MAX_EXTRA_BODY_KEYS truncation count is unchanged in meaning.
  • The … in the bounded key name is escaped to … by _emit's ensure_ascii default — 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 (None vs {}) 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

@james-in-a-box

This comment has been minimized.

@james-in-a-box

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.
@james-in-a-box

Copy link
Copy Markdown
Contributor

Re-review feedback addressed — bb9e479

All five non-blocking items fixed in this PR. The mutation sweep was the useful part again: item 1 was a guard I claimed was covered and wasn't, and re-running the sweep after this delta found a second unpinned exit that neither of us had named.

1 — _positive's bool exclusion is the one unpinned guard

fixed-in-PR (commit bb9e479). Correct, and the correction to my "No green mutations" claim is fair — it was incomplete. test_boolean_cost_is_not_a_cost pins all three call sites (cost, the cost_details fallback, and response_cost), since isinstance(True, int) is True at each of them and float(True) records a $1.00 charge that was never billed.

2 — docs/…:641 "survives all of these" is false for the size cap

fixed-in-PR (commit bb9e479). Took the second option you offered — the wider value cap — because you named the actual tension: "load-bearing enough to reorder the dict for" and "same size budget as a junk sibling" can't both be true. _bounded_param now takes max_chars, and priority keys draw on _MAX_PRIORITY_PARAM_JSON_CHARS = 2048. Your 596-char pin:

before: '<596 chars omitted>'
after:  {'order': [...], 'ignore': [...], 'allow_fallbacks': False, 'quantizations': [...]}

The doc sentence is qualified rather than dropped, because "degrades last, not never" is the honest version and the 2048 bound is still reachable: "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." Measured worst case is now 20,676 chars over 33 keys; the constant's comment says ~21KB and what it takes to reach it.

A second unpinned exit, found by re-running your sweep on this delta. _bounded_param has two size checks — the raw-string shortcut and the JSON round-trip — and plumbing max_chars through only the second one left drop max_chars on str branch → 44 passed green. That is the same shape as item 1: a guard that looks covered because its sibling is. test_the_cap_is_caller_settable_on_both_branches pins both exits, and the mutation now fails.

3 — _extract_estimated_cost's fallback gate is asymmetric with _extract_cost

fixed-in-PR (commit bb9e479). if not _positive(rc):, as you suggested. Fixed on the strength of the argument rather than the reproduction — response_cost: 0.0 is documented in this function's own docstring as the unpriceable-model case, which is precisely what the fallback exists for, so a presence gate lets that zero mask a good estimate in the metrics object. Whether litellm 1.86.2 emits that pairing decides how often it fires, not whether the gate is right.

{"response_cost": 0.0,  "standard_logging_object": {"response_cost": 0.004}}  ->  0.004
{"response_cost": inf,  "standard_logging_object": {"response_cost": 0.004}}  ->  0.004

4 — the truncation marker skips the collision-suffix logic

fixed-in-PR (commit bb9e479). The suffix logic is now _uncollided_key, and every emitted key routes through it — the marker included. Your repro:

extra_body = {"<egg:truncated>": "REAL", **{f"k{i}": i for i in range(40)}}
  before: emitted["<egg:truncated>"] == '<9 more keys omitted>', len 32   # operator value lost
  after:  emitted["<egg:truncated>"] == 'REAL'
          emitted["<egg:truncated><2>"] == '<9 more keys omitted>', len 33

The important half was your observation that test_truncation_marker_does_not_overwrite_a_real_key used the old <truncated> name — a test named for a collision that cannot collide asserts nothing about the sentinel, and it made the _MAX_EXTRA_BODY_KEYS + 1 invariant fixture-specific. It now uses cc._EXTRA_BODY_TRUNCATED_KEY itself, so the invariant is unconditional.

5 — the new bullet is detached from its list

fixed-in-PR (commit bb9e479). Moved into the list; the lead-in reads "Three things to know". The prompt-exclusion paragraph now closes the block, which is where it belongs — it is a property of the allowlist, not a fourth reading note.


Verification. tests/config/test_cost_callback.py: 44 passed (40 before). Ruff check and ruff format --check 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.

Mutation sweep over the delta, each guard reverted in isolation:

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

@james-in-a-box

This comment has been minimized.

@egg-reviewer egg-reviewer Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 == 33

5. 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_key is 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 provider does not acquire priority treatment — membership is tested on the source key before name bounding (:546), not after.
  • _scrub_non_finite / the except ValueError vs except Exception ordering / the circular-reference path are untouched and still degrade cleanly.
  • No change to the extraction source, _REQUEST_PARAM_KEYS, the prompt-exclusion property, or the None-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

@james-in-a-box

This comment has been minimized.

@james-in-a-box

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.
@james-in-a-box

james-in-a-box Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Re-review feedback addressed — 749d06c

All four non-blocking items fixed in this PR. Item 1 was the interesting one: the asymmetry you flagged is real, and the consequence is worse than the one it's asymmetric with.

1 — _extract_cache_stats._num admits bool and non-finite

fixed-in-PR (commit 749d06c). Every word of _positive's docstring is true of the four counts _num reads, and the outcome is one notch past the cost case exactly as you traced it: int(inf) raises OverflowError inside _record, the outer handler drops the line, and because the value already landed in agg[...] the session total stays inf and every subsequent call in that session emits nothing for the pod's lifetime.

Factored _positive's finite/non-bool half into _finite_number and applied it in both places, rather than duplicating the predicate — the asymmetry you found existed because the guard lived inside the function that needed it first:

prompt_tokens=True   -> (0.0, 0.0, 0.0, 0.0)
prompt_tokens=inf    -> (0.0, 0.0, 0.0, 0.0)
prompt_tokens=1200   -> (1200.0, 0.0, 0.0, 0.0)

# one poisoned call, then a healthy one in the same session:
before: line1 emitted? False   line2 emitted? False   totals.prompt_tokens = inf
after:  line1 emitted? True    line2 emitted? True    totals.prompt_tokens = 1000.0

Two tests: test_boolean_and_non_finite_token_counts_are_not_counts (top-level and both nested schemas) and test_a_non_finite_count_does_not_silence_the_rest_of_the_session, which pins the session-poisoning half rather than only the per-call one.

2 — the aggregate bound sits above the ~16KB line-split threshold

fixed-in-PR (commit 749d06c). Took the framing rather than the constant: if the cap's purpose is "one line cannot take out the stream", then the target is the threshold — and once you measure against the line, tightening _MAX_EXTRA_BODY_KEYS alone doesn't get there. The 19 allowlisted keys at the 512-char value cap add ~10KB on their own, so the per-dimension caps clear 20KB together with every individual cap intact. That's the actual defect: the caps bound each dimension and compose multiplicatively.

So the block now has a ceiling of its own — _MAX_REQUEST_PARAMS_CHARS = 12288, 12KiB, leaving headroom under 16KiB for the ~800 bytes of cost/attribution fields sharing the line. _fit_request_params marks down the largest entries first (the sampling scalars are a handful of bytes each — never what pushed the block over) and collapses extra_body to its priority keys before dropping it outright, so a trimmed line still answers what the field exists for:

19 allowlisted keys at 512 chars + 100-key maximal extra_body
  -> 10,166 chars, within budget
  -> temperature: intact (512 chars)
  -> extra_body: {"provider": {"order": ["Alibaba"]}, "<egg:truncated>": "<16 more keys omitted>"}

_MAX_EXTRA_BODY_KEYS drops to 16 as well, but now sized against that budget rather than picked round: 16 maximal keys emit 11,289 chars measured, so the case the key cap already covers leaves the aggregate guard nothing to undo. Three tests — the aggregate bound, the pin-preserving collapse, and one asserting a stock line is left untouched (a backstop that fired on real traffic would be a regression in the data this PR adds). The doc bullet now names the block cap and warns that a <N chars omitted> on a small field means the block was over budget, not that field.

On the PLAUSIBLE rating: I also couldn't verify the runtime constant from here, so the comment on _MAX_REQUEST_PARAMS_CHARS states 16KiB as the documented behaviour of Docker's json-file driver and containerd's CRI logger rather than as something measured. The fix stands either way — a 20KB observability line is worth bounding regardless of where exactly it gets split.

3 — bare truthiness in the symmetry assertion

fixed-in-PR (commit 749d06c). == 0.05. You're right that a redundant assertion that can't fail is worse than none — it reads as coverage.

4 — the slack term isn't exercised by its own fixture

fixed-in-PR (commit 749d06c). Confirmed, and there was a second layer under it: with a 22-char pin the term was headroom, but the fixture was also not maximal in any other dimension, and the + 64 per-key fudge in the bound is loose enough that even a fully maximal fixture stayed under the general term. So making the pin big alone would not have fixed it.

Both halves are addressed: the fixture is now genuinely maximal (every key name past its cap so each emits prefix and size suffix, every value at its cap, and a 130-backend pin near the 2048 priority cap), and the bound is stated as it is derived — name cap + suffix + value cap + punctuation — instead of the loose approximation. Asserted from below as well as above, so a fixture that stops exercising the slack term fails rather than passes quietly:

general term = 9,856    emitted = 11,227    general + slack = 11,392

Verification. tests/config/test_cost_callback.py: 48 passed (44 before). ruff check and ruff format --check 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.

Mutation sweep over the delta, each guard reverted in isolation on a scratch copy:

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

@james-in-a-box

This comment has been minimized.

@egg-reviewer egg-reviewer Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_body collapses 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: True

Please 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_number extraction is faithful. _positive = _finite_number(v) and v > 0 is semantically identical to the old inline predicate for every input class; no caller behaviour changed.
  • The _num guard is the real fix, not a surface one. test_a_non_finite_count_does_not_silence_the_rest_of_the_session pins the second call in the session, which is where the old bug actually bit (int(inf) → OverflowError → line dropped → agg already poisoned → every later call silent). The per-call assertion alone would not have caught it.
  • A side benefit of x >= 0 that isn't called out: cached = _num(a) or _num(b) no longer short-circuits on a non-finite cache_read_input_tokens, so an inf there now falls through to prompt_tokens_details.cached_tokens instead 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.05 pins a value where truthiness pinned nothing.
  • _MAX_EXTRA_BODY_KEYS 32 → 16 is a narrowing, but a real extra_body is 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, the None-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

@james-in-a-box

Copy link
Copy Markdown
Contributor

egg review completed. View run logs

15 previous review(s) hidden.

@james-in-a-box

Copy link
Copy Markdown
Contributor

Automated feedback loop has reached the maximum of 5 rounds. Human review is needed to make further progress on this PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Sampling params are neither set nor recorded, making model-behaviour incidents unanalysable

1 participant