Repository navigation
test(integration): cover anthropic_messages endpoint contracts - #44704
Conversation
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
|
bugbot run |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
…racts_anthropic_messages
…wlist Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
…en and pin the truncated stream bug Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
…racts_anthropic_messages
|
bugbot run |
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
@litereview code-review |
✅ code-review5/5 · Ready for human reviewScope: full · Full PR review. Completed · Some checks not run. No correctness findings. The PR changes only test files under Checks and execution details
View review · Reviewed |
|
bugbot run |
…racts_anthropic_messages
|
@litereview code-review |
|
bugbot run |
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
@litereview code-review |
|
bugbot run |
…racts_anthropic_messages
|
@litereview code-review |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit de0c18a. Configure here.
TLDR
Problem this solves:
/v1/messagescontracts had no real-proxy wire testsHow it solves it:
litellm/BUGskips with full test bodiesWhat is now covered
A native Anthropic deployment now has wire tests for the Claude Code CLI spelling (
POST /v1/messages?beta=truewith the full comma-separatedanthropic-betalist including a made-up future beta,safeguards,metadata.user_id, tools and systemcache_control), stream false and true, asserting the forwardedanthropic-betacarries exactly the client's tokens (none dropped, none added), the whole upstream JSON body andsafeguard_resultsreaching the client unchanged. Upstream 429 and 400 errors are asserted as Anthropic error envelopes with the right status and SDK exception class, an upstream 529 is compared as a whole envelope, a mid-stream upstream error is asserted as the client's full SSE sequence (message_startthenerror, nomessage_stop), an upstream stream that closes aftermessage_startand a text delta withoutmessage_stopis asserted to end with the incomplete-streamerrorevent instead of a clean 200 (aBUGskip, main relays it as a clean 200), and image (base64 and url), PDF document,tool_resultwithis_errorand nested content, and repeated tool-use history are asserted byte-equal at the upstream with every returned block type parsed by the Anthropic SDKThe Claude Code gateway aliases
/claude_code_gateway/v1/messagesand/claude_code_gateway/v1/messages/count_tokensare asserted to 404 with the exact{"detail": "Claude Code gateway is not enabled"}body without reaching the provider when the gateway is disabled, and on an owned proxy with the gateway enabled to produce the identical upstream request (method, path,x-api-keyswap,anthropic-beta, full body) and identical client response or SSE as/v1/messagesfor stream false and true, to refuse a model outside the key allowlist with the same 403 envelope as/v1/messageswithout reaching upstream, and to write a spend row attributed to the calling key. The count_tokens alias is asserted to reach/v1/messages/count_tokenswithx-api-key, the exact body and the same{input_tokens}as the native route, and to refuse a model outside the keyThe gateway OAuth device flow is driven end to end against a scripted generic SSO identity provider:
authorization_pendingbefore SSO and again after SSO but before user-code verification, a wrong verification code rejected with 400Invalid verification codewhile the poll staysauthorization_pending,expired_tokenfor a device code whose poll secret is wrong, exactly one access token on success,expired_tokenon replay,unsupported_grant_typeandinvalid_grantfor other grants, and the issued bearer working on the gateway, stream false and true with?beta=true, only for models both the user and the team allow (user[A, B], team[A, C]: A passes, B gets 403team_model_access_denied, C gets through on the team grant), with each success writing a spend row for the signed-in user and teamA
vertex_ai/claude-*deployment is asserted to call:rawPredictor:streamRawPredict?alt=ssewith Bearer auth,anthropic_version: vertex-2023-10-16, nomodelfield and only supported betas. Anazure_ai/claude-*deployment is asserted to call/anthropic/v1/messageswithx-api-keyand noAuthorizationorapi-keyleak, with and without an/anthropicapi_base suffix, and, for stream false and true, a body carryingoutput_config.formatand acompact_20260112context-management edit is asserted to reach Azure verbatim with exactlyanthropic-beta: structured-outputs-2025-11-13, so the auto-injectedcompact-2026-01-12(null forazure_aiinlitellm/anthropic_beta_headers_config.json) is proven filtered. Native/v1/messages/count_tokensis asserted through bothclient.messages.count_tokensandclient.beta.messages.count_tokens(the?beta=truespelling) to forward messages, system and tools withx-api-keyandanthropic-version, return{input_tokens}unchanged, refuse a key without model access before upstream, and fall back to the local count when the provider errors, with the fallback pinned to the constant 65 instead of read from/utils/token_counterPOST /v1/skills?beta=truewith the documented repeatedfiles[]field is asserted to reach the provider as one text part and two file parts with the exact names, filenames and bytes, and the client parses the returnedSkilllitellm/)tests/integration/messages_endpoint/providers/anthropic/test_anthropic_wire.py::test_anthropic_messages_preserves_cli_beta_safeguards_and_result[non_stream],[stream]litellm/llms/anthropic/pass_through/messages/transformation.pyshould_filter_anthropic_beta_headersreturn self._resolved_provider != "anthropic"->return Truetest_anthropic_wire.py:283assert sorted(request.headers["anthropic-beta"].split(",")) == sorted(beta.split(","))got['context-management-2025-06-27', 'interleaved-thinking-2025-05-14', 'prompt-caching-scope-2026-01-05'](Claude Code, made-up future and token-count betas stripped)...test_anthropic_gateway_wire.py::test_enabled_gateway_matches_native_messages_route[non_stream],[stream],::test_enabled_gateway_attributes_spend_to_virtual_keyreturn Truemutationtest_anthropic_gateway_wire.py:152and:316assert sorted(request.headers["anthropic-beta"].split(",")) == client_betasgot the same three betaslitellm/types/llms/anthropic.py:430deletesafeguards: ReadOnly[list[dict[str, object]] | None]fromAnthropicMessagesRequestOptionalParams(the allowlistget_requested_anthropic_messages_optional_paramreads through_anthropic_messages_optional_param_keys)test_anthropic_wire.py:297upstream whole-body assertion,safeguardsmissing from the forwarded bodytests/integration/messages_endpoint/providers/anthropic/test_anthropic_gateway_wire.py::test_shared_gateway_route_is_disabled_without_reaching_provider[messages]gateway_endpoints.py/v1/messagesaliasdependencies=_GATEWAY_ENABLED,->dependencies=(),test_anthropic_gateway_wire.py:97assert response.status_code == 404got 500, and the upstream handler saw/v1/messages...test_anthropic_gateway_wire.py::test_shared_gateway_route_is_disabled_without_reaching_provider[count_tokens]gateway_endpoints.py/v1/messages/count_tokensaliasdependencies=_GATEWAY_ENABLED,->dependencies=(),test_anthropic_gateway_wire.py:97assert response.status_code == 404got 200{"input_tokens":9}...test_anthropic_gateway_wire.py::test_enabled_gateway_count_tokens_alias_matches_native_count_tokens_routegateway_endpoints.pycount_tokens alias handlercount_tokens,->anthropic_response,test_anthropic_gateway_wire.py:249assert gateway_response.status_code == 200got 400endpoints.pycount_tokensdroptools=data.get("tools"),assert _JSON_OBJECT.validate_json(request.body) == expected_provider_bodyand line 250 got 23 instead of 41...test_anthropic_gateway_wire.py::test_enabled_gateway_matches_native_messages_route[non_stream],[stream](unchanged)gateway_endpoints.pyalias handleranthropic_responsetocount_tokensrequest.target == "/v1/messages"and typedMessagevalidation...test_anthropic_gateway_wire.py::test_enabled_gateway_refuses_model_outside_virtual_key(unchanged)auth_checksif _check_model_access_helper(toif True or _check_model_access_helper(/v1/messages...test_anthropic_gateway_wire.py::test_enabled_gateway_attributes_spend_to_virtual_key(unchanged)spend_tracking_utils.pyapi_key=str(api_key)toapi_key=""assert spend_rows == (...)got([], [])tests/integration/authorization/test_claude_code_gateway_oauth.py::test_device_authorization_polls_complete_sso_and_mints_a_model_restricted_bearergateway_endpoints.pyif not _verify_cli_sso_poll_secret(flow, poll_secret):->if not True:test_claude_code_gateway_oauth.py:231assert ... wrong_secret ... == {"error": "expired_token"}gotauthorization_pendinggateway_endpoints.pysso_complete/user_code_verifiedguardor->andtest_claude_code_gateway_oauth.py:270assert still_pending.status_code == 400got anaccess_tokenui_sso.pyif not isinstance(expected_user_code_hash, str) or not secrets.compare_digest(->if isinstance(expected_user_code_hash, bool) and not secrets.compare_digest(test_claude_code_gateway_oauth.py:279assert wrong_code_completion.status_code == 400got 200user_api_key_auth.py"models": () if team_object is not None else user_models(user_object),->"models": user_models(user_object),test_claude_code_gateway_oauth.py:422assert model_c_response.status_code == 200got 403key_model_access_deniedgateway_endpoints.py_claim_device_codereturn claims == 1->return claims >= 1assert len(successful_polls) == 1got 7 successful polls, red 3 of 3 runs...test_anthropic_count_tokens_wire.py::test_anthropic_count_tokens_forwards_body_and_refuses_a_key_without_model_access[messages_count_tokens],[beta_messages_count_tokens]if model is not None:->if model is not None and route != "/v1/messages/count_tokens":pytest.raises(anthropic.PermissionDeniedError)reports DID NOT RAISE in both cellstests/integration/providers/test_vertex_partner_messages_wire.py::test_vertex_partner_messages_uses_raw_predict_contract_and_typed_response[non_stream],[stream](unchanged)anthropic_messages_request["anthropic_version"] = "vertex-2023-10-16"assert ... request.body == expected_bodytests/integration/messages_endpoint/providers/anthropic/test_anthropic_count_tokens_wire.py::test_anthropic_count_tokens_forwards_body_and_refuses_a_key_without_model_access[messages_count_tokens],[beta_messages_count_tokens]endpoints.pycount_tokensdroptools=data.get("tools"),test_anthropic_count_tokens_wire.py:108assert result.model_dump() == {"input_tokens": _COUNTED_INPUT_TOKENS}got 23...test_anthropic_count_tokens_wire.py::test_anthropic_count_tokens_relays_an_upstream_server_error,::test_anthropic_count_tokens_relays_an_upstream_client_errorproxy_server.py_try_provider_token_countreplace theraise ProxyException(...)on a provider error withreturn None(the local fallback that #46121 removed)pytest.raises(anthropic.InternalServerError)andpytest.raises(anthropic.BadRequestError)report DID NOT RAISEtest_claude_code_gateway_oauth.py::test_device_authorization_polls_complete_sso_and_mints_a_model_restricted_bearerrefresh_tokenfromproxy_credential_response_AccessToken.model_validate_jsonfails withrefresh_token Field required...test_anthropic_wire.py::test_anthropic_messages_preserves_upstream_error_status_and_body[rate_limit],[invalid_request](unchanged)_anthropic_error_json_responsedrop**envelope,assert caught.value.response.json() == {...}...test_anthropic_wire.py::test_anthropic_messages_stream_surfaces_upstream_error_eventstreaming_model_restamp.pyrestamped_text.encode("utf-8") if index == decider else frame ...->b"" if index == decider else frame ...(dropsmessage_start)test_anthropic_wire.py:577assert cc.sse_events(response.text) == (("message_start", ...), ("error", error))got only theerrorevent...test_anthropic_wire.py::test_anthropic_messages_preserves_image_document_and_tool_result_blocks(unchanged)documentblocks afterstrip_advisor_blocks_from_messagesmessagestests/integration/providers/test_azure_ai_claude_messages_wire.py::test_azure_ai_claude_messages_preserves_target_auth_beta_and_typed_response[*](4 cases, unchanged)litellm/llms/azure_ai/anthropic/messages_transformation.pyomitapi_base + "/v1/messages"assert request.target == api_path...test_azure_ai_claude_messages_wire.py::test_azure_ai_claude_messages_filters_auto_injected_betas_by_azure_support[non_stream],[stream]litellm/llms/anthropic/pass_through/messages/transformation.py:106return self._resolved_provider != "anthropic"->return Falsetest_azure_ai_claude_messages_wire.py:185assert request.headers.get("anthropic-beta") == expected_betagotcompact-2026-01-12,structured-outputs-2025-11-13tests/integration/providers/test_anthropic_skills_create_wire.py::test_anthropic_skill_create_forwards_repeated_files_as_file_partshttp_parsing_utils.pyparsed_form_data.setdefault(clean_key, []).append(value)->parsed_form_data[clean_key] = [value]assert tuple(_part_summary(part) ...) == (("display_title", ...), ("files[]", "synthetic-skill/SKILL.md", ...), ("files[]", "synthetic-skill/helper.py", ...))saw one file part, and line 67 got 500Every mutation path above is the real path at this tip (
litellm/llms/anthropic/experimental_pass_through/no longer exists, the native config lives inlitellm/llms/anthropic/pass_through/messages/transformation.py). Mutations on disjoint test nodes were applied together in one proxy restart (three restarts, then the stream mutation and the two OAuth poll mutations each on their own restart), each node went red on the named assertion, everything was reverted (git status litellm/clean) and both group runs below are the green rerunsAnswers to the reviewer at 12e4a48, with evidence from this rig:
_mint_access_tokenteam_models=[]) is an equivalent mutant. The test stayed green under it because_refresh_session_token_grantsinuser_api_key_auth.pyre-reads the team's models from Postgres on every session-token request, so the minted claim is never the source of truth. The team grant is now asserted (user[A, B], team[A, C]) and the refresh line itself is the mutation that kills itanthropic-betanever reaches that transformation on main, so the provider receives onlytoken-counting-2024-11-01. The merged-header contract is pinned as aBUGskip below for both SDK spellingsget_supported_anthropic_messages_paramshas no request-path caller on native/v1/messagesAnswers to the reviewer at ab52731, with evidence from this rig at 6e71084 (origin/main merged in):
test_azure_ai_claude_messages_filters_auto_injected_betas_by_azure_supportdrives betas LiteLLM injects from the body, which do reach the filter, and 8R2 now turns both cells red withcompact-2026-01-12leaking. The older Azure test no longer claims beta filteringget_supported_anthropic_messages_paramsis dead on this route. The allowlist that actually drops unknown top-level fields isAnthropicMessagesRequestOptionalParams, and deletingsafeguardsthere (1T) turns both safeguards cells red on the whole-body assertion, so the allowlist-drift claim of gap 1 is now provenlitellm/llms/anthropic/pass_through/messages/transformation.py, the real path at this tiplitellm/, so they are not fixed here and the halves they pin are recorded as partial, not covered, in the table that followsAnswers to the reviewer at 6e71084, with evidence from this rig at 52a85d5:
None == '7', 529 reaches the client as HTTP 500api_error, count_tokens returns 65 instead of 73 withthinking,tool_choiceandoutput_configmissing from the provider body, count_tokens sends onlytoken-counting-2024-11-01for both SDK spellings, and Azure gets noanthropic-beta. They are real bugs in product code this tests-only PR may not change, so those halves stay partial and are listed as dropped below rather than claimed coveredsorted(set(...))expectation is gone at all three sites. Each now compares the upstream header token-for-token with the header the client sent (beta.split(",")andcc.CLI_BETA.split(",")), so any dropped, added or duplicated beta fails. Order is not compared on purpose:merge_anthropic_beta_headerssorts by design and Anthropic reads the header as a set of flags, so pinning the client's order would pin a fact we do not owntest_anthropic_messages_stream_ending_without_message_stop_surfaces_an_error_eventis new. The upstream sendsmessage_start,content_block_startand onetext_delta, then closes cleanly. With the skip removed it fails attest_anthropic_wire.py:649(650 with the skip line) because the client gets exactly those three events and HTTP 200, noerrorevent.BaseAnthropicMessagesStreamingIterator.async_sse_wrapperappends that event, but native/v1/messagesstreams throughPassThroughStreamingHandler.chunk_processor, which readsmessage_stoponly to decide prompt-cache evidence for logging and never appends that event to the client stream. A dropped-connection variant was tried and dropped: the proxy had not committed headers yet, so it answers 500 with an Anthropic envelope, which is not the truncated-200 shape and depends on timingAnswers to the reviewer at dff0cb2, with evidence from this rig at 7a536b7:
litellm/device_codepolls and asserts exactly one 200 with a valid access token and 7expired_token400s, while the later sequential replay check stays. Mutating_claim_device_codereturn claims == 1->return claims >= 1alone turns it red 3 of 3 runs with 7 successful polls, and it is green twice after revertsafeguardsfrom the supported-params list" is an equivalent mutant becauseAnthropicMessagesConfig.get_supported_anthropic_messages_paramshas no callers. Gap 1's allowlist claim rests only on theAnthropicMessagesRequestOptionalParamsTypedDict-key mutation (1T), which is killedkey_model_access_deniedJSON as the Anthropic contract. It asserts what an Anthropic SDK user sees,anthropic.PermissionDeniedErrorwith status 403 and the requested model in the message, plus no upstream request. Skipping the model check for/v1/messages/count_tokensturns both spellings red withDID NOT RAISE PermissionDeniedError. The current body shape is recorded here only as a product observationrefresh_token,user_idandteam_idto the device-code token response. The two count_tokens fallback tests now assert the relayed 500 and 400 through the Anthropic SDK, and the OAuth test asserts the full new token body and theinvalid_requestanswer for a refresh grant with no token. M9R (tools=Nonein local counting) no longer applies since the error path never counts locally, so its row is droppedmodel_b, the placeholder-free f-string, the unusedWireimport) and the changed files areruff formatcleanCoverage at this tip:
thinking,tool_choice,output_configand the merge of the clientanthropic-betaare not covered, their tests are BUG skips and the contract stays unproven until the product fix landserrorframe are covered. Upstreamretry-afteron 429, 529overloaded_errorpassthrough, and theerrorevent for a stream closed beforemessage_stopare not covered, their tests are BUG skips and those contracts stay unproven until the product fixes landProduct bugs on current main, each pinned with
pytest.skip("BUG: ...")as the first line of a full test body:test_anthropic_wire.py::test_anthropic_messages_preserves_upstream_rate_limit_retry_after: an upstream 429 withretry-after: 7reaches the client as a 429 Anthropic envelope but with noretry-afterheader (test_anthropic_wire.py:464gotNone)test_anthropic_wire.py::test_anthropic_messages_preserves_upstream_overloaded_error: an upstream 529overloaded_errorreaches the client as HTTP 500api_error(test_anthropic_wire.py:516got 500)test_anthropic_count_tokens_wire.py::test_anthropic_count_tokens_preserves_thinking_tool_choice_and_output_config:thinking,tool_choiceandoutput_confignever reach the provider count call, and the client gets the local count (65) instead of the provider's (73)test_anthropic_count_tokens_wire.py::test_anthropic_count_tokens_merges_the_client_beta_with_the_token_counting_beta[messages_count_tokens],[beta_messages_count_tokens]: a clientanthropic-beta: client-future-beta-2099-01-01is dropped, and the provider receives onlytoken-counting-2024-11-01instead ofclient-future-beta-2099-01-01,token-counting-2024-11-01test_anthropic_wire.py::test_anthropic_messages_stream_ending_without_message_stop_surfaces_an_error_event: an upstream stream that closes aftermessage_startand a delta, with nomessage_stop, reaches the client as HTTP 200 with those events and noerrorevent (test_anthropic_wire.py:649with the skip removed)test_azure_ai_claude_messages_wire.py::test_azure_ai_claude_messages_forwards_supported_beta:interleaved-thinking-2025-05-14, listed as supported forazure_aiinlitellm/anthropic_beta_headers_config.json, is dropped and noanthropic-betareaches AzureLinear ticket
Related to LIT-6816 and LIT-7940
Pre-Submission checklist
Screenshots / Proof of Fix
Rig set up as in
.circleci/scripts/run_integration.sh: Postgrescircle_test, Redis, the owned scripted upstream on 127.0.0.1:8190 and the proxy on 127.0.0.1:4000After (de0c18a, a merge of origin/main onto 7a536b7 that picks up the migration lock fix)
providers
30 passed, 7 skipped in 86.24sat de0c18a30 passed, 7 skippedat 7a536b7 and twice at 744c957 before the earlier mergesmanagement
1 passed in 87.37sat de0c18a1 passedtwice at 7a536b7make check:check: PASS.ruff check,ruff check --config ruff-tests.tomlandruff format --checkpass on the changed filesType
Test
Caveats (if any)
Low
safeguardsfromget_supported_anthropic_messages_paramsis not killableAnthropicMessagesRequestOptionalParamsmutation is killed insteadteam_modelsmutation is not killableanthropic-betais compared as a token multiset, not in the client's orderNote
Low Risk
Test-only changes under
tests/integration/with no production code modifications; risk is limited to CI runtime and test maintenance.Overview
Adds wire-based integration tests that drive the real LiteLLM proxy against scripted upstream peers and assert exact provider requests plus Anthropic SDK–parsed responses—no
litellm/product changes.Coverage spans native
/v1/messages(CLIanthropic-beta, safeguards, rich blocks, error envelopes, mid-stream SSE errors),/v1/messages/count_tokens(both SDK spellings, model access, upstream error relay), Claude Code gateway aliases (disabled 404, parity with native routes, spend attribution), a full device OAuth + generic SSO flow (poll semantics, concurrent token claim, team/user model grants), Vertex:rawPredict/:streamRawPredict, Azure AI/anthropic/v1/messagesauth/path/beta filtering, andPOST /v1/skillsmultipartfiles[]forwarding.Several full test bodies are
pytest.skip("BUG: …")to document known gaps on main (e.g.retry-afteron 429, 529 passthrough, count_tokens field/beta forwarding, truncated streams, Azure supported beta) until product fixes land.Reviewed by Cursor Bugbot for commit de0c18a. Bugbot is set up for automated code reviews on this repo. Configure here.
litellm/is empty)litellm/is empty)litellm/is empty)litellm/is empty)litellm/is empty)