Skip to content

test(cost): cover unpriced provider slugs and explicit zero rates - #42467

Merged
kerry-berri merged 8 commits into
BerriAI:mainfrom
eduardopessin:fix/dated-provider-slug-zero-cost
Oct 28, 2026
Merged

kerry-berri merged 8 commits into
BerriAI:mainfrom
eduardopessin:fix/dated-provider-slug-zero-cost

Conversation

@eduardopessin

@eduardopessin eduardopessin commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Guard provider-model pricing fallback against future regressions

How it solves it:

  • Cover unmapped provider names with deterministic test rates
  • Cover provider-rate precedence, including explicit zero rates
  • Document pricing precedence without adding runtime helpers

Current main already handles the original report. After integrating main, this PR contains only regression tests and documentation, with no pricing implementation changes relative to main

User Flow

Before, current main already calculates the expected charges

  1. Calculate usage with a provider-reported name absent from pricing
  2. Observe the charge from the priced response model
  3. Register a provider rate, including zero, and observe that rate win

After, the same behavior has focused regression coverage

  1. Calculate usage with a provider-reported name absent from pricing
  2. Observe the charge from the priced response model
  3. Register a provider rate, including zero, and observe that rate win

Relevant issues

Related to #42161. This PR no longer claims a new runtime fix for that issue

Pre-Submission checklist

  • I have added meaningful tests
  • The handful of test files covering my change pass locally
  • My PR passes all required CI/CD checks
  • My PR's scope is isolated to one problem
  • Every automated review on my latest commit has finished and findings are addressed

All three targeted regression cases passed after integrating main at 66cd1a651647. An earlier full-file run had 515 passing tests and one failure when Windows environment isolation prevented Prisma from finding the home directory. That full-file failure was not rerun to reconfirm it

Screenshots / Proof of Fix

This is a regression-only PR. The same real completion_cost program passed at the current merge base and the published tip. Rates and model names are locally registered test values, so no provider account or paid request is involved

Run the shared program from each checkout

import json, os
os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
os.environ["PYTHON_DOTENV_DISABLED"] = "1"
import litellm
from litellm.cost_calculator import completion_cost
from litellm.types.utils import ModelResponse, Usage
response_name = "anthropic/claude-publication-response"
reported_name = "claude-publication-priced"
free_name = "claude-publication-free"
missing_name = "claude-publication-unmapped"
litellm.register_model(model_cost={response_name: {"input_cost_per_token": 0.001, "output_cost_per_token": 0.002, "litellm_provider": "anthropic", "mode": "chat"}, "anthropic/"+reported_name: {"input_cost_per_token": 0.01, "output_cost_per_token": 0.02, "litellm_provider": "anthropic", "mode": "chat"}, "anthropic/"+free_name: {"input_cost_per_token": 0.0, "output_cost_per_token": 0.0, "litellm_provider": "anthropic", "mode": "chat"}})
for case, reported, expected in (("baseline",None,0.086),("unmapped",missing_name,0.086),("priced",reported_name,0.86),("free",free_name,0.0)):
    response = ModelResponse(model=response_name, choices=[], usage=Usage(prompt_tokens=38, completion_tokens=24, total_tokens=62))
    if reported:
        response._hidden_params["provider_response_model"] = reported
    cost = completion_cost(completion_response=response,custom_llm_provider="anthropic")
    print(json.dumps({"case":case,"cost":cost}))
    assert abs(cost-expected)<1e-12
print("PASS: existing fallback and explicit zero pricing preserved")

Before (66cd1a6)

  1. Run the shared program at the merge base
  2. Baseline and unmapped-name costs are 0.086, the explicitly priced provider costs 0.86, and the explicitly free provider costs 0.0

After (b7f95fa)

  1. Run the same program at this PR's tip
  2. The same four charges are preserved and the program reports PASS

CI follow-up

The root shard failed after a runtime-registration replay test overwrote supports_function_calling on the shared catalog and then restored the same already-mutated dictionary. A later proxy-capability case on that worker read the leaked value

Both registration replay tests now use the existing local_model_cost_map fixture. The failing capability assertion is unchanged. A serial run of the replay cases, proxy capability cases, and pricing regressions passed all 24 cases. A real SDK registration probe also changed the flag temporarily and confirmed the original catalog and capability were restored

