litellm/tests/unit/llms/chatgpt/test_chatgpt_common_utils.py
Onur C. Cakmak d9aae590e3
fix(chatgpt): derive the upstream session id from prompt_cache_key (#42014)
* fix(chatgpt): derive Responses session id from prompt_cache_key

ChatGPT partitions the Codex prompt cache by the Responses session-id
header (the Codex CLI sends a stable per-conversation key derived from
prompt_cache_key). The provider only consulted explicit session ids
and otherwise stamped a per-request uuid4, so no turn ever reused the
prompt cache -- 0% cache hits on repeat turns, an order-of-magnitude
quota/cost multiplier on subscription accounts.

Resolution order after this change:
explicit session config (session_id / litellm_session_id /
metadata.session_id) > prompt_cache_key (sanitized with
_safe_header_value) > litellm-internal ids > uuid4.

Two guards, mirroring get_fireworks_session_id:
- proxy-generated session ids (missing_session_id: "generate") are
  per-request and are skipped, checked in both "metadata" and
  "litellm_metadata" (LITELLM_METADATA_ROUTES, responses included)
- internal per-request ids (litellm_trace_id / litellm_call_id) lose
  to a stable conversation key

Supersedes the body-key forwarding of #37630: a random session header
overrides the body key on the provider side, so the header must carry
the caller's key. Related: #29978, #29993.

Verified against a real ChatGPT Codex account: stable session id ->
97-100% cached on repeat turns; random per-request -> 0%.

* style: ruff format

* fix(chatgpt): address review - hash unsafe cache keys, move tests, drop comments

- hash prompt_cache_keys containing header-unsafe chars instead of
  mapping them through _safe_header_value, whose replacement char could
  collapse distinct keys onto one cache shard and serialize unrelated
  requests (greptile review)
- strip the explanatory comment blocks per AGENTS.md comment policy
- move the tests into the existing mapped responses transformation test
  file per AGENTS.md test-placement rule

* fix(chatgpt): keep session typing and test diff scoped

* fix(chatgpt): hash surrogate cache keys, type session params, flatten tests

* test(chatgpt): record upstream requests with a mock instead of appending to a list

* fix(chatgpt): keep proxy-mapped session headers ahead of body session_id and ignore non-string cache keys

* fix(chatgpt): hash cache keys with leading or trailing whitespace so the session header stays valid

* test(chatgpt): type the session id test parameters

* fix(chatgpt): keep trace ids copied into litellm_session_id from outranking prompt_cache_key

* fix(chatgpt): mark session ids copied from trace_id so explicit ones keep precedence

* fix(chatgpt): keep the trace-id session marker out of provider params

The marker now uses the _litellm_ internal prefix, so bridges that pass litellm_params back into completion() drop it instead of sending it as a provider param

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
2026-10-28 10:57:51 -07:00

165 lines
6.8 KiB
Python

import base64
import json
from collections.abc import Mapping
from typing import Final
import h11
import pytest
from litellm.constants import SESSION_ID_GENERATED_METADATA_KEY
from litellm.litellm_core_utils.get_litellm_params import get_litellm_params
from litellm.llms.chatgpt.common_utils import (
extract_chatgpt_account_id,
get_chatgpt_client_credential,
get_chatgpt_session_id,
is_chatgpt_oauth_key,
select_chatgpt_client_credential_headers,
)
def _make_jwt(payload: dict) -> str:
def _b64(obj: dict) -> str:
raw = json.dumps(obj, separators=(",", ":")).encode("utf-8")
return base64.urlsafe_b64encode(raw).decode("utf-8").rstrip("=")
return f"{_b64({'alg': 'none', 'typ': 'JWT'})}.{_b64(payload)}."
CHATGPT_JWT = _make_jwt({"https://api.openai.com/auth": {"chatgpt_account_id": "acct-alice"}})
CHATGPT_JWT_WITHOUT_ACCOUNT = _make_jwt({"https://api.openai.com/auth": {"user_id": "user-1"}})
NON_CHATGPT_JWT = _make_jwt({"sub": "someone", "https://api.openai.com/auth": "not-an-object"})
class TestExtractChatGPTAccountId:
def test_reads_account_id_from_auth_claim(self):
assert extract_chatgpt_account_id(CHATGPT_JWT) == "acct-alice"
@pytest.mark.parametrize(
"token",
[None, "", "sk-proj-not-a-jwt", "header.only", NON_CHATGPT_JWT, CHATGPT_JWT_WITHOUT_ACCOUNT],
)
def test_returns_none_without_a_usable_account_claim(self, token):
assert extract_chatgpt_account_id(token) is None
class TestIsChatGPTOAuthKey:
def test_recognizes_bearer_and_raw_chatgpt_jwt(self):
assert is_chatgpt_oauth_key(CHATGPT_JWT)
assert is_chatgpt_oauth_key(f"Bearer {CHATGPT_JWT}")
assert is_chatgpt_oauth_key(f"Bearer {CHATGPT_JWT_WITHOUT_ACCOUNT}")
@pytest.mark.parametrize(
"value", [None, "", "Bearer sk-proj-platform-key", "Bearer not.a.jwt", _make_jwt({"sub": "x"})]
)
def test_rejects_non_chatgpt_credentials(self, value):
assert not is_chatgpt_oauth_key(value)
class TestSelectChatGPTClientCredentialHeaders:
def test_account_header_alone_is_not_forwarded(self):
selected = select_chatgpt_client_credential_headers(
{"chatgpt-account-id": "acct-alice", "authorization": "Bearer sk-proj-platform-key"}
)
assert dict(selected) == {}
assert get_chatgpt_client_credential({"chatgpt-account-id": "acct-alice"}) is None
def test_forwards_only_bearer_and_account_context(self):
selected = select_chatgpt_client_credential_headers(
{
"Authorization": f"Bearer {CHATGPT_JWT}",
"ChatGPT-Account-Id": "acct-explicit",
"x-litellm-api-key": "sk-gateway",
"user-agent": "codex",
}
)
assert dict(selected) == {"Authorization": f"Bearer {CHATGPT_JWT}", "ChatGPT-Account-Id": "acct-explicit"}
credential = get_chatgpt_client_credential(selected)
assert credential is not None
assert credential.access_token == CHATGPT_JWT
assert credential.account_id == "acct-explicit"
def test_account_id_falls_back_to_jwt_claim(self):
credential = get_chatgpt_client_credential({"authorization": f"Bearer {CHATGPT_JWT}"})
assert credential is not None
assert credential.account_id == "acct-alice"
@pytest.mark.parametrize("scheme", ["Bearer", "bearer", "BEARER"])
def test_bearer_scheme_is_case_insensitive(scheme):
credential = get_chatgpt_client_credential({"authorization": f"{scheme} {CHATGPT_JWT}"})
assert credential is not None
assert credential.access_token == CHATGPT_JWT
assert credential.account_id == "acct-alice"
def test_other_authentication_schemes_are_not_chatgpt_logins():
assert not is_chatgpt_oauth_key(f"Basic {CHATGPT_JWT}")
class TestGetChatGPTSessionId:
@pytest.mark.parametrize(
"explicit",
[
{"litellm_session_id": "chosen"},
{"session_id": "chosen"},
{"metadata": {"session_id": "chosen"}},
get_litellm_params(litellm_session_id="chosen", metadata={"trace_id": "chosen"}),
],
)
def test_explicit_session_id_wins_over_prompt_cache_key(self, explicit: Mapping[str, object]) -> None:
assert get_chatgpt_session_id({**explicit, "prompt_cache_key": "conv-123"}) == "chosen"
@pytest.mark.parametrize(
"request_scoped",
[
{"litellm_trace_id": "trace-1"},
{"litellm_call_id": "call-1"},
get_litellm_params(metadata={"trace_id": "trace-1"}),
get_litellm_params(litellm_metadata={"trace_id": "trace-1"}),
{"litellm_session_id": "gen-1", "metadata": {"session_id": "gen-1", SESSION_ID_GENERATED_METADATA_KEY: True}},
{
"litellm_session_id": "gen-1",
"litellm_metadata": {"session_id": "gen-1", SESSION_ID_GENERATED_METADATA_KEY: True},
},
],
)
def test_prompt_cache_key_wins_over_request_scoped_ids(self, request_scoped: Mapping[str, object]) -> None:
assert get_chatgpt_session_id({**request_scoped, "prompt_cache_key": "conv-123"}) == "conv-123"
@pytest.mark.parametrize(
"mapped_header",
[
{
"litellm_session_id": "header-session",
"metadata": {"trace_id": "header-session", "session_id": "header-session"},
},
get_litellm_params(metadata={"trace_id": "header-session", "session_id": "header-session"}),
],
)
def test_proxy_mapped_session_header_wins_over_body_session_id(self, mapped_header: Mapping[str, object]) -> None:
assert (
get_chatgpt_session_id({**mapped_header, "session_id": "body-session", "prompt_cache_key": "conv-123"})
== "header-session"
)
@pytest.mark.parametrize("prompt_cache_key", [{"tenant": "a"}, 12345, True, ["x", "y"]])
def test_non_string_prompt_cache_key_is_ignored(self, prompt_cache_key: object) -> None:
assert get_chatgpt_session_id({"prompt_cache_key": prompt_cache_key, "litellm_call_id": "call-1"}) == "call-1"
@pytest.mark.parametrize(
"first, second",
[
("a\nb", "a\tb"),
(json.loads('"conv-\\ud800"'), json.loads('"conv-\\udc00"')),
("conv-123 ", " conv-123"),
],
)
def test_header_unsafe_cache_keys_map_to_distinct_stable_header_values(self, first: str, second: str) -> None:
first_id: Final = get_chatgpt_session_id({"prompt_cache_key": first})
second_id: Final = get_chatgpt_session_id({"prompt_cache_key": second})
assert first_id is not None and second_id is not None
assert first_id == get_chatgpt_session_id({"prompt_cache_key": first})
assert first_id != second_id
for value in (first_id, second_id):
h11.Request(method="POST", target="/", headers=[("host", "chatgpt.com"), ("session_id", value)])