Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(proxy): probe upstream connections with TCP keepalive so a dead link fails over (#3907)

gglucassc46e7cc6514e
diff --git a/headroom/cli/proxy.py b/headroom/cli/proxy.py
index 15da1f71c..fdbcf34a2 100644
--- a/headroom/cli/proxy.py
+++ b/headroom/cli/proxy.py
@@ -526,6 +526,18 @@ def dashboard(port: int, no_open: bool) -> None:
"Env: HEADROOM_WRITE_TIMEOUT_SECONDS."
),
)
+ "--upstream-tcp-keepalive-seconds",
+ type=click.IntRange(min=0),
+ default=None,
+ envvar="HEADROOM_UPSTREAM_TCP_KEEPALIVE_SECONDS",
+ help=(
+ "Seconds an upstream connection may sit silent before TCP keepalive "
+ "probes it (default: 30, 0 disables). A link that dies without a reset "
+ "then fails over after about this + 60s instead of waiting out the read "
+ "timeout. Env: HEADROOM_UPSTREAM_TCP_KEEPALIVE_SECONDS."
+ ),
+)
@click.option(
"--anthropic-buffered-request-timeout-seconds",
type=click.IntRange(min=1),
@@ -1055,6 +1067,7 @@ def proxy(
request_timeout_seconds: int | None,
connect_timeout_seconds: int | None,
write_timeout_seconds: int | None,
+ upstream_tcp_keepalive_seconds: int | None,
anthropic_buffered_request_timeout_seconds: int | None,
anthropic_pre_upstream_concurrency: int | None,
anthropic_pre_upstream_acquire_timeout_seconds: float | None,
@@ -1391,6 +1404,9 @@ def proxy(
if connect_timeout_seconds is not None
else 10,
write_timeout_seconds=write_timeout_seconds if write_timeout_seconds is not None else 150,
+ upstream_tcp_keepalive_seconds=(
+ upstream_tcp_keepalive_seconds if upstream_tcp_keepalive_seconds is not None else 30
+ ),
anthropic_buffered_request_timeout_seconds=(
anthropic_buffered_request_timeout_seconds
if anthropic_buffered_request_timeout_seconds is not None
diff --git a/headroom/proxy/models.py b/headroom/proxy/models.py
index 0f87c89eb..002beea5a 100644
--- a/headroom/proxy/models.py
+++ b/headroom/proxy/models.py
@@ -397,6 +397,13 @@ class ProxyConfig:
# unreachable: 150s carries a 15MB body -- the largest #3259 reports -- over
# a ~1 Mbps uplink, and still fires well before the OS gives up at ~180s.
write_timeout_seconds: int = 150
+ # Seconds an upstream connection may sit silent before TCP keepalive probes
+ # it (0 disables). The read timeout cannot tell a model thinking from a link
+ # that died without a reset (network change, tunnel, NAT drop), so without
+ # this a dead link holds a request for the whole read timeout, per attempt.
+ # Probes go every 10s and give up after 6, so a dead link fails over after
+ # about this + 60s. See headroom/proxy/tcp_keepalive.py.
+ upstream_tcp_keepalive_seconds: int = 30
# Anthropic buffered reads can legitimately run longer than the generic
# proxy request cap. Keep the generic timeout unchanged elsewhere.
anthropic_buffered_request_timeout_seconds: int = 600
diff --git a/headroom/proxy/server.py b/headroom/proxy/server.py
index 44e21ce23..8a2474911 100644
--- a/headroom/proxy/server.py
+++ b/headroom/proxy/server.py
@@ -188,6 +188,7 @@ from headroom.proxy.ssl_context import (
describe_trust_policy,
ensure_process_trust_if_owned,
)
+from headroom.proxy.tcp_keepalive import install_tcp_keepalive
from headroom.proxy.tool_schema_savings_policy import tool_schema_saved_from_tags
from headroom.proxy.upstream_pinning import install_upstream_pinning
from headroom.proxy.warmup import WarmupRegistry
@@ -1987,15 +1988,19 @@ class HeadroomProxy(
# honour a pin at all — a proxy resolves the target itself, on its own
# network. Operator-configured upstreams have no pin and are untouched,
# so trust_env, limits, HTTP/2 and connection reuse are unchanged.
+ # Keepalive goes on first: pinning hides proxy pools behind a wrapper.
+ _keepalive = self.config.upstream_tcp_keepalive_seconds
self.http_client = install_upstream_pinning(
- httpx.AsyncClient(http2=_http2, **_client_kwargs)
+ install_tcp_keepalive(httpx.AsyncClient(http2=_http2, **_client_kwargs), _keepalive)
)
# Reuse the primary client when HTTP/2 is already off; otherwise keep a
# dedicated HTTP/1.1 client for ChatGPT passthrough.
self.http_client_h1 = (
self.http_client
if not _http2
- else install_upstream_pinning(httpx.AsyncClient(http2=False, **_client_kwargs))
+ else install_upstream_pinning(
+ install_tcp_keepalive(httpx.AsyncClient(http2=False, **_client_kwargs), _keepalive)
+ )
)
logger.info("Headroom Proxy started (version %s)", __version__)
logger.info(f"Optimization: {'ENABLED' if self.config.optimize else 'DISABLED'}")
@@ -5860,6 +5865,11 @@ def _proxy_config_from_env() -> ProxyConfig:
150,
min_value=1,
),
+ upstream_tcp_keepalive_seconds=_get_env_int(
+ "HEADROOM_UPSTREAM_TCP_KEEPALIVE_SECONDS",
+ 30,
+ min_value=0,
+ ),
buffered_ccr_grace_seconds=_get_env_float(
"HEADROOM_BUFFERED_CCR_GRACE_SECONDS",
DEFAULT_BUFFERED_CCR_GRACE_SECONDS,
@@ -6619,6 +6629,11 @@ if __name__ == "__main__":
150,
min_value=1,
),
+ upstream_tcp_keepalive_seconds=_get_env_int(
+ "HEADROOM_UPSTREAM_TCP_KEEPALIVE_SECONDS",
+ 30,
+ min_value=0,
+ ),
vertex_api_url=_get_env_str("VERTEX_TARGET_API_URL", args.vertex_api_url),
# Backend settings
backend=_get_env_str("HEADROOM_BACKEND", args.backend), # type: ignore[arg-type]
diff --git a/headroom/proxy/tcp_keepalive.py b/headroom/proxy/tcp_keepalive.py
new file mode 100644
index 000000000..4ce1bbac7
--- /dev/null
+++ b/headroom/proxy/tcp_keepalive.py
@@ -0,0 +1,129 @@
+"""TCP keepalive on the proxy's upstream connections.
+
+A request waiting on a model reads nothing for minutes, legitimately, so the
+read timeout cannot tell a slow answer from a dead link. When the network goes
+away without a reset (a train entering a tunnel, a Wi-Fi handover, a NAT
+dropping its state, a laptop changing networks) the socket stays open and the
+proxy waits out the whole read timeout: 600s on the buffered Anthropic path,
+for each of ``retry_max_attempts`` attempts. The buffered path heartbeats the
+client meanwhile, so the client's own stall detection never fires either, and
+the user watches a spinner for 10-30 minutes where a direct connection would
+have failed over in about three.
+
+Keepalive asks the peer's kernel, not the model, whether the connection is
+alive: after ``idle_seconds`` of silence it sends a probe every
+``PROBE_INTERVAL_SECONDS`` and drops the connection after ``PROBE_COUNT``
+unanswered ones. A live upstream answers probes while the model thinks, so slow
+answers are untouched. A dead link fails after about ``idle_seconds + 60`` as a
+transport error, which ``_retry_request`` already retries on a fresh
+connection. Keepalive never fires while sent data is unacknowledged; a stalled
+upload is ``write_timeout_seconds``' job (#3259, #3327).
+"""
+
+from __future__ import annotations
+
+import logging
+import socket
+from collections.abc import Iterable
+from typing import Any
+
+import httpcore
+import httpx
+
+logger = logging.getLogger(__name__)
+
+PROBE_INTERVAL_SECONDS = 10
+PROBE_COUNT = 6
+
+
+def keepalive_socket_options(idle_seconds: int) -> list[tuple[int, int, int]]:
+ """Keepalive options for this platform: on, idle time, probe interval, probe count."""
+ # Linux and Windows call the idle time TCP_KEEPIDLE, macOS TCP_KEEPALIVE.
+ idle = getattr(socket, "TCP_KEEPIDLE", None)
+ if idle is None:
+ idle = getattr(socket, "TCP_KEEPALIVE", None)
+ options = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)]
+ for name, value in (
+ (idle, idle_seconds),
+ (getattr(socket, "TCP_KEEPINTVL", None), PROBE_INTERVAL_SECONDS),
+ (getattr(socket, "TCP_KEEPCNT", None), PROBE_COUNT),
+ ):
+ if name is not None:
+ options.append((socket.IPPROTO_TCP, name, value))
+ return options
+
+
+class KeepaliveNetworkBackend(httpcore.AsyncNetworkBackend):
+ """Turns keepalive on for every TCP connection the wrapped backend opens.
+
+ Options are set after the connect rather than passed as httpcore
+ ``socket_options``: httpcore maps a failing ``setsockopt`` to ConnectError,
+ so a platform refusing one option would fail every request. Here a refused
+ option is skipped and the connection goes ahead as it would have without it.
+ """
+
+ def __init__(
+ self, inner: httpcore.AsyncNetworkBackend, options: list[tuple[int, int, int]]
+ ) -> None:
+ self._inner = inner
+ self._options = options
+
+ async def connect_tcp(
+ self,
+ host: str,
+ port: int,
+ timeout: float | None = None,
+ local_address: str | None = None,
+ socket_options: Iterable[Any] | None = None,
+ ) -> httpcore.AsyncNetworkStream:
+ stream = await self._inner.connect_tcp(
+ host,
+ port,
+ timeout=timeout,
+ local_address=local_address,
+ socket_options=socket_options,
+ )
+ sock = stream.get_extra_info("socket")
+ if sock is not None:
+ for option in self._options:
+ try:
+ sock.setsockopt(*option)
+ except OSError as exc:
+ logger.debug("upstream TCP keepalive option %r refused: %s", option, exc)
+ return stream
+
+ async def connect_unix_socket(
+ self,
+ path: str,
+ timeout: float | None = None,
+ socket_options: Iterable[Any] | None = None,
+ ) -> httpcore.AsyncNetworkStream:
+ return await self._inner.connect_unix_socket(
+ path, timeout=timeout, socket_options=socket_options
+ )
+
+ async def sleep(self, seconds: float) -> None:
+ await self._inner.sleep(seconds)
+
+
+def install_tcp_keepalive(client: httpx.AsyncClient, idle_seconds: int) -> httpx.AsyncClient:
+ """Probe every upstream connection ``client`` opens; ``idle_seconds <= 0`` leaves it as is.
+
+ Wraps the network backend of each transport's connection pool: the primary
+ one and every proxy mount httpx built from HTTP(S)_PROXY or the system proxy
+ settings, so direct dials, CONNECT tunnels and SOCKS proxies all get it.
+ ``httpx.AsyncHTTPTransport(socket_options=...)`` cannot do this: passing a
+ transport switches off environment proxies, and httpcore's proxy pools do
+ not forward ``socket_options`` to the connections they open. Call before
+ ``install_upstream_pinning``, which hides proxy pools behind a refusing
+ wrapper.
+ """
+ if idle_seconds <= 0:
+ return client
+ options = keepalive_socket_options(idle_seconds)
+ for transport in (client._transport, *client._mounts.values()):
+ pool: Any = getattr(transport, "_pool", None)
+ backend = getattr(pool, "_network_backend", None)
+ if backend is not None and not isinstance(backend, KeepaliveNetworkBackend):
+ pool._network_backend = KeepaliveNetworkBackend(backend, options)
+ return client
diff --git a/headroom/settings_store.py b/headroom/settings_store.py
index 4e36fc73b..3ca2fd8d3 100644
--- a/headroom/settings_store.py
+++ b/headroom/settings_store.py
@@ -577,6 +577,22 @@ SETTINGS: tuple[SettingField, ...] = (
),
tier="advanced",
),
+ SettingField(
+ "HEADROOM_UPSTREAM_TCP_KEEPALIVE_SECONDS",
+ "upstream_tcp_keepalive_seconds",
+ "Upstream TCP keepalive (s)",
+ "Timeouts",
+ "int",
+ default=None,
+ minimum=0,
+ help=(
+ "Seconds an upstream connection may sit silent before TCP keepalive "
+ "probes it. Default: 30, 0 disables. A link that dies without a reset "
+ "then fails over after about this + 60s instead of waiting out the "
+ "read timeout."
+ ),
+ tier="advanced",
+ ),
SettingField(
"HEADROOM_ANTHROPIC_BUFFERED_REQUEST_TIMEOUT_SECONDS",
"anthropic_buffered_request_timeout_seconds",
diff --git a/tests/test_upstream_tcp_keepalive.py b/tests/test_upstream_tcp_keepalive.py
new file mode 100644
index 000000000..cc2bf7a48
--- /dev/null
+++ b/tests/test_upstream_tcp_keepalive.py
@@ -0,0 +1,246 @@
+"""Upstream connections must notice a dead link without waiting for the model.
+
+The read timeout cannot tell a model thinking from a link that died without a
+reset (a network change, a tunnel, a NAT dropping state), so the proxy held such
+a request for the whole read timeout, 600s on the buffered Anthropic path, per
+attempt, while heartbeating the client so its own stall detection never fired.
+TCP keepalive asks the peer's kernel instead, so every socket the upstream
+client opens, direct or through a proxy, has to carry it.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import socket
+
+import httpcore
+import httpx
+import pytest
+
+from headroom.proxy.models import ProxyConfig
+from headroom.proxy.tcp_keepalive import (
+ PROBE_COUNT,
+ PROBE_INTERVAL_SECONDS,
+ KeepaliveNetworkBackend,
+ install_tcp_keepalive,
+ keepalive_socket_options,
+)
+
+_IDLE = getattr(socket, "TCP_KEEPIDLE", None) or getattr(socket, "TCP_KEEPALIVE", None)
+
+
+class _RecordingBackend(httpcore.AsyncNetworkBackend):
+ """Hands out real connections and remembers their sockets."""
+
+ def __init__(self) -> None:
+ self._real = httpcore.AnyIOBackend()
+ self.sockets: list[socket.socket] = []
+
+ async def connect_tcp(self, host, port, timeout=None, local_address=None, socket_options=None):
+ stream = await self._real.connect_tcp(
+ host,
+ port,
+ timeout=timeout,
+ local_address=local_address,
+ socket_options=socket_options,
+ )
+ self.sockets.append(stream.get_extra_info("socket"))
+ return stream
+
+ async def connect_unix_socket(self, path, timeout=None, socket_options=None):
+ raise NotImplementedError
+
+ async def sleep(self, seconds: float) -> None:
+ await asyncio.sleep(seconds)
+
+
+async def _http_server(seen_paths: list[str]) -> asyncio.Server:
+ """Answers every request 200; works as an origin and as a forward proxy."""
+
+ async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ while True:
+ head = await reader.readuntil(b"\r\n\r\n")
+ seen_paths.append(head.split(b" ", 2)[1].decode())
+ writer.write(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")
+ await writer.drain()
+
+ async def guarded(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ try:
+ await handle(reader, writer)
+ except (asyncio.IncompleteReadError, ConnectionError):
+ writer.close()
+
+ return await asyncio.start_server(guarded, "127.0.0.1", 0)
+
+
+def _assert_keepalive(sock: socket.socket, idle_seconds: int) -> None:
+ assert sock.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) != 0
+ if _IDLE is not None:
+ assert sock.getsockopt(socket.IPPROTO_TCP, _IDLE) == idle_seconds
+ if hasattr(socket, "TCP_KEEPINTVL"):
+ assert sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL) == PROBE_INTERVAL_SECONDS
+ if hasattr(socket, "TCP_KEEPCNT"):
+ assert sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT) == PROBE_COUNT
+
+
+def _record_under_keepalive(client: httpx.AsyncClient) -> _RecordingBackend:
+ """Put a recorder beneath every keepalive layer ``client`` dials through."""
+ recorder = _RecordingBackend()
+ for transport in (client._transport, *client._mounts.values()):
+ backend = transport._pool._network_backend
+ assert isinstance(backend, KeepaliveNetworkBackend)
+ backend._inner = recorder
+ return recorder
+
+
+def test_options_turn_keepalive_on_with_the_idle_time_this_platform_names() -> None:
+ options = keepalive_socket_options(42)
+
+ assert (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) in options
+ if _IDLE is not None:
+ assert (socket.IPPROTO_TCP, _IDLE, 42) in options
+
+
+async def test_a_direct_upstream_connection_carries_keepalive() -> None:
+ """The regression itself: a real socket to the upstream, probed when idle."""
+ seen: list[str] = []
+ server = await _http_server(seen)
+ port = server.sockets[0].getsockname()[1]
+ client = install_tcp_keepalive(httpx.AsyncClient(trust_env=False), 25)
+ recorder = _record_under_keepalive(client)
+ try:
+ response = await client.get(f"http://127.0.0.1:{port}/v1/messages")
+ assert response.status_code == 200
+ assert len(recorder.sockets) == 1
+ _assert_keepalive(recorder.sockets[0], 25)
+ finally:
+ await client.aclose()
+ server.close()
+
+
+async def test_a_proxied_upstream_connection_carries_keepalive() -> None:
+ """httpcore's proxy pools drop ``socket_options``; the backend layer does not.
+
+ The socket to the proxy is the one that dies with the user's network, so it
+ is the one that has to be probed.
+ """
+ seen: list[str] = []
+ proxy = await _http_server(seen)
+ port = proxy.sockets[0].getsockname()[1]
+ client = install_tcp_keepalive(
+ httpx.AsyncClient(proxy=f"http://127.0.0.1:{port}", trust_env=False), 25
+ )
+ recorder = _record_under_keepalive(client)
+ try:
+ response = await client.get("http://upstream.example/v1/messages")
+ assert response.status_code == 200
+ assert seen == ["http://upstream.example/v1/messages"] # it went via the proxy
+ assert len(recorder.sockets) == 1
+ _assert_keepalive(recorder.sockets[0], 25)
+ finally:
+ await client.aclose()
+ proxy.close()
+
+
+async def test_environment_proxy_mounts_are_covered(monkeypatch: pytest.MonkeyPatch) -> None:
+ """System and env proxies become mounts httpx builds itself."""
+ monkeypatch.setenv("HTTPS_PROXY", "http://proxy.internal:3128")
+ client = install_tcp_keepalive(httpx.AsyncClient(), 30)
+ try:
+ transports = [client._transport, *client._mounts.values()]
+ assert len(transports) > 1
+ for transport in transports:
+ assert isinstance(transport._pool._network_backend, KeepaliveNetworkBackend)
+ finally:
+ await client.aclose()
+
+
+async def test_zero_leaves_the_client_untouched() -> None:
+ client = httpx.AsyncClient(trust_env=False)
+ backend = client._transport._pool._network_backend
+ try:
+ assert install_tcp_keepalive(client, 0) is client
+ assert client._transport._pool._network_backend is backend
+ finally:
+ await client.aclose()
+
+
+async def test_installing_twice_does_not_stack() -> None:
+ client = install_tcp_keepalive(
+ install_tcp_keepalive(httpx.AsyncClient(trust_env=False), 30), 30
+ )
+ try:
+ backend = client._transport._pool._network_backend
+ assert isinstance(backend, KeepaliveNetworkBackend)
+ assert not isinstance(backend._inner, KeepaliveNetworkBackend)
+ finally:
+ await client.aclose()
+
+
+async def test_a_refused_option_never_fails_the_connection() -> None:
+ """Keepalive is best effort; a platform that rejects an option still connects."""
+ seen: list[str] = []
+ server = await _http_server(seen)
+ port = server.sockets[0].getsockname()[1]
+ bogus = (socket.IPPROTO_TCP, 0x7FFF, 1)
+ backend = KeepaliveNetworkBackend(
+ httpcore.AnyIOBackend(), [bogus, (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)]
+ )
+ try:
+ stream = await backend.connect_tcp("127.0.0.1", port)
+ sock = stream.get_extra_info("socket")
+ assert sock.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) != 0
+ await stream.aclose()
+ finally:
+ server.close()
+
+
+def test_keepalive_defaults_on_and_fails_over_well_inside_the_read_timeouts() -> None:
+ config = ProxyConfig()
+ detection = config.upstream_tcp_keepalive_seconds + PROBE_INTERVAL_SECONDS * PROBE_COUNT
+
+ assert config.upstream_tcp_keepalive_seconds > 0
+ assert detection < config.request_timeout_seconds
+ assert detection < config.anthropic_buffered_request_timeout_seconds
+
+
+def test_env_sets_and_disables_it(monkeypatch: pytest.MonkeyPatch) -> None:
+ from headroom.proxy.server import _proxy_config_from_env
+
+ monkeypatch.setenv("HEADROOM_UPSTREAM_TCP_KEEPALIVE_SECONDS", "45")
+ assert _proxy_config_from_env().upstream_tcp_keepalive_seconds == 45
+ monkeypatch.setenv("HEADROOM_UPSTREAM_TCP_KEEPALIVE_SECONDS", "0")
+ assert _proxy_config_from_env().upstream_tcp_keepalive_seconds == 0
+
+
[email protected]("http2", [False, True])
+def test_the_proxy_dials_every_upstream_through_keepalive_and_pinning(http2: bool) -> None:
+ """Keepalive sits under the pin, so a pinned dial is probed too."""
+ from fastapi.testclient import TestClient
+
+ from headroom.proxy.server import create_app
+ from headroom.proxy.upstream_pinning import PinnedAddressBackend
+
+ config = ProxyConfig(http2=http2, optimize=False, cache_enabled=False, rate_limit_enabled=False)
+ with TestClient(create_app(config)) as client:
+ proxy = client.app.state.proxy
+ for upstream in (proxy.http_client, proxy.http_client_h1):
+ backend = upstream._transport._pool._network_backend
+ assert isinstance(backend, PinnedAddressBackend)
+ assert isinstance(backend._inner, KeepaliveNetworkBackend)
+
+
+def test_the_proxy_leaves_sockets_alone_when_disabled() -> None:
+ from fastapi.testclient import TestClient
+
+ from headroom.proxy.server import create_app
+
+ config = ProxyConfig(
+ upstream_tcp_keepalive_seconds=0,
+ optimize=False,
+ cache_enabled=False,
+ rate_limit_enabled=False,
+ )
+ with TestClient(create_app(config)) as client:
+ backend = client.app.state.proxy.http_client._transport._pool._network_backend
+ assert not isinstance(backend._inner, KeepaliveNetworkBackend)