The pricing smoke was repeated at this tip and preserved the same four charges. No production pricing implementation changed. The new push starts a fresh CI run rather than rerunning the failing revision

Type

Test
Documentation

Caveats

Medium

  • Earlier full-file verification hit Windows home-directory isolation failure

Low

  • Latest CI and automated reviews still need to finish

No maintainer review is requested until the latest automated checks and findings are examined

Final Attestation

  • All required checks and full-file validation are complete

@eduardopessin
eduardopessin requested a review from a team September 22, 2026 12:09
@CLAassistant

CLAassistant commented Sep 22, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@greptile-apps

greptile-apps Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

The pricing behavior appears correct, but explicit repository requirements for source comments, line length, and stable tests must be satisfied before merging

Findings

  1. P2 Excess explanatory comments ▶
  2. P2 Overlong Python lines ▶
  3. P2 Mutable vendor facts pinned ▶

Summary

This PR changes cost-model selection so an unpriced provider-reported model can fall back to the response model while preserving priced provider-model precedence

  • Adds helpers to determine whether a reported model resolves to pricing
  • Uses the response model when the provider-reported slug is unavailable in the price map
  • Adds regression coverage for fallback and precedence behavior
  • The implementation is behaviorally sound, but repository requirements concerning comments, line length, and stable tests remain unmet

Reviews (1) · Last reviewed commit: "fix(cost): a provider slug the price map..."

Comment thread litellm/cost_calculator.py Resolved
Comment thread litellm/cost_calculator.py Resolved
@codspeed

codspeed Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing eduardopessin:fix/dated-provider-slug-zero-cost (fd60471) with main (259c166)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (a76b59d) during the generation of this report, so 259c166 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@codecov

codecov Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@eduardopessin

Copy link
Copy Markdown
Contributor Author

Thanks, two of the three were right and are fixed in bc829e3.

The helper docstrings explained what the code already shows, so they are gone.

The vendor pinning was the real catch. The tests asserted claude-opus-5 is in the
price map and claude-opus-5-20250930 is not, and neither is a fact we own: if
Anthropic registers the dated build, the test breaks with no litellm change behind it.
They now use a name that is ours and assert the invariant, that what the provider
reports cannot change the price of a turn the map cannot quote it by.

Worth noting what that rewrite turned up, since it nearly slipped through. My first
attempt used an arbitrary string, and that makes get_model_info raise rather than
return zero rates, which a caller upstream already handles. The tests then passed with
and without the fix, so they defended nothing. A claude- prefixed name reaches the
zero-rate fallback this bug actually rides on, so claude-test-42161 reproduces it and
stays ours. With the fix reverted the regression test fails on
assert 0.0 == 0.0007900000000000001, as it should.

On the third point, lines 801 and 828 are 98 and 39 characters, so there is nothing to
wrap there. No line I added exceeds 120.

eduardopessin added a commit to eduardopessin/litellm-mysubs that referenced this pull request Sep 22, 2026
… readable

0.1.8 and 0.1.9 both claimed to stop streamed Claude turns being logged at zero
cost. Neither did. The code has been sitting in the package doing nothing, so it
goes.

The diagnosis was right and the placement was wrong. 0.1.8 rewrote the chunks
coming out of the stream, but the cost is computed inside CustomStreamWrapper
from a value chunk_creator reads off the raw chunk first. 0.1.9 corrected that
attribute through chunk_creator, which is right for a plain wrapper, except the
Router interposes a FallbackStreamWrapper that overrides __anext__ and never
calls chunk_creator. That class is defined inside
_acompletion_streaming_iterator, so it is not importable and the tests could not
have built it: all three attempts were verified against a hand-made wrapper that
behaves differently from what the proxy gets.

The bug is upstream: BerriAI/litellm#42161, PR at BerriAI/litellm#42467. An
explicit input_cost_per_token in model_info works around it meanwhile.

Tool-name aliasing from 0.1.7 is untouched. Its tests now cover only what it
actually does, including that the stream wrapper is handed back as itself.

