Skip to content

chore(release): v1.103.6 patch - #47522

Merged
yuneng-berri merged 4 commits into
stable/1.103.xfrom
patch_f62f7f90
Oct 20, 2026
Merged

yuneng-berri merged 4 commits into
stable/1.103.xfrom
patch_f62f7f90

Conversation

@yuneng-berri

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • stable/1.103.x is missing 2 fixes from main that stable/1.102.x already ships
  • Upgrading from 1.102.x to 1.103.5 loses both today

How it solves it:

  • One -x cherry-pick per main PR, in main merge order, plus 1 test-only prerequisite
  • No pricing data sync on this line tonight
  • Bumps litellm 1.103.5 -> 1.103.6

Intentional product change: a refused upstream realtime handshake now sends an error event and closes 1008, 1013 or 1011, instead of a bare 1011 or 1006 close with no event

Backport

Added prerequisites

Adaptation notes

#42388

  • close_after_upstream_handshake_refusal wraps websocket.close() on this line. Without it, a client that hangs up while the upstream handshake is pending makes the close raise, and the Router retries the refused handshake. A local proxy pointed at an upstream that refuses with 401 opened 3 upstream handshakes per client connection with the unwrapped close and 1 on the line tip
  • The source PR deliberately left the close unwrapped, expecting the proxy's generic handler to absorb a raise. On this line the raise reaches the Router's retry loop first
  • Main has the same unwrapped close. It was not run on main here, but main likely needs the same change
  • A new parametrized test pins that the helper still tries the 1008 close and returns when that close raises. It fails with the wrap removed or narrowed to RuntimeError
#42388 interdiff against main 2bab39e
--- main 2bab39e374
+++ line c66597f432
@@ -48,10 +48,13 @@
 +        await websocket.send_text(realtime_error_event(message, error_type="server_error"))
 +    except Exception:  # noqa: BLE001  # best-effort notice: a dead client socket must not skip the close below
 +        pass
-+    await websocket.close(
-+        code=upstream_handshake_close_code(status_code),
-+        reason=websocket_close_reason(message, fallback="Upstream handshake rejected"),
-+    )
++    try:
++        await websocket.close(
++            code=upstream_handshake_close_code(status_code),
++            reason=websocket_close_reason(message, fallback="Upstream handshake rejected"),
++        )
++    except Exception:  # noqa: BLE001  # the client may have closed the socket already; closing twice is not an error
++        pass
 diff --git a/litellm/llms/azure/realtime/handler.py b/litellm/llms/azure/realtime/handler.py
 --- a/litellm/llms/azure/realtime/handler.py
 +++ b/litellm/llms/azure/realtime/handler.py
@@ -288,6 +291,7 @@
 +from typing import cast
  
  import pytest
