mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
fix(proxy): retry a TLS error only while the request is being written (#4776)
## Description A corrupt TLS record after the handshake surfaces as a raw `ssl.SSLError` (for example `[SSL: RECORD_LAYER_FAILURE] record layer failure`, or the `SSLV3_ALERT_BAD_RECORD_MAC` bursts in #1615). httpcore maps `ssl.SSLError` to `ConnectError` only in `start_tls`; its `read`/`write` maps cover only anyio's resource errors and timeouts, and anyio's `TLSStream` re-raises a non-EOF `SSLError` as it is. So the error is not an `httpx.TransportError`, and the #1639 retry in `_retry_request` and `_stream_response` lets it through. That error alone does not say whether upstream received the request. This PR retries it only when httpcore reports that writing the request failed: its documented `trace` request extension emits `send_request_headers.failed` or `send_request_body.failed`. Upstream then never had a complete request to run. A TLS error raised after the request was written propagates, as on main, so a POST upstream may have accepted is never sent twice. In the streaming path it still ends as the SSE 502, now with `upstream_tls_error` instead of a generic `api_error`. What this no longer fixes: the case the first version of this PR targeted, a corrupt record in the reply on a reused HTTP/1.1 keep-alive connection, happens after the request was written. It is ambiguous, so it still fails the request (502), as on main. What it does fix: a TLS failure while the request is still being written, for example on a shared HTTP/2 connection where a large body waits for flow-control window and the read for that window hits the corrupt record. ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) ## Changes Made - `helpers.py`: `RequestWriteTrace`, an httpcore `trace` callback that records whether `send_request_headers` or `send_request_body` failed. `forbids_retry(exc)` is true for a raw `ssl.SSLError` raised after a complete write. - `server.py` (`_retry_request`) and `handlers/streaming.py` (`_stream_response`): each attempt attaches a fresh trace, and a raw `ssl.SSLError` is retried only when that trace shows the write failed. Every other retry is unchanged. The streaming exhaustion handler still catches `ssl.SSLError`, for the 502 `upstream_tls_error` SSE body. - `tests/test_h2_stream_reset_retry.py`: the SSL cases now run through real httpcore over a fake socket. An accepted POST sends one POST and propagates, in the buffered and the streaming path. A failed write is retried, in both paths. The review's harness (an `httpx.MockTransport` that records the POST, then raises `ssl.SSLError`) sends one POST. - Three test fakes of `http_client.post` accept the new `extensions` kwarg. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text $ uv run --frozen --extra dev pytest tests/test_h2_stream_reset_retry.py -q 11 passed in 0.39s # source reverted to the previous head's retry (240680df), tests kept: FAILED tests/test_h2_stream_reset_retry.py::test_retry_request_does_not_replay_a_post_upstream_received (assert 2 == 1) FAILED tests/test_h2_stream_reset_retry.py::test_stream_does_not_replay_a_post_upstream_received (assert 2 == 1) FAILED tests/test_h2_stream_reset_retry.py::test_ssl_error_without_write_evidence_is_not_retried (assert 2 == 1) 3 failed, 8 passed # source as on upstream/main (no SSL retry), tests kept: FAILED tests/test_h2_stream_reset_retry.py::test_retry_request_retries_ssl_error_while_writing_the_request FAILED tests/test_h2_stream_reset_retry.py::test_stream_does_not_replay_a_post_upstream_received (raw SSLError escapes; no upstream_tls_error 502) FAILED tests/test_h2_stream_reset_retry.py::test_stream_retries_ssl_error_while_writing_the_request 3 failed, 8 passed $ uv run --frozen --extra dev pytest <134 files: the tests this PR and main changed since200c838c, every test importing handlers.streaming, and every test calling _retry_request, _stream_response or a fake http_client> -q 2457 passed, 2 failed, 22 skipped in 178s # both failures are timing assertions in test_read_maturation_handler_nobust.py, which replaces # _retry_request with a mock. Run alone 3 times, that file fails 1 test in 3 of 3 runs on this head # and in 2 of 3 runs with server.py, streaming.py and helpers.py as on upstream/main. $ uvx ruff@0.17.3 check <touched files> All checks passed! $ uvx ruff@0.17.3 format --check <touched files> already formatted $ mypy headroom/proxy/helpers.py headroom/proxy/server.py headroom/proxy/handlers/streaming.py --ignore-missing-imports Success: no issues found in 3 source files ``` ## Real Behavior Proof - Environment: macOS 27.2 (Apple Silicon), Python 3.13, httpx 0.28.1, httpcore 1.0.9, anyio 4.14.2. `headroom proxy --port 6811 --no-rate-limit --anthropic-api-url https://127.0.0.1:8445` (plus `--no-http2` in run 1), a clean temp HOME per run, `HEADROOM_CA_BUNDLE` pointing at a local test CA. Each run starts its own stub and proxy and stops both. - Exact command / steps: Controlled upstream: a local TLS stub, not a real provider. Run 1 (HTTP/1.1, accepted POST): the stub reads the whole request and counts it, then writes a corrupt TLS application-data record instead of a reply and closes; a byte-identical replay of a body it has seen gets a normal 200. One buffered and one streaming `POST /v1/messages` through the proxy, on upstream/main9f2cc017, on the previous head240680dfand on this head. Run 2 (HTTP/2, write failure): on the first connection the stub grants no flow-control window beyond the default 65,535 bytes, so a 418,702-byte streaming POST is still being written when the stub writes the corrupt record; later connections are served normally. On main and on this head. - Observed result: Run 1: main and this head send each POST once and return 502;240680dfsends each POST twice, byte-identical, and returns the second reply as 200. Run 2: main returns 502 `api_error`; this head retries on a fresh connection and returns 200, and the stub received one complete POST. - Not tested: A real provider sending a corrupt record, and a real HTTP/2 connection shared by several streams when one of them hits it. ```text Run 1: controlled upstream, HTTP/1.1, TLS broken after the whole POST was received version request POSTs the stub received client got upstream/main buffered 1 HTTP 502 api_error upstream/main streaming 1 HTTP 502 api_error240680dfbuffered 2 (byte-identical) HTTP 200 (reply to the replay)240680dfstreaming 2 (byte-identical) HTTP 200 (reply to the replay) this head buffered 1 HTTP 502 api_error this head streaming 1 HTTP 502, SSE error event with "code": "upstream_tls_error" Run 2: controlled upstream, HTTP/2, TLS broken at 65,535 of 418,702 body bytes upstream/main streaming 1 incomplete HTTP 502 api_error this head streaming 1 incomplete, 1 complete HTTP 200 (message_start ... message_stop) WARNING [hr_1794561952_000001] Connection error to upstream API (attempt 1/3): SSLError(1, '[SSL: RECORD_LAYER_FAILURE] record layer failure (_ssl.c:2660)'); retrying in 899ms ``` ## Runtime Rollout Safety - Rollout-managed feature(s): None. - Minimum rollout channel: Stable. - Stable/default behavior changed: Yes. A raw TLS error raised while the request is being written is retried on a fresh connection, like other transport errors. A raw TLS error after the request was written is not retried, as on main; in the streaming path it now ends as a 502 `upstream_tls_error` SSE error instead of a 502 `api_error`. - Kill switch / disable path: `--retry-max-attempts 1` (`HEADROOM_RETRY_MAX_ATTEMPTS=1`) disables the retry, as for every transport error. - Unsafe override required: No. - Qualification impact: None. - Rollback path: Revert this PR. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [x] I have commented my code, particularly in hard-to-understand areas - [x] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [x] I did **not** edit `CHANGELOG.md` — it is generated by release-please from my Conventional Commit PR title (a CI guard enforces this) ## Screenshots (if applicable) Not applicable. ## Additional Notes - Changed after review: the first version retried any raw `ssl.SSLError` before the first byte reached the client. JerrettDavis and Devin showed that replays a POST upstream may already have accepted. This version retries only a failed write, and the title now says so. - No idempotency key is added. The retry rests only on httpcore reporting that the request write failed. - Not changed here: the existing #1639 retries of `httpx.TransportError` (for example a `ReadError` or `ReadTimeout` after the request was written) carry the same after-the-write ambiguity. This PR leaves them as they are. - Companion PR #4775 is independent of this change. The cancellation-stress numbers quoted in the earlier version of this body were measured with the broader retry, so I removed them. - Documentation: no doc describes the retry classes, so there is nothing to update. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
JerrettDavis
parent
998d71080c
commit
854a696544
@@ -9,6 +9,7 @@ import asyncio
|
||||
import contextlib
|
||||
import json
|
||||
import logging
|
||||
import ssl
|
||||
import time
|
||||
from collections.abc import AsyncIterator
|
||||
from typing import TYPE_CHECKING, Any
|
||||
@@ -18,6 +19,7 @@ from headroom.proxy.auth_mode import classify_client, supports_mid_turn_coalesci
|
||||
from headroom.proxy.handlers._debug_dump import write_upstream_error_dump
|
||||
from headroom.proxy.helpers import (
|
||||
RETRYABLE_OVERLOAD_STATUSES,
|
||||
RequestWriteTrace,
|
||||
_path_for_log,
|
||||
jitter_delay_ms,
|
||||
overload_retry_is_futile,
|
||||
@@ -1430,10 +1432,12 @@ class StreamingMixin:
|
||||
last_connect_error = None
|
||||
|
||||
for attempt in range(retry_attempts):
|
||||
request_trace = RequestWriteTrace()
|
||||
try:
|
||||
_upstream_req = streaming_client.build_request(
|
||||
"POST", url, content=outbound_bytes, headers=outbound_headers
|
||||
)
|
||||
_upstream_req.extensions["trace"] = request_trace
|
||||
upstream_response = await streaming_client.send(_upstream_req, stream=True)
|
||||
if _codex_wire_debug:
|
||||
capture_codex_wire_debug(
|
||||
@@ -1481,9 +1485,11 @@ class StreamingMixin:
|
||||
# `StreamReset`) from a poisoned shared h2 connection. This runs
|
||||
# before any body byte is forwarded to the client, so re-sending
|
||||
# on a fresh connection is safe and avoids a 502. (#1639)
|
||||
except httpx.TransportError as e:
|
||||
# A raw ssl.SSLError escapes httpx's TransportError mapping; it is
|
||||
# retried only if the request write failed (RequestWriteTrace).
|
||||
except (httpx.TransportError, ssl.SSLError) as e:
|
||||
last_connect_error = e
|
||||
if attempt >= retry_attempts - 1:
|
||||
if attempt >= retry_attempts - 1 or request_trace.forbids_retry(e):
|
||||
raise
|
||||
|
||||
delay_with_jitter = jitter_delay_ms(
|
||||
@@ -1513,7 +1519,7 @@ class StreamingMixin:
|
||||
# 502 keeps the structured SSE body for clients that read it while
|
||||
# letting SDK retry logic treat a transient upstream transport failure
|
||||
# as what it is.
|
||||
except httpx.TransportError as e:
|
||||
except (httpx.TransportError, ssl.SSLError) as e:
|
||||
error_msg = str(e) or repr(e)
|
||||
logger.error(f"[{request_id}] Connection error to upstream API: {error_msg}")
|
||||
self.metrics.record_upstream_connection_error(provider)
|
||||
|
||||
@@ -16,6 +16,7 @@ import logging
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import ssl
|
||||
import threading
|
||||
import time
|
||||
import warnings
|
||||
@@ -1767,6 +1768,30 @@ def overload_retry_is_futile(response: httpx.Response, max_ms: int, retries_left
|
||||
RETRYABLE_OVERLOAD_STATUSES: frozenset[int] = frozenset({429, 529})
|
||||
|
||||
|
||||
class RequestWriteTrace:
|
||||
"""httpcore ``trace`` extension that records a failed request write.
|
||||
|
||||
httpcore maps an ``ssl.SSLError`` to ``ConnectError`` only during the
|
||||
handshake. Later, a corrupt TLS record surfaces as a raw ``ssl.SSLError``
|
||||
that says nothing about whether upstream received the request. It is safe
|
||||
to retry only when it was raised while the request was still being written
|
||||
(``send_request_headers`` / ``send_request_body`` failed): upstream then
|
||||
never had a complete request to run. Raised after the write, upstream may
|
||||
already have accepted, and billed, the POST, so it is not replayed.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.write_failed = False
|
||||
|
||||
async def __call__(self, event: str, info: dict[str, Any]) -> None:
|
||||
if event.endswith((".send_request_headers.failed", ".send_request_body.failed")):
|
||||
self.write_failed = True
|
||||
|
||||
def forbids_retry(self, exc: BaseException) -> bool:
|
||||
"""True for a raw TLS error raised after the request was fully written."""
|
||||
return isinstance(exc, ssl.SSLError) and not self.write_failed
|
||||
|
||||
|
||||
async def request_with_transient_retry(
|
||||
client: httpx.AsyncClient,
|
||||
*,
|
||||
|
||||
@@ -35,6 +35,7 @@ import logging
|
||||
import math
|
||||
import os
|
||||
import signal
|
||||
import ssl
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
@@ -146,6 +147,7 @@ from headroom.proxy.helpers import (
|
||||
EAGER_PRELOAD_TIMEOUT_SECONDS,
|
||||
MAX_COMPRESSION_CACHE_SESSIONS,
|
||||
RETRYABLE_OVERLOAD_STATUSES,
|
||||
RequestWriteTrace,
|
||||
_setup_file_logging,
|
||||
is_anthropic_auth, # noqa: F401
|
||||
jitter_delay_ms,
|
||||
@@ -2878,6 +2880,8 @@ class HeadroomProxy(
|
||||
)
|
||||
|
||||
for attempt in range(self.config.retry_max_attempts):
|
||||
request_trace = RequestWriteTrace()
|
||||
post_kwargs["extensions"] = {"trace": request_trace}
|
||||
try:
|
||||
if stream:
|
||||
# For streaming, we return early - retry happens at higher level
|
||||
@@ -2943,10 +2947,16 @@ class HeadroomProxy(
|
||||
# HTTP/2 `StreamReset`) that a poisoned shared h2 connection raises on
|
||||
# every in-flight request. Retrying drops the bad connection and
|
||||
# re-sends on a fresh one instead of collapsing to a 502. (#1639)
|
||||
except (httpx.TransportError, httpx.HTTPStatusError) as e:
|
||||
# A raw ssl.SSLError escapes httpx's TransportError mapping; it is
|
||||
# retried only if the request write failed (RequestWriteTrace).
|
||||
except (httpx.TransportError, httpx.HTTPStatusError, ssl.SSLError) as e:
|
||||
last_error = e
|
||||
|
||||
if not self.config.retry_enabled or attempt >= self.config.retry_max_attempts - 1:
|
||||
if (
|
||||
not self.config.retry_enabled
|
||||
or attempt >= self.config.retry_max_attempts - 1
|
||||
or request_trace.forbids_retry(e)
|
||||
):
|
||||
# On exhaustion, preserve the upstream 5xx status (e.g. 503
|
||||
# Service Unavailable, 500, 502, 504) so the client can apply
|
||||
# its own retry/backoff. Collapsing every exhausted 5xx into a
|
||||
|
||||
@@ -6,12 +6,19 @@ every in-flight request. Those are transport errors, so the proxy must retry
|
||||
them (dropping the bad connection and re-sending on a fresh one) instead of
|
||||
collapsing to a 502. These tests drive the real `_retry_request` and
|
||||
`_stream_response` paths.
|
||||
|
||||
A corrupt TLS record surfaces as a raw `ssl.SSLError`, not an
|
||||
`httpx.TransportError`. It is retried only when it hit while the request was
|
||||
still being written. After the write, upstream may already have accepted and
|
||||
billed the POST, so the error propagates and the POST is sent once.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ssl
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import httpcore
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
@@ -177,3 +184,134 @@ async def test_successful_stream_still_returns_200():
|
||||
|
||||
assert result.status_code == 200
|
||||
proxy.metrics.record_upstream_connection_error.assert_not_called()
|
||||
|
||||
|
||||
def _bad_record() -> ssl.SSLError:
|
||||
# What httpx raises on a connection whose next TLS record is corrupt.
|
||||
return ssl.SSLError(1, "[SSL] record layer failure (_ssl.c:2580)")
|
||||
|
||||
|
||||
_SSE_STOP = b'event: message_stop\ndata: {"type":"message_stop"}\n\n'
|
||||
_SSE_OK = b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ncontent-length: %d\r\n\r\n%s" % (
|
||||
len(_SSE_STOP),
|
||||
_SSE_STOP,
|
||||
)
|
||||
|
||||
|
||||
class _Upstream(httpcore.AsyncNetworkBackend):
|
||||
"""Real httpcore over fake sockets: one failure mode per connection.
|
||||
|
||||
``"write"``: the TLS error hits while the request is written (never sent).
|
||||
``"read"``: upstream receives the whole POST, then the TLS error hits.
|
||||
``None``: a healthy connection that answers with an SSE stream.
|
||||
"""
|
||||
|
||||
def __init__(self, *modes: str | None) -> None:
|
||||
self.modes = list(modes)
|
||||
self.received = b""
|
||||
|
||||
@property
|
||||
def posts(self) -> int:
|
||||
return self.received.count(b"POST /v1/messages")
|
||||
|
||||
async def connect_tcp(self, host, port, timeout=None, local_address=None, socket_options=None):
|
||||
return _UpstreamStream(self, self.modes.pop(0))
|
||||
|
||||
|
||||
class _UpstreamStream(httpcore.AsyncNetworkStream):
|
||||
def __init__(self, upstream: _Upstream, mode: str | None) -> None:
|
||||
self.upstream, self.mode, self.replied = upstream, mode, False
|
||||
|
||||
async def write(self, buffer, timeout=None):
|
||||
if self.mode == "write":
|
||||
raise _bad_record()
|
||||
self.upstream.received += buffer
|
||||
|
||||
async def read(self, max_bytes, timeout=None):
|
||||
if self.mode == "read":
|
||||
raise _bad_record()
|
||||
reply, self.replied = (b"" if self.replied else _SSE_OK), True
|
||||
return reply
|
||||
|
||||
async def aclose(self):
|
||||
pass
|
||||
|
||||
async def start_tls(self, ssl_context, server_hostname=None, timeout=None):
|
||||
return self
|
||||
|
||||
|
||||
def _proxy_over(upstream: _Upstream):
|
||||
proxy = _mock_proxy()
|
||||
transport = httpx.AsyncHTTPTransport()
|
||||
# Same hook upstream_pinning uses: swap the pool's network backend.
|
||||
transport._pool._network_backend = upstream
|
||||
proxy.http_client = httpx.AsyncClient(transport=transport)
|
||||
return proxy
|
||||
|
||||
|
||||
async def _retry_post(proxy):
|
||||
return await proxy._retry_request(
|
||||
"POST",
|
||||
"https://api.anthropic.com/v1/messages",
|
||||
{"x-api-key": "sk-test"},
|
||||
{"model": "claude-sonnet-4-20250514", "messages": []},
|
||||
)
|
||||
|
||||
|
||||
async def test_retry_request_does_not_replay_a_post_upstream_received():
|
||||
upstream = _Upstream("read", None)
|
||||
|
||||
with pytest.raises(ssl.SSLError):
|
||||
await _retry_post(_proxy_over(upstream))
|
||||
|
||||
assert upstream.posts == 1
|
||||
|
||||
|
||||
async def test_retry_request_retries_ssl_error_while_writing_the_request():
|
||||
upstream = _Upstream("write", None)
|
||||
|
||||
result = await _retry_post(_proxy_over(upstream))
|
||||
|
||||
assert result.status_code == 200
|
||||
assert upstream.posts == 1
|
||||
assert upstream.modes == []
|
||||
|
||||
|
||||
async def test_stream_does_not_replay_a_post_upstream_received():
|
||||
upstream = _Upstream("read", None)
|
||||
|
||||
result = await _run_stream(_proxy_over(upstream))
|
||||
body = b"".join([chunk async for chunk in result.body_iterator])
|
||||
|
||||
assert upstream.posts == 1
|
||||
assert result.status_code == 502
|
||||
assert b"upstream_tls_error" in body
|
||||
|
||||
|
||||
async def test_stream_retries_ssl_error_while_writing_the_request():
|
||||
upstream = _Upstream("write", None)
|
||||
|
||||
result = await _run_stream(_proxy_over(upstream))
|
||||
body = b"".join([chunk async for chunk in result.body_iterator])
|
||||
|
||||
assert result.status_code == 200
|
||||
assert _SSE_STOP in body
|
||||
assert upstream.posts == 1
|
||||
assert upstream.modes == []
|
||||
|
||||
|
||||
async def test_ssl_error_without_write_evidence_is_not_retried():
|
||||
# The review's harness: the transport accepts the POST, then raises. It
|
||||
# emits no httpcore trace events, so nothing shows the POST went unsent.
|
||||
seen: list[httpx.Request] = []
|
||||
|
||||
def accept_then_fail(request: httpx.Request) -> httpx.Response:
|
||||
seen.append(request)
|
||||
raise _bad_record()
|
||||
|
||||
proxy = _mock_proxy()
|
||||
proxy.http_client = httpx.AsyncClient(transport=httpx.MockTransport(accept_then_fail))
|
||||
|
||||
with pytest.raises(ssl.SSLError):
|
||||
await _retry_post(proxy)
|
||||
assert len(seen) == 1
|
||||
|
||||
@@ -33,7 +33,7 @@ class _FakeClient:
|
||||
self._response = response
|
||||
self.calls = 0
|
||||
|
||||
async def post(self, url, content=None, headers=None):
|
||||
async def post(self, url, content=None, headers=None, extensions=None):
|
||||
self.calls += 1
|
||||
if self._responses is not None:
|
||||
return self._responses[self.calls - 1]
|
||||
|
||||
@@ -223,7 +223,7 @@ class _RetryThenSuccessClient:
|
||||
def __init__(self) -> None:
|
||||
self.attempts = 0
|
||||
|
||||
async def post(self, url, content, headers, timeout=None): # noqa: ANN001, ANN201
|
||||
async def post(self, url, content, headers, timeout=None, extensions=None): # noqa: ANN001, ANN201
|
||||
self.attempts += 1
|
||||
if self.attempts == 1:
|
||||
raise httpx.ConnectTimeout("connect timed out")
|
||||
|
||||
@@ -37,7 +37,7 @@ class _FakeClient:
|
||||
self._exc = exc
|
||||
self.calls = 0
|
||||
|
||||
async def post(self, url, content=None, headers=None):
|
||||
async def post(self, url, content=None, headers=None, extensions=None):
|
||||
self.calls += 1
|
||||
if self._exc is not None:
|
||||
raise self._exc
|
||||
|
||||
Reference in New Issue
Block a user