LICENSE is plain MIT again so GitHub stops reporting NOASSERTION; the oh-my-pi
attribution that used to sit mid-file is in NOTICE, shipped in the wheel.
…rn at zero

Anthropic names the dated build in `message_start`, so a streamed turn carries
`provider_response_model="claude-opus-5-20250930"` while the price map holds
`claude-opus-5`. `_select_model_name_for_cost_calc` prefers the reported name
over `response.model`, and `get_model_info` answers a model it has never heard
of with zero rates rather than raising -- so the turn is billed 0.0 with nothing
in the logs to explain it.

Same usage, only that field varying, on main:

    provider_response_model absent                  ->  0.00079
    provider_response_model=claude-opus-5           ->  0.00079
    provider_response_model=claude-opus-5-20250930  ->  0.0

Missing is harmless; the damage is a name that is present and unpriced.

The reported name still wins whenever it resolves to a rate -- it is the most
specific truth about what served the turn. It is only passed over when charging
by it would produce a silent zero, and then the response's own model is used:
the name the deployment resolved to, and the one an unstreamed turn is already
priced by.

This is not specific to Anthropic or to streaming. Any provider reporting a more
specific slug than the map carries -- dated, regional, build-suffixed -- is
affected, and only streamed turns carry the field, which is why it reads as a
streaming bug from the outside.

Reported in BerriAI#42161.
@eduardopessin
eduardopessin force-pushed the fix/dated-provider-slug-zero-cost branch from bc829e3 to eda6bbf Compare September 25, 2026 10:40
…in tests

Three points from the review, two of which were right.

The helper docstrings explained behaviour the code already shows, which AGENTS.md
rules out. Removed.

The tests asserted that `claude-opus-5` is in the price map and
`claude-opus-5-20250930` is not. Both are facts we do not own: if Anthropic registers
the dated build, the test breaks without any litellm change. They now use a name that
is ours, and assert the invariant instead, that what the provider reports cannot change
the price of a turn the map cannot quote it by.

Picking that name needed care. An arbitrary string makes `get_model_info` raise, which
a caller upstream already handles, so the test passed with or without the fix and
defended nothing. A `claude-` prefixed name reaches the zero-rate fallback that this
bug rides on, so `claude-test-42161` reproduces it and stays ours.

The third point, that lines 801 and 828 exceed 120 characters, does not hold: they are
98 and 39.
@eduardopessin
eduardopessin force-pushed the fix/dated-provider-slug-zero-cost branch from 59843dd to 57182eb Compare September 27, 2026 10:09
Mark the blind except in _has_rate with noqa: BLE001, as the file does elsewhere for get_model_info.
…ponse_model

basedpyright counted the bare variable as partially unknown (reportUnknownArgumentType +1 over the budget).
@eduardopessin

Copy link
Copy Markdown
Contributor Author

Updated onto current main (73072b8). The bug still reproduces there, same numbers as in the description:

provider_response_model main this PR
absent 0.00079 0.00079
claude-opus-5 0.00079 0.00079
claude-opus-5-20250930 0.0 0.00079

Changes since the last review:

  • Merged main. The only conflict was in tests/unit/test_cost_calculator.py, where both sides appended tests; kept both.
  • _has_rate marks its except Exception with noqa: BLE001, the way the file already does for get_model_info, since that lookup raises a bare Exception for some unmapped models.
  • The new call passes completion_response_model as str or None. basedpyright counted the bare variable as partially unknown and the type gate was one over its reportUnknownArgumentType budget. lint passes now.

Two checks still fail, and they fail the same way on other open PRs: osv-scan reports pypdf 6.16.2 in uv.lock, which this PR does not touch, and schema-migration fails in test_db_push_timeout_hint_names_the_per_command_budget on a database connection.

@eduardopessin eduardopessin changed the title fix(cost): a provider slug the price map lacks no longer bills the turn at zero test(cost): cover unpriced provider slugs and explicit zero rates Oct 20, 2026
@kerry-berri

Copy link
Copy Markdown
Contributor

thank you for contributing!

@kerry-berri
kerry-berri merged commit e5fe716 into BerriAI:main Oct 28, 2026
86 checks passed
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.

3 participants