RCLI icon indicating copy to clipboard operation
RCLI copied to clipboard

Anthropic shim opens a new TLS connection for every request (~541 ms per turn)

Open AmanSwar opened this issue 2 months ago • 4 comments

Release blocker. ~541 ms is added to every request an agent makes through wally, before a single byte of the request is sent.

Problem

The Anthropic→OpenAI shim builds a fresh httplib::Client for every request to the hosted endpoint: inside the streaming sink in src/anthropic/messages.cpp (HandleStreaming, httplib::Client client(*origin) ~L183) and again in HandleNonStreaming (~L119). Each one opens a new TCP connection and completes a new TLS handshake, streams one response, and is destroyed.

Against the regional load balancer that handshake was measured at ~541 ms (InferenceInfra .claude/rules/terraform-safety.md, 2026-09-06; InferenceInfra #418 measured ~556 ms per new connection from Delhi, and nothing on reused connections). Claude Code makes several requests per user turn once ANTHROPIC_BASE_URL points at the shim — the main completion plus the small side calls — and every one pays it. Claude Code → shim is loopback and unaffected; the shim → inference.runanywhere.ai leg is where the cost lands.

Why it blocks release

It is the largest piece of time-to-first-token a customer feels that has nothing to do with the GPU, on every turn. It also makes the regional-TLS question (InferenceInfra #299) look worse than it is: once the connection is reused, that handshake is paid once per session instead of once per request.

Fix

  1. Keep long-lived httplib::Clients on the shim's Runtime, set_keep_alive(true). An httplib::Client serialises requests on its one socket, so use a small pool — one per concurrent stream — and reuse across turns.
  2. Reconnect lazily: if a request fails on a stale socket (the ALB keeps idle client connections ~10 minutes), retry once on a fresh one. Never retry a request that has started streaming.
  3. Enable TLS session resumption on the client so a reconnect is one round-trip.
  4. Same pattern in src/harness/codex.cpp / opencode.cpp only if they own an HTTP client of their own; if they hand the tool a base URL and the tool's client talks directly, they are unaffected.

Done when

A packet capture of a second request in the same session shows no TLS handshake, and the per-turn TTFT in a real agent session drops by roughly the handshake time.

Related: the cancel-on-close issue (same file), InferenceInfra #299.

AmanSwar avatar Sep 12 '26 12:09 AmanSwar

Plan — wally #80: reuse the shim's upstream connection

Done when (from the issue): a second request in the same wally session shows no TLS handshake, and per-turn TTFT drops by roughly the handshake time.

What the code does today

src/anthropic/messages.cpp builds a fresh httplib::Client per request — in the streaming sink (HandleStreaming, ~L183) and in HandleNonStreaming (~L119) — so every request pays TCP connect + TLS handshake (~541 ms measured against the regional ALB). The shim's httplib::Server runs a thread pool, so requests are concurrent; an httplib::Client serialises requests on its single socket (request_mutex_), so one shared client would make Claude Code's parallel side calls wait behind a long stream. Hence a pool, not a singleton. src/ide/openai_proxy.cpp has the same pattern at three sites.

Design

  • New src/net/upstream_pool.{h,cpp} — UpstreamPool(origin, api_key, read_timeout) holding idle httplib::Clients (each set_keep_alive(true), bearer set, 600 s read timeout as today, plus a 10 s connect timeout). Lease acquire() pops an idle client or builds one; the RAII Lease returns it on destruction only if the request completed cleanly; a lease marked discard() (stream aborted, transport error) drops the socket. Idle cap 4 (Claude Code's realistic parallelism); concurrent leases are unbounded. Mutex-protected; no global state.
  • Retry once on a stale reused socket. Pure decision RetryOnFreshConnection(error, status, receiver_called, was_reused): retry iff the client was reused, no HTTP status arrived, the receiver was never called (nothing reached the editor), and the error is connection-class (Connection, Read, Write, ConnectionClosed, SSLConnection). Never retry once bytes have streamed; never retry a fresh client (a real outage must surface). httplib already drops a socket that received FIN (is_socket_alive) before reuse; this covers the half-open case the ALB's ~10-minute idle timeout can leave.
  • Shim wiring. Runtime owns std::shared_ptr<UpstreamPool>; the streaming lambda captures it (same reason the current code captures shared_ptrs: the sink outlives the handler). Verbose mode logs upstream: reused|fresh. Behaviour otherwise unchanged: same translation, same error mapping, same Retry-After forwarding.
  • Out of scope, stated: TLS session resumption — cpp-httplib 0.46.1 does not implement it, so a reconnect is a full handshake regardless; keep-alive is the fix. HTTP/2 — not in httplib.

Steps (each with the test that proves it; every new test shown RED then GREEN, both runs quoted in the commit)

  1. Test harness first. tests/test_wally_anthropic.cpp (new executable, registered in tests/CMakeLists.txt like the others): a fake upstream httplib::Server on loopback serving /v1/chat/completions (JSON and SSE) that records request.remote_port per request. Test A: start the shim via anthropic::Start against it, send two sequential /v1/messages, assert the upstream saw the same remote port both times (same TCP connection). RED today — ports differ. Test B: two concurrent streaming requests → two distinct ports, both complete (guards against a serialising singleton).
  2. UpstreamPool + its unit tests (lease/return/discard/idle-cap/thread-safety, no sockets touched beyond loopback). Hermetic.
  3. Wire the shim (streaming + non-streaming) to the pool. Test A → GREEN; existing 10 tests stay green.
  4. Retry-once. Unit-test the decision table. Integration: fake upstream with set_keep_alive_max_count(1) (server closes after every response) → second request still succeeds; aborted-stream test (upstream streams slowly, editor side disconnects) → that connection is discarded and the next request succeeds on a new port.
  5. Docs + hygiene. One paragraph in docs/EDITORS.md (the translator keeps a connection per stream open across turns; reconnects once on a stale one); AGENTS.md untouched unless a rule needs it; scripts/ci/check-agents-sync.sh, clang-format on touched files, full ctest.
  6. System check (needs a signed-in session): wally claude-code -m glm-5.3-flash with the shim verbose against dev — second request logs reused; optionally a packet capture showing one handshake. Aman runs this, or I do with WALLY_CONSOLE_URL pointed at dev.
  7. Follow-up, separate PR unless you want it here: wire the same pool into src/ide/openai_proxy.cpp (3 sites).

Risks

  • Stale reused socket → covered by httplib's liveness check + the retry-once rule; a retry never repeats a request that has produced output.
  • Memory/sockets → idle cap 4; discarded leases close.
  • Windows → httplib abstracts Winsock; the pool uses only its public API.
  • Server-side Connection: close (e.g. LiteLLM restarts) → httplib honours it and reconnects; test 4 covers the mechanism.

Validation before the PR

cmake --build build && ctest --test-dir build --output-on-failure (all green, new suite included) · bash scripts/ci/check-agents-sync.sh · clang-format check · break-test quotes for tests A, B, retry, abort in the commits · draft PR against main, no attribution lines.

AmanSwar avatar Sep 12 '26 15:09 AmanSwar

Plan review — amendments before implementation

Reviewed the plan above against the shim and cpp-httplib 0.46.1. Core design stands (pooled keep-alive clients, RAII lease returned only on clean completion, retry only when nothing reached the editor). Five amendments:

  1. Step 6 is mandatory and quantitative, not optional. The hermetic tests prove httplib reuses a connection to our fake server; they cannot prove the real edge allows it (an ALB/Cloud Run Connection: close would leave every test green and the win at zero). Before the PR leaves draft: shim via wally claude-code --serve against dev, two requests with curl -w '%{time_starttransfer}', both numbers and a handshake count in the PR body. That is the issue's own done-when.
  2. Retry-once needs an integration test on the real path. set_keep_alive_max_count(1) makes the server send FIN, which httplib's is_socket_alive catches before sending, so the retry code never runs. Add a raw-socket fake upstream that serves request 1, then on request 2 reads the request and closes without responding: reused client → connection-class error, no status, receiver never called → retry on a fresh client → success.
  3. State the duplicate-generation risk. On a reused socket, "no bytes back" does not prove the server never processed the request. This is the curl/browser heuristic for stale keep-alives and is kept, capped at one retry, and logged (upstream: retried on fresh connection) so a duplicate is traceable. Recorded in the PR body as an accepted risk.
  4. Test B needs a latch. The fake upstream holds both concurrent streams open until both have arrived; otherwise legitimate reuse of a fast stream's connection makes the test flaky.
  5. The 10 s connect timeout is a behaviour change (today: httplib default 300 s). Kept, but named in the PR body as outside #80's strict scope.

Also recorded: connection reuse lapses across long tool runs (ALB idle timeout ~10 min) — one full handshake per lull, by design; goes in docs/EDITORS.md. Step 7 (JetBrains proxy, 3 sites) stays a separate PR.

AmanSwar avatar Sep 12 '26 15:09 AmanSwar

Monday MVP triage (2026-09-12): moved to important / P2, still open.

Connection reuse improves latency; user explicitly excluded performance-only work from Monday gates. Retain for follow-up and PR82 coordination.

This is a scope decision, not a fix or passing deployment claim. The final production acceptance gate is tracked in RunanywhereAI/InferenceInfra#280; reapply release-blocker if its stated workaround/disabled-feature assumption is not true of the release artifact.

sanchitmonga22 avatar Sep 12 '26 19:09 sanchitmonga22

Fixed on main (Rust port). The shim keeps its upstream connection open and reuses it across turns (src/net/upstream_pool.rs, src/net/http1.rs), opens a separate one for concurrent streams, and retries once on a fresh connection only when a reused one went stale. Checked today: sequential_requests_reuse_the_upstream_connection, concurrent_requests_use_separate_connections and stale_reused_connection_is_retried_once_on_a_fresh_one pass on main, along with the rest of test_wally_anthropic (24/24).

Siddhesh2377 avatar Oct 01 '26 11:10 Siddhesh2377