++from starlette.websockets import WebSocketDisconnect
  
  from litellm.litellm_core_utils.realtime_errors import (
      WEBSOCKET_CLOSE_REASON_MAX_BYTES,
@@ -354,6 +358,35 @@
 +    await close_after_upstream_handshake_refusal(websocket, 500)
 +
 +    assert websocket.closed == (1011, "Upstream realtime handshake rejected with HTTP 500")
++
++
++@pytest.mark.asyncio
++@pytest.mark.parametrize(
++    "close_error",
++    [
++        RuntimeError('Cannot call "send" once a close message has been sent.'),
++        OSError("client disconnected"),
++        WebSocketDisconnect(code=1006),
++    ],
++)
++async def test_close_after_upstream_handshake_refusal_returns_when_client_already_closed(close_error: Exception):
++    class _ClosedWebSocket(_RecordingWebSocket):
++        def __init__(self) -> None:
++            super().__init__()
++            self.close_attempts: list[int] = []
++
++        async def send_text(self, data: str) -> None:
++            raise OSError("client disconnected")
++
++        async def close(self, code: int = 1000, reason: str | None = None) -> None:
++            self.close_attempts.append(code)
++            raise close_error
++
++    websocket = _ClosedWebSocket()
++
++    await close_after_upstream_handshake_refusal(websocket, 401)
++
++    assert websocket.close_attempts == [1008]
 diff --git a/tests/test_litellm/llms/azure/realtime/__init__.py b/tests/test_litellm/llms/azure/realtime/__init__.py
 new file mode 100644
 --- /dev/null

#44508 has context-only divergences, the fix's own lines are byte-for-byte main's

  • The method after the new claim_async_success_log is still has_run_logging on this line (main renamed it mark_logging_complete), so it stays and the new method sits in front of it, same as the stable/1.102.x backport
  • Unit tests live in tests/test_litellm/ on this line. Both test files hit empty-HEAD append conflicts, so each was reset to the line's copy and only the PR's own lines were appended
  • The new integration test is registered in tests/integration/contracts.json with its covers marker, since this line enforces that manifest at collection and main no longer does
  • The nested-wrapper test fails on the line tip (assert 2 == 1, logged twice) and passes with the pick
#44508 interdiff against main 157d96d
--- main 157d96dcd0
+++ line cd788ce1aa
@@ -7,8 +7,8 @@
          self._enqueue_deferred_logging: Callable[[], None] | None = None
 +        self._async_success_scheduled: bool = False
          self._on_detached_stream_failure: Callable[[Exception], Awaitable[None]] | None = None
-         self.shadow_eval_request_snapshot: GuardrailRequestSnapshot | None = None
  
+     def set_response_timing_metrics(self, timing_metrics: Mapping[str, float]) -> None:
 @@ class Logging(LiteLLMLoggingBaseClass):
          except Exception:
              return True
@@ -22,7 +22,7 @@
 +        self._async_success_scheduled = True
 +        return True
 +
-     def mark_logging_complete(
+     def has_run_logging(
          self,
          event_type: Literal["async_success", "sync_success", "async_failure", "sync_failure"],
 diff --git a/litellm/utils.py b/litellm/utils.py
@@ -47,6 +47,19 @@
  
      def _enqueue_async_logging() -> None:
          asyncio.create_task(
+diff --git a/tests/integration/contracts.json b/tests/integration/contracts.json
+--- a/tests/integration/contracts.json
++++ b/tests/integration/contracts.json
+@@
+     ],
+     "tests/integration/providers/test_responses_bridge_incomplete.py::test_chat_stream_over_responses_deployment_folds_message_and_two_function_calls_into_one_choice": [
+       "other.provider_wire.responses_bridge.stream_message_and_two_calls_fold_numbered_0_1"
++    ],
++    "tests/integration/spend/test_responses_bridge_spend_once.py::test_bridged_chat_completion_above_log_offload_threshold_logs_and_charges_once": [
++      "quota_management.spend_tracking.responses_bridge.logs_and_charges_once_above_offload_threshold"
+     ]
+   },
+   "browser": {
 diff --git a/tests/integration/spend/test_responses_bridge_spend_once.py b/tests/integration/spend/test_responses_bridge_spend_once.py
 new file mode 100644
 --- /dev/null
@@ -118,6 +131,7 @@
 +
 +
 +@pytest.mark.timeout(120)
++@pytest.mark.covers("quota_management.spend_tracking.responses_bridge.logs_and_charges_once_above_offload_threshold")
 +def test_bridged_chat_completion_above_log_offload_threshold_logs_and_charges_once(gateway: Gateway) -> None:
 +    prompt_prefix: Final = f"spend once {uuid4().hex[:8]} "
 +    long_prompt: Final = (prompt_prefix + "lorem ipsum " * 30_000)[:300_000]
@@ -163,9 +177,9 @@
 +            seconds=70,
 +        )
 +        assert float(str(key_spend[0]["spend"])) == pytest.approx(EXPECTED_SPEND), key_spend
-diff --git a/tests/unit/litellm_core_utils/test_litellm_logging.py b/tests/unit/litellm_core_utils/test_litellm_logging.py
---- a/tests/unit/litellm_core_utils/test_litellm_logging.py
-+++ b/tests/unit/litellm_core_utils/test_litellm_logging.py
+diff --git a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py
+--- a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py
++++ b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py
 @@ def _interactions_logging_obj(stream: bool, call_type: str = "acreate"):
          messages=[],
          stream=stream,
@@ -175,10 +189,10 @@
          litellm_call_id="interactions-call-id",
          function_id="interactions-fn-id",
      )
-@@ def test_get_custom_logger_compatible_class_does_not_match_generic_api_logger(
-         assert logging_module.get_custom_logger_compatible_class(integration) is None
-     finally:
-         logging_module._in_memory_loggers.clear()
+@@ class TestAzurePTUSpilloverCost:
+         finally:
+             litellm.model_cost.pop(custom_model_id, None)
+             self._unregister_models()
 +
 +
 +@pytest.mark.asyncio
@@ -237,13 +251,13 @@
 +    await completion
 +
 +    assert counting_logger.logged_results == [completed, in_progress], counting_logger.logged_results
-diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py
---- a/tests/unit/test_utils.py
-+++ b/tests/unit/test_utils.py
-@@ def test_function_setup_never_logs_the_ocr_data_uri_payload() -> None:
- 
-     assert logged == [{"role": "user", "content": f"data:application/pdf;base64 ({len(payload)} chars)"}]
-     assert payload not in str(logged)
+diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.py
+--- a/tests/test_litellm/test_utils.py
++++ b/tests/test_litellm/test_utils.py
+@@ def test_calculate_max_parallel_requests_precedence(
+         )
+         == expected
+     )
 +
 +
 +@pytest.mark.asyncio

Gate

  • Targeted tests: 8 files, 1306 passed, 0 new failures, 3 failures already red on the line tip
  • Cost map tests: 98 files, 5083 passed, 0 new failures, 1 failure already red on the line tip. Run at 42f52a591b, which differs from the tip only in test_realtime_errors.py, not a cost map test
  • Importer scan: 0 hits
  • Format check: ruff 0.15.3, 7 files clean
  • Gauntlet-mini: SURVIVED after 3 fix tries, 5/5 lenses, run gm-193baa137892, reviewed fe02b14e96
    • Round 1, REFUTED at the first tip. The new integration test was missing from the line's contracts manifest, and two redaction tests went stale. Fixed by registering the test and adding test(realtime): drop legacy InvalidStatusCode tests and pin websockets imports #42624
    • Round 2, REFUTED. A verifier confirmed the Router retry described above. Fixed by wrapping the close
    • Round 3, the wrap's first test asserted nothing and pushed the test quality gate one over its limit. The test now asserts the attempted close code, and the gate passes
    • The largest finding left open is the /v1/responses budget reservation in Caveats, not verdict-flipping

User Flow

#42388

Before: a developer connecting to a realtime deployment whose Azure credential is rejected sees the socket vanish with no explanation

  1. They run wscat -c "wss://litellm-domain/v1/realtime?model=azure-realtime" -H "Authorization: Bearer sk-..."
  2. wscat prints Connected (press CTRL+C to quit)
  3. Nothing arrives, then wscat prints Disconnected (code: 1006, reason: "")
  4. The same key against POST https://litellm-domain/v1/chat/completions works, so they cannot tell whether the proxy, the key, or the provider is broken

After: the same connection tells them exactly what the upstream said and closes cleanly

  1. They run wscat -c "wss://litellm-domain/v1/realtime?model=azure-realtime" -H "Authorization: Bearer sk-..."
  2. wscat prints Connected (press CTRL+C to quit)
  3. They receive {"type": "error", "error": {"type": "server_error", "message": "Upstream realtime handshake rejected with HTTP 401"}}
  4. wscat prints Disconnected (code: 1008, reason: "Upstream realtime handshake rejected with HTTP 401")

#42624

Before: a contributor running the realtime unit tests on main gets two failures unrelated to their change, and cannot rerun a refusal test on its own

  1. They run uv run pytest tests/test_litellm/test_redact_string_in_error_paths.py -k realtime
  2. TestOpenAIRealtimeRedaction::test_invalid_status_code_redacts_reason and TestAzureRealtimeRedaction::test_invalid_status_code_redacts_reason fail with assert 1011 == 403
  3. They run uv run pytest tests/test_litellm/llms/azure/realtime/test_handler.py::test_async_realtime_upstream_handshake_refusal_sends_error_event_then_policy_close to look at one refusal test on its own
  4. It fails with AttributeError: module 'websockets' has no attribute 'exceptions', though the whole file passes

After: the same commands pass, and nothing changes for proxy users since only tests move

  1. They run uv run pytest tests/test_litellm/test_redact_string_in_error_paths.py -k realtime
  2. 4 passed, the two legacy tests are gone
  3. They run uv run pytest tests/test_litellm/llms/azure/realtime/test_handler.py::test_async_realtime_upstream_handshake_refusal_sends_error_event_then_policy_close
  4. 1 passed

#44508

Before: a developer sends one large chat request and is billed twice in LiteLLM's own accounting

  1. They send POST https://litellm-domain/v1/chat/completions to a openai/responses/gpt-5.6-luna model with ~300k characters of message text, no streaming
  2. The response comes back normally, and the provider bills one call
  3. https://litellm-domain/ui/?page=logs shows two rows for the request, and the key and team budgets drop by twice the real cost

After: the same request is logged once

  1. They send the same POST https://litellm-domain/v1/chat/completions
  2. The response comes back normally
  3. The logs page shows one row, and the key and team budgets drop by the real cost

Relevant issues

Related to #44500, fixed on main by #44508

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Type

🐛 Bug Fix
✅ Test

Caveats (if any)

Medium

Low

  • No live-proxy proof, and CI does not run on stable PRs
  • 3 targeted test failures were already red on the line tip
  • The close wrap exists only on this line, main still raises there
  • The new integration spend test was collected but not run here
  • A custom logging object without claim_async_success_log now raises on success, real ones are fine
  • The /v1/responses refusal event says "realtime" and has no status field, same as main
  • 3 of 5 refusal catch sites are not pinned by tests, same as main

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

devin-ai-integration Bot and others added 4 commits October 20, 2026 01:06
…t and policy close (#42388)

* fix(realtime): surface an upstream handshake refusal as an error event and policy close

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(realtime): tidy the handshake refusal e2e

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(realtime): keep upstream exception text out of the Azure client error

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* refactor(realtime): map handshake refusal close codes with a lookup

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>
(cherry picked from commit 2bab39e)
…s imports (#42624)

The two redaction tests raised the deprecated InvalidStatusCode, which the
websockets 15 asyncio client never raises, and asserted the raw 403 close
code that the handshake refusal path replaced with 1008. The refusal path
builds its close reason from the status code alone, so there is no secret
to redact there, and the handshake refusal tests already cover the error
event and the 1008 close.

Those refusal tests only passed when run after a sibling test had imported
websockets.asyncio.client, since websockets lazy-loads its exceptions
submodule. Importing InvalidStatus, Response, and Headers from their own
submodules makes them pass in any order.

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
(cherry picked from commit 38f0eb8)
…chat to Responses bridge (#44508)

* fix(logging): claim the async success dedup flag before the first await

Nested @client wrappers on the chat -> Responses bridge schedule two async
success tasks on one logging object. The dedup flag was checked at the top
of _async_success_handler_body but only set after several awaits; the
worker-thread base64 offload for messages >= 256 KiB yields there, so the
second task passed the same check and the request was logged twice
(two SpendLogs rows, key/team/daily spend counted twice).

Fixes #44500

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(logging): serialise async success handlers per logging object instead of claiming early

Claiming the dedup flag before the first await (previous commit) let a first
handler that is cancelled before its callbacks run (e.g. by the logging
worker's per-coroutine timeout) suppress the second one, losing the request's
success accounting. Serialise non-streaming handlers on the same Logging
object with an asyncio.Lock kept in a module-level WeakKeyDictionary: the
second handler waits, then skips if the first logged, or logs itself if the
first raised or was cancelled first. Streaming chunk logging is not locked.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(integration): pin one spend row and one key charge for large bridged chat completions

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(integration): wait for the large request's spend row before asserting

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(logging): use fixed timestamps in async success dedup tests

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* style(logging): trim the async success dedup lock comment

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(logging): reset background interaction dedupe under the success dedup lock

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(logging): use a fixed start time in the interactions logging helper

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix: claim the async success log at schedule time instead of locking the handler

Nested @client wrappers (chat over the Responses bridge, Anthropic Messages over the chat adapter) exit with one shared Logging object and each queued their own async success handler. The handler checked has_logged_async_success before its awaited work and set it after, so both could pass the check and the request was logged and billed twice.

_schedule_async_success_logging now claims the log on the Logging object synchronously through claim_async_success_log, and a later wrapper returns without enqueuing. There is no await between the check and the decision, so no lock is needed. The per-object asyncio.Lock, the WeakKeyDictionary that held it and the locked block in async_log_background_interaction_completion are gone.

Tests: the regression test moves to tests/unit/test_utils.py and drives two _dispatch_success_logging exits with one Logging object through the logging worker, asserting one log with the inner result. It fails without the claim. The cancelled-handler test is dropped since a second wrapper no longer retries. The background interaction completion test stays.
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(logging): pin the background completion event order and name the innermost wrapper in the claim docstrings

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(integration): send one bridged request and assert the inner Responses result is the logged one

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: kerry <kerry@berri.ai>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 157d96d)
litellm 1.103.5 already shipped, so the next release off this line is 1.103.6
@CLAassistant

CLAassistant commented Oct 20, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
2 out of 3 committers have signed the CLA.

✅ hektorjg
✅ yuneng-berri
❌ devin-ai-integration[bot]
You have signed the CLA already but the status is still pending? Let us recheck it.

@yuneng-berri
yuneng-berri marked this pull request as ready for review October 20, 2026 16:08
@yuneng-berri
yuneng-berri requested a review from a team October 20, 2026 16:08
@yuneng-berri
yuneng-berri merged commit dce7feb into stable/1.103.x Oct 20, 2026
7 of 9 checks passed
@yuneng-berri
yuneng-berri deleted the patch_f62f7f90 branch October 20, 2026 16:10

This branch was successfully deployed

No deployments
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.

4 participants