|
| 1 | +"""Shared HTTP client defaults for provider SDK clients. |
| 2 | +
|
| 3 | +The SDK defaults are tuned for a caller whose event loop is responsive. An |
| 4 | +inspect runner's loop is not: long CPU-bound sections (payload transforms, |
| 5 | +transcript scans) hold it for seconds at a time, and a connect deadline that |
| 6 | +expires during one of those blocks fails a connection that the kernel already |
| 7 | +completed — anyio's cancellation lands on the first checkpoint after the loop |
| 8 | +resumes, so a finished connect is no defence. |
| 9 | +
|
| 10 | +Three defaults follow, all overridable by environment variable: |
| 11 | +
|
| 12 | +* ``connect`` at 60s rather than 5s. A partial raise buys nothing (a 26s block |
| 13 | + failed 75% at 5s and 76.7% at 15s, 0% at 30s), and the deadline has to clear |
| 14 | + *several* blocks: a connect that misses its window waits out whole blocks, so |
| 15 | + failure latency quantises to multiples of the block length (a 3s block |
| 16 | + against a 5s deadline failed 77% of the time, median 6.1s). The cost is that |
| 17 | + a dead endpoint takes 120s to detect, since the retry below gives it a second |
| 18 | + full deadline; httpcore charges the deadline separately to the TCP connect |
| 19 | + and the TLS handshake, so a slow-then-stalling endpoint can reach 4x, and an |
| 20 | + SDK that retries multiplies that again. |
| 21 | +
|
| 22 | +* ``max_keepalive_connections`` at the connection limit rather than 100. Above |
| 23 | + the cap every connection is destroyed the moment it goes idle, stepping the |
| 24 | + new-connection rate ~20x once concurrency passes ~120, and only new |
| 25 | + connections run the connect path at all. |
| 26 | +
|
| 27 | +* One connection-establishment retry. httpcore retries the connect only and |
| 28 | + never re-sends the request, so it is safe for non-idempotent calls. It needs |
| 29 | + the loop running again by the time it fires, so it rescues a lightly loaded |
| 30 | + caller and does little for a saturated one. |
| 31 | +
|
| 32 | +The transport also carries the TCP keepalive socket options the Anthropic SDK |
| 33 | +sets on its own, since they live on the transport and supplying one drops them. |
| 34 | +Supplying a transport likewise turns off httpx's environment proxy discovery, |
| 35 | +so the proxy mounts are rebuilt here and given the same settings. |
| 36 | +
|
| 37 | +``keepalive_expiry`` stays at httpx's 5s default: raising it past an |
| 38 | +intermediary's idle timeout (an ALB commonly defaults to 60s) trades these |
| 39 | +failures for stale-connection ones. Note this leaves the |
| 40 | +``max_keepalive_connections`` raise inert whenever blocks outlast the expiry, |
| 41 | +which is the case that motivated it (at a 6s block, 100 versus 1000 changed |
| 42 | +nothing, both failing every request). A deployment that knows its own topology |
| 43 | +should raise the expiry alongside the cap. |
| 44 | +""" |
| 45 | + |
| 46 | +from __future__ import annotations |
| 47 | + |
| 48 | +import os |
| 49 | +import socket |
| 50 | +from typing import Any, overload |
| 51 | + |
| 52 | +import httpx |
| 53 | + |
| 54 | + |
| 55 | +def _no_environment_proxies() -> dict[str, str | None]: |
| 56 | + return {} |
| 57 | + |
| 58 | + |
| 59 | +try: |
| 60 | + # Private to httpx, but replicating its NO_PROXY rules would drift; the |
| 61 | + # anthropic SDK vendors a copy for the same reason. Degrade to no mounts |
| 62 | + # rather than failing to import if httpx moves it. |
| 63 | + from httpx._utils import get_environment_proxies as _get_environment_proxies |
| 64 | +except ImportError: # pragma: no cover - httpx moved its internals |
| 65 | + _get_environment_proxies = _no_environment_proxies |
| 66 | + |
| 67 | +DEFAULT_CONNECT_TIMEOUT = 60.0 |
| 68 | +DEFAULT_REQUEST_TIMEOUT = 600.0 |
| 69 | +DEFAULT_POOL_CONNECTIONS = 1000 |
| 70 | +DEFAULT_KEEPALIVE_EXPIRY = 5.0 |
| 71 | +DEFAULT_CONNECT_RETRIES = 1 |
| 72 | + |
| 73 | +CONNECT_TIMEOUT_ENV = "INSPECT_HTTP_CONNECT_TIMEOUT" |
| 74 | +REQUEST_TIMEOUT_ENV = "INSPECT_HTTP_REQUEST_TIMEOUT" |
| 75 | +POOL_CONNECTIONS_ENV = "INSPECT_HTTP_POOL_CONNECTIONS" |
| 76 | +POOL_KEEPALIVE_CONNECTIONS_ENV = "INSPECT_HTTP_POOL_KEEPALIVE_CONNECTIONS" |
| 77 | +KEEPALIVE_EXPIRY_ENV = "INSPECT_HTTP_KEEPALIVE_EXPIRY" |
| 78 | +CONNECT_RETRIES_ENV = "INSPECT_HTTP_CONNECT_RETRIES" |
| 79 | + |
| 80 | + |
| 81 | +def _env_float(name: str, fallback: float) -> float: |
| 82 | + """A non-negative float from the environment, `fallback` on unset or junk.""" |
| 83 | + raw = os.environ.get(name) |
| 84 | + if raw is None or not raw.strip(): |
| 85 | + return fallback |
| 86 | + try: |
| 87 | + value = float(raw) |
| 88 | + except ValueError: |
| 89 | + return fallback |
| 90 | + return value if value >= 0 else fallback |
| 91 | + |
| 92 | + |
| 93 | +@overload |
| 94 | +def _env_int(name: str, fallback: int) -> int: ... |
| 95 | + |
| 96 | + |
| 97 | +@overload |
| 98 | +def _env_int(name: str, fallback: None) -> int | None: ... |
| 99 | + |
| 100 | + |
| 101 | +def _env_int(name: str, fallback: int | None) -> int | None: |
| 102 | + """A non-negative int from the environment, `fallback` on unset or junk.""" |
| 103 | + raw = os.environ.get(name) |
| 104 | + if raw is None or not raw.strip(): |
| 105 | + return fallback |
| 106 | + try: |
| 107 | + value = int(raw) |
| 108 | + except ValueError: |
| 109 | + return fallback |
| 110 | + return value if value >= 0 else fallback |
| 111 | + |
| 112 | + |
| 113 | +def connect_timeout() -> float: |
| 114 | + return _env_float(CONNECT_TIMEOUT_ENV, DEFAULT_CONNECT_TIMEOUT) |
| 115 | + |
| 116 | + |
| 117 | +def default_timeout( |
| 118 | + request_timeout: float = DEFAULT_REQUEST_TIMEOUT, |
| 119 | +) -> httpx.Timeout: |
| 120 | + """Timeouts, with the environment overriding `request_timeout`. |
| 121 | +
|
| 122 | + The argument is only the fallback, so a provider whose SDK has a budget of |
| 123 | + its own can pass it and keep it until an operator sets the variable. |
| 124 | + """ |
| 125 | + return httpx.Timeout( |
| 126 | + timeout=_env_float(REQUEST_TIMEOUT_ENV, request_timeout), |
| 127 | + connect=connect_timeout(), |
| 128 | + ) |
| 129 | + |
| 130 | + |
| 131 | +def default_limits( |
| 132 | + max_connections: int | None = DEFAULT_POOL_CONNECTIONS, |
| 133 | +) -> httpx.Limits: |
| 134 | + """Pool limits, with the environment overriding `max_connections`. |
| 135 | +
|
| 136 | + The argument is only the fallback, so a provider whose pool is deliberately |
| 137 | + uncapped can pass None and keep it until an operator sets the variable. |
| 138 | + """ |
| 139 | + connections = _env_int(POOL_CONNECTIONS_ENV, max_connections) |
| 140 | + return httpx.Limits( |
| 141 | + max_connections=connections, |
| 142 | + # Tracks the pool size unless set outright, so lowering the limit |
| 143 | + # cannot leave a keepalive cap above it. |
| 144 | + max_keepalive_connections=_env_int(POOL_KEEPALIVE_CONNECTIONS_ENV, connections), |
| 145 | + keepalive_expiry=_env_float(KEEPALIVE_EXPIRY_ENV, DEFAULT_KEEPALIVE_EXPIRY), |
| 146 | + ) |
| 147 | + |
| 148 | + |
| 149 | +def _default_socket_options() -> list[tuple[int, int, int]]: |
| 150 | + """TCP keepalive options matching the ones the Anthropic SDK installs.""" |
| 151 | + options: list[tuple[int, int, int]] = [ |
| 152 | + (socket.SOL_SOCKET, socket.SO_KEEPALIVE, True) |
| 153 | + ] |
| 154 | + # Not every knob exists on every platform. |
| 155 | + for name, value in ( |
| 156 | + ("TCP_KEEPINTVL", 60), |
| 157 | + ("TCP_KEEPCNT", 5), |
| 158 | + ("TCP_KEEPIDLE", 60), |
| 159 | + ): |
| 160 | + option = getattr(socket, name, None) |
| 161 | + if isinstance(option, int): |
| 162 | + options.append((socket.IPPROTO_TCP, option, value)) |
| 163 | + return options |
| 164 | + |
| 165 | + |
| 166 | +async def _floor_connect_timeout(request: httpx.Request) -> None: |
| 167 | + """Stop a scalar SDK timeout from shortening the connect deadline. |
| 168 | +
|
| 169 | + SDKs stamp their own per-request timeout over whatever the client was built |
| 170 | + with, and httpx expands a bare float to all four phases, so an overall |
| 171 | + budget such as `-M client_timeout=30` would become the connect deadline |
| 172 | + too. Only ever raises it, leaving a longer deadline and a `None` (no limit) |
| 173 | + alone. |
| 174 | + """ |
| 175 | + extension = request.extensions.get("timeout") |
| 176 | + if not isinstance(extension, dict): |
| 177 | + return |
| 178 | + # Safe to mutate: httpx.Timeout.as_dict() builds this fresh per request. |
| 179 | + timeout: dict[str, float | None] = extension |
| 180 | + connect = timeout.get("connect") |
| 181 | + floor = connect_timeout() |
| 182 | + if connect is not None and connect < floor: |
| 183 | + timeout["connect"] = floor |
| 184 | + |
| 185 | + |
| 186 | +def _transport_kwargs( |
| 187 | + limits: httpx.Limits, overrides: dict[str, Any] |
| 188 | +) -> dict[str, Any]: |
| 189 | + """Settings httpx would apply itself if it were building the transport.""" |
| 190 | + kwargs: dict[str, Any] = { |
| 191 | + "retries": _env_int(CONNECT_RETRIES_ENV, DEFAULT_CONNECT_RETRIES), |
| 192 | + "limits": limits, |
| 193 | + "socket_options": _default_socket_options(), |
| 194 | + } |
| 195 | + # httpx applies these only to a transport it builds itself, so a caller |
| 196 | + # passing verify=... would otherwise have it silently dropped. |
| 197 | + kwargs.update( |
| 198 | + { |
| 199 | + arg: overrides[arg] |
| 200 | + for arg in ("verify", "cert", "trust_env", "http1", "http2") |
| 201 | + if arg in overrides |
| 202 | + } |
| 203 | + ) |
| 204 | + return kwargs |
| 205 | + |
| 206 | + |
| 207 | +def default_client_kwargs(**overrides: Any) -> dict[str, Any]: |
| 208 | + """`httpx.AsyncClient` kwargs carrying these defaults; caller overrides win.""" |
| 209 | + kwargs = dict(overrides) |
| 210 | + # `limits` resolves first because httpx applies `limits=` only to a |
| 211 | + # transport it builds itself, so the transport has to bake them in. |
| 212 | + limits = kwargs.setdefault("limits", default_limits()) |
| 213 | + kwargs.setdefault("timeout", default_timeout()) |
| 214 | + kwargs.setdefault("follow_redirects", True) |
| 215 | + |
| 216 | + if "transport" not in kwargs: |
| 217 | + transport_kwargs = _transport_kwargs(limits, kwargs) |
| 218 | + # Supplying a transport turns off httpx's environment proxy discovery, |
| 219 | + # so rebuild the mounts with the same settings rather than losing |
| 220 | + # either the proxy or the retry and keepalive options. |
| 221 | + mounts: dict[str, httpx.AsyncBaseTransport | None] = { |
| 222 | + key: None |
| 223 | + if url is None |
| 224 | + else httpx.AsyncHTTPTransport(proxy=httpx.Proxy(url), **transport_kwargs) |
| 225 | + for key, url in _get_environment_proxies().items() |
| 226 | + } |
| 227 | + mounts.update(kwargs.get("mounts") or {}) |
| 228 | + kwargs["mounts"] = mounts |
| 229 | + kwargs["transport"] = httpx.AsyncHTTPTransport(**transport_kwargs) |
| 230 | + |
| 231 | + hooks = dict(kwargs.get("event_hooks") or {}) |
| 232 | + hooks["request"] = [_floor_connect_timeout, *hooks.get("request", [])] |
| 233 | + kwargs["event_hooks"] = hooks |
| 234 | + return kwargs |
| 235 | + |
| 236 | + |
| 237 | +def default_async_client(**overrides: Any) -> httpx.AsyncClient: |
| 238 | + return httpx.AsyncClient(**default_client_kwargs(**overrides)) |
0 commit comments