Repository navigation
fix(proxy): recover upstream requests the gateway accepted but never answered - #597
Conversation
…r answered The IBM LiteLLM gateway sometimes accepts a request and never sends a response byte. The TCP connection stays healthy: every request byte is ACKed and TCP keep-alives are answered for the full 10 minutes. With a 10-minute ResponseHeaderTimeout, each such request held the turn until Claude Code gave up (~300 s, logged as "context canceled"), the keep-alive ping hit 60 s, or the proxy returned 502/504 at 600 s. Packet capture of real traffic on contextguru2 (2026-10-18): 911 upstream requests, 63 hung. 34 of the 63 were the first request on a new connection, so this is not connection reuse. The same request, sent again on a new connection, is answered. For a streaming request, the upstream sends response headers as soon as it accepts the request. So silence after the request is written is a reliable signal. Now: - A streaming request with no response byte 45 s after it was written is cancelled and sent once more on a new connection. - The 45 s budget is above 99.9% of the measured answered first bytes. - Non-streaming requests are not touched: their headers come only when the answer is complete. - No byte has reached the client when the resend starts, so no stream is replayed. At most one resend. The client's own cancellation is never resent. - /metrics exports cg_upstream_silent_resends_total and cg_upstream_silent_failures_total. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: Osher-Elhadad <[email protected]>
http.DefaultTransport keeps at most 2 idle connections per host. When a burst of N streams to one gateway ends, N-2 healthy connections are closed at once, and the next burst pays N-2 new TCP+TLS handshakes. Measured on contextguru2 (2026-10-18): 172 of 388 upstream connections were closed less than 1 s after their last response for this reason. Up to 16 were open at the same time. - MaxIdleConnsPerHost is now 32 on the upstream transport. - IdleConnTimeout stays at 90 s. A shorter value only adds handshakes: the gateway hangs requests on fresh connections as often as on reused ones (see upstreamsilence.go). Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: Osher-Elhadad <[email protected]>
The IBM LiteLLM gateway sometimes closes a kept-alive connection right after our request is written: the packet capture shows the request ACKed, then about 1 s later the gateway's TLS close_notify and FIN, and never a response. Go reports this as "Post ...: EOF". Go's transport retries this exact case only for idempotent requests. A POST is not one, so every occurrence became a 502: 55 on contextguru2 since September, including the 2026-10-18 benchmark failure at 15:21:33. The request was never processed: no byte came back, so the upstream had not started a response and nothing reached the client. So: - On a REUSED connection, a request that was fully written and then got EOF with no response byte is sent once more on a new connection. This applies to streaming and non-streaming requests. - A fresh connection that is closed on us is a real failure and is returned as one, so a gateway that drops everything still fails fast. - /metrics exports cg_upstream_dropped_reuse_resends_total. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: Osher-Elhadad <[email protected]>
… count_tokens From an independent review of this branch: - Request.Close does not make the transport dial: the resend could take another idle pooled connection that the gateway had also dropped, and fail with the same "EOF" 502. Before a resend, the idle pool is now closed (CloseIdleConnections), so the resend dials. The dropped-reuse case may resend up to 2 times, as Go's own retry does; each resend uses a freshly dialled connection. - count_tokens called h.client.Do directly, so it still returned the unretried EOF 502. It now goes through the same guard, with no silence deadline. - A WroteRequest that fires after Do returned could start a 45 s timer. The timer is now guarded and is not started after Do returns or when the write failed. - The silence error now wraps the transport's error, so the log keeps the detail. - The comment no longer claims a dropped reused connection is "never processed". The worst case is one duplicated generation, never a duplicated stream. - Tests: several stale pooled connections dropped together (fails without the fix with the production error "Post ...: EOF"), a response cut off midway is not resent, a client that left is not resent, count_tokens recovers. The burst test no longer races on its channel. All new tests pass with -race. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: Osher-Elhadad <[email protected]>
Review round 1: findings and fixesIndependent review (a separate agent, read-only), then fixed in commit "address review: fresh connection on resend, count_tokens, races".
|
…ial tests
From a second independent review (no blockers):
- The watchdog checked "answered" and then cancelled, so a first byte
arriving between the two could have an answered attempt thrown away
and resent. Both now run under the attempt's mutex, so a byte and the
watchdog cannot both win.
- Three of the reviewer's adversarial tests are added:
- a first byte racing the silence deadline is never lost, corrupted,
or sent more than twice;
- 50 concurrent workers x 20 requests against a gateway that drops
and ignores requests at random: every request ends in its own
correct response or an error, sends stay within the bounds, and no
goroutine is left behind;
- closing the idle pool for a resend does not break 10 streams in
flight on the same transport.
Assisted-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Osher-Elhadad <[email protected]>
Review round 2: independent reviewer, with runsResult: no blockers. The reviewer ran the code, not only read it. All runs pass. Runs
Findings (all nits)
|
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (bob, user of @amiddavid) | IBM Bob Shell 1.0.3 | offload-review skill, @amiddavid's session | fresh | 1 of 2 | 1 of 2 | 9efa71cbe0cb |
blocking |
Verdict: blocking
Findings
-
proxy/upstreamsilence.go:219 — Watchdog timer can leak if client.Do panics
- What fails: If
client.Do(req)panics afterwatchdogis started (line 197) but beforestopWatchdog()executes (line 219), the timer continues running and eventually fires, callingcancel(errUpstreamSilent)on an already-returned context. - Proof: The
watchdogtimer is started inWroteRequestcallback (line 197). Thenclient.Do(req)is called (line 218). IfDopanics, execution jumps to the caller without reachingstopWatchdog()at line 219. The timer remains active and will fire aftersilenceduration, accessing theansweredatomic and callingcancelon a context whose owner has already returned. While Go'scontext.WithCancelCauseis safe to call multiple times, the timer itself leaks and the goroutine it spawns accesses variables from a returned stack frame. - Fix: Wrap
client.Do(req)in a defer-guarded block:Or movedefer func() { if r := recover(); r != nil { stopWatchdog() panic(r) } }() resp, err := client.Do(req) stopWatchdog()
stopWatchdog()into a single defer at the function start that checks ifwatchdog != nil.
- What fails: If
-
proxy/upstreamsilence.go:234 — Dropped reuse detection can false-positive on io.EOF from partial read
- What fails: The condition
reused.Load() && wrote.Load() && !answered.Load() && errors.Is(err, io.EOF)(line 234) treats anyio.EOFon a reused connection as a dropped keep-alive. However,io.EOFcan also occur if the response body is read to completion and then the connection is closed normally. Ifclient.Doreturns success but the body read (which happens later, outside this function) encounters EOF, this code path is not reached. But ifDoitself returnsio.EOF(which can happen if the server sends headers then immediately closes), this is correctly identified. The comment at line 231 says "A partial response ends in io.ErrUnexpectedEOF instead" which is correct for body reads, butDocan returnio.EOFfor a clean close after headers. Need to verify this doesn't false-positive. - Proof: Tested in
TestAResponseCutOffMidwayIsNotResent(line 537-560 of upstreamsilence_test.go) which sends partial headers and verifies it's NOT resent. The test shows a response cut off mid-headers returns an error that is NOT treated as a dropped reuse. However, the test doesn't explicitly verify the error isio.ErrUnexpectedEOFvsio.EOF. The implementation is likely correct becausehttp.Client.Dowraps transport errors, and a clean EOF after partial headers would beio.ErrUnexpectedEOF. But the comment could be clearer. - Fix: Add a comment clarifying that
io.EOFfromclient.Dospecifically means "connection closed before any response", not "response read to completion". Or add an explicit test case that verifies a response with headers but body EOF is not resent.
- What fails: The condition
Non-blocking
-
proxy/upstreamsilence.go:45 — The constant
streamSilenceTimeout = 45 * time.Secondis well-justified by the comment, but consider making it configurable viaOptions.StreamSilenceTimeoutfor deployments with different upstream characteristics. (Already done -Options.StreamSilenceTimeoutexists and is used.) -
proxy/upstreamsilence.go:328-345 —
upstreamTransportincreasesMaxIdleConnsPerHostfrom 2 to 32. The comment justifies this well with production measurements. Consider documenting this in the operator guide since it affects memory footprint (32 idle connections × N upstreams). -
proxy/upstreamsilence_test.go:594-620 —
TestAFirstByteRacingTheWatchdogIsNeverLostOrDuplicatedusesrand.Intn(12)to create timing races. This is good for finding race conditions, but makes the test non-deterministic. Consider adding a comment that this test may occasionally fail due to timing and should be re-run if it does. -
proxy/promexport.go:1044-1046 — The new metrics
cg_upstream_silent_resends_total,cg_upstream_silent_failures_total, andcg_upstream_dropped_reuse_resends_totalare well-documented. Consider adding a Grafana alert template forcg_upstream_silent_failures_total > 0since this indicates a genuinely failing upstream.
What I checked
- Read every changed line in all 6 modified files
- Verified fail-open behavior: resends only happen when no response byte arrived, never duplicate a partial response
- Confirmed test coverage: 805 lines of tests covering all code paths including edge cases (concurrent requests, client cancellation, truncated responses, etc.)
- Ran key tests on eval box:
TestASilentStreamingRequestIsResentOnANewConnection,TestAGatewayThatNeverAnswersFailsAfterOneResend,TestAReusedConnectionClosedUnansweredIsResentall pass - Verified metrics are properly exported and documented
- Checked that non-streaming requests are excluded from silence detection (correct - they get no silence deadline)
- Confirmed the fix addresses the production issue: 63 hung requests and 55 dropped reuse 502s from the packet capture
- Verified
freshAttemptcloses idle connections to force new dial, preventing reuse of other dropped connections - Checked
cancelOnCloseproperly releases attempt context when response body is closed - Confirmed
maxDroppedReuseRetries = 2bounds retry attempts to prevent infinite loops
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (bob, user of @amiddavid) | IBM Bob Shell 1.0.3 | offload-review skill, @amiddavid's session | fresh | 2 of 2 | 1 of 2 | 9efa71cbe0cb |
approve |
Verdict: approve
Findings
No blocking issues found.
Non-blocking
- upstreamsilence.go:227 — Error wrapping inconsistency
- The silence error wraps the transport error (
fmt.Errorf("%w: %w", errUpstreamSilent, err)), but the dropped-reuse case returns a custom type that also wraps. Both paths work correctly, but the wrapping styles differ. - Impact: None. Both preserve the underlying error for logging.
- Note: This is a style observation only. The implementation is correct.
- The silence error wraps the transport error (
What I checked
- Full diff review: Read all 806 lines of new test code, 256 lines of implementation, and integration changes in proxy.go, counttokens.go, and promexport.go.
- Core logic: The silence guard correctly implements the two recovery cases described in the PR:
- Streaming requests silent after being written are resent once after 45s
- Requests on dropped reused connections (EOF with no response byte) are resent up to 2 times
- Race conditions: The mutex properly guards the watchdog/first-byte race. Both
WroteRequestandGotFirstResponseBytetake the mutex, so a byte arriving while the watchdog fires either wins (no cancel) or loses (cancel before byte), never both. Thedoneflag prevents a lateWroteRequestfrom starting a timer afterDoreturns. - Fail-open behavior: Maintained at every level:
- Parent context cancellation is never turned into a resend (line 223)
- Only exact EOF shape on reused connections triggers retry (line 233)
- Fresh connections closed on us are returned as real errors (line 422 test)
- At most 1 silence resend + 2 dropped-reuse retries (lines 122-138)
- Integration points:
proxy.go:2127: Correctly applies silence guard only to streaming requestscounttokens.go:98: Correctly uses guard with no silence timeout (non-streaming)- Both use
doWithSilenceGuardconsistently
- Connection pool management:
freshAttemptcloses idle connections before retry, forcing a new dial. Active streams are not idle and are unaffected (line 768 test proves this). - Metrics: Three new counters properly exported in promexport.go (lines 739-747):
cg_upstream_silent_resends_total,cg_upstream_silent_failures_total,cg_upstream_dropped_reuse_resends_total. - Test coverage: Comprehensive adversarial tests added in review rounds:
- First byte racing the deadline (line 580): never lost, corrupted, or sent >2 times
- 50 concurrent workers against randomly failing gateway (line 693): correct responses, bounded sends, no goroutine leak
- Closing idle pool during in-flight streams (line 768): streams complete
- Multiple dropped pooled connections (line 438): resend dials fresh
- Response cut off midway is not resent (line 490)
- Client cancellation is not resent (line 536)
- Non-streaming requests never get silence deadline (line 217)
- count_tokens recovery (line 551)
- Compilation: Verified proxy package builds successfully on eval box.
- Problem addressed: The fix directly targets the measured production failures:
- 63 of 911 requests hung for 10 minutes (6.9%)
- 55 EOF 502s since September
- Now recovered in ~45s for silence, immediately for dropped reuse
- Validation results: PR description shows 360 requests, 0 failures in final run with 3 dropped reused connections successfully recovered.
The implementation is correct, well-tested, and solves the stated problem. The mutex guards prevent the race conditions, fail-open is preserved, and the recovery logic is bounded and safe.
|
Integrator reply to reviewer 1, round 1 (head Finding 1 — the watchdog timer leaks if
Finding 2 —
Tests the integrator ran on the eval box at this head: the silence-guard tests with |
|
Integrator test results on the eval box, head Result: all pass. Each half of the fix has tests that fail when it is broken.
|
Summary
Fixes the 502s and the 5–10 minute hangs that users saw only through context-guru, not when calling the IBM LiteLLM gateway directly. Three fixes in
proxy/:Post ...: EOF).count_tokensuses the same guard (from review).What we found
From a packet capture of real traffic on contextguru2 (context-guru →
ete-litellm.ai-models.vpc-int, 2026-10-18), 911 upstream requests:EOF. It retries this case only for idempotent requests, so every one became a 502. There were 55 since September, including a user's benchmark failure at 15:21:33.MaxIdleConnsPerHostwas 2, with up to 16 open at once.Why context-guru made it worse
ResponseHeaderTimeoutis 10 minutes, so each hang kept the turn open until something else gave up. From 10-14 to 10-18, 825 of ~25,000 requests ended that way:context canceled;What changed
proxy/upstreamsilence.go(new):doWithSilenceGuard.req.Close).Request.Closewould not force that, so the idle pool is closed first (CloseIdleConnections).proxy/proxy.go:doUpstreamuses the guard. NewOptions.StreamSilenceTimeout.upstreamTransportsetsMaxIdleConnsPerHost = 32.proxy/promexport.go: new counters, so hangs stay visible:cg_upstream_silent_resends_totalcg_upstream_silent_failures_totalcg_upstream_dropped_reuse_resends_totalHow it was tested
proxy/upstreamsilence_test.go.-race. The fake gateways reproduce the captured behaviour: a request read, then silence; a reused connection closed with no response.Post ...: EOF. The pool test opens 6 extra connections.go test ./...passes; the wholeproxypackage also passes under-race. A few dashboard and tenant tests failed withSQLITE_BUSYwhen the whole suite ran in parallel on a loaded host; they pass when run alone. They don't touch the changed code.max_tokens: 1calls;Validation results
Isolated proxy built from the deployed commit (core v0.3.2 + IBM layer) on contextguru2, upstream
ete-litellm.ai-models.vpc-int, all three models. Traffic mix: streaming one-message calls, streaming multi-turn calls (thinking on), non-streamingmax_tokens: 1calls, pauses of 0.2–45 s, and concurrent bursts. A failure is any request without a complete response within 150 s.EOF502 (dropped reused connection), 1 × 150 s hangEOF502 (not yet fixed in that build)cg_upstream_dropped_reuse_resends_total 3)Latency is in the same range (p50 / p90 total, seconds; before #2 vs final, runs at different hours):
Not fixed: a NON-streaming request that the gateway never answers.
max_tokens: 1call.ResponseHeaderTimeout. In production these are keep-alive pings and Claude Code's own non-streaming calls.max_tokens: 1. Measured: p99.9 30.5 s, max 33 s.Technical notes
IdleConnTimeoutwas the obvious fix, and the capture rules it out:Assisted-By: Claude Opus 5.5 (1M context) [email protected]