Skip to content

fix(proxy): recover upstream requests the gateway accepted but never answered - #597

Merged
amiddavid merged 5 commits into
mainfrom
fix/upstream-silent-connection
Oct 20, 2026
Merged

amiddavid merged 5 commits into
mainfrom
fix/upstream-silent-connection

Conversation

@OsherElhadad

@OsherElhadad OsherElhadad commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator

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/:

  1. A streaming request that the upstream accepted but never answered is sent once more on a new connection after 45 s, instead of waiting for the 10-minute header timeout.
  2. A request whose reused keep-alive connection is closed with no response byte is sent once more on a new connection, instead of returning a 502 (Post ...: EOF).
  3. The upstream connection pool keeps 32 idle connections per host instead of Go's default 2, so a burst of streams no longer pays new TCP+TLS handshakes on the next burst.
  4. count_tokens uses 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:

  • 63 hung (6.9%). For each one, the gateway ACKed every byte of the request, answered TCP keep-alives every 5 s for the full 10 minutes, and never sent one byte of response. No reset, no FIN.
  • Connection reuse is not the cause. 34 of the 63 were the first request on a new connection. Shortening the idle-connection timeout would have added handshakes and left most hangs in place.
  • The same request, sent again on another connection, is answered. A plain Go client with no context-guru in the path also hung (1 of 24 requests under 4-way concurrency).
  • Separately, the gateway sometimes closes a reused connection about 1 s after our request is written, with no response. Go reports 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.
  • 172 of 388 upstream connections were closed less than 1 s after their last response because MaxIdleConnsPerHost was 2, with up to 16 open at once.

Why context-guru made it worse

ResponseHeaderTimeout is 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:

  • Claude Code's own timeout, ~300 s, logged as context canceled;
  • the keep-alive ping, 60 s;
  • our own 502/504 at 600 s.

What changed

  • proxy/upstreamsilence.go (new): doWithSilenceGuard.
    • Silence (streaming only). A watchdog starts when the request is fully written. If no response byte arrives in 45 s, the attempt is cancelled and the request is sent once on a new connection (req.Close).
      • 45 s is above 99.9% of the measured first-byte times of answered requests (p99 19 s, max 58 s).
      • Non-streaming requests are not touched: their headers arrive only when the answer is complete.
    • Dropped reused connection (all requests). The request was fully written on a reused connection, then EOF arrived with no response byte: it is sent on a new connection, up to 2 times, as Go's own retry does. A fresh connection that is closed on us is returned as a real error.
    • A resend always dials. Request.Close would not force that, so the idle pool is closed first (CloseIdleConnections).
    • Safety.
      • At most one silence resend.
      • No byte has reached the client when a resend starts, so no stream is replayed.
      • A client that gives up is never resent.
  • proxy/proxy.go: doUpstream uses the guard. New Options.StreamSilenceTimeout. upstreamTransport sets MaxIdleConnsPerHost = 32.
  • proxy/promexport.go: new counters, so hangs stay visible:
    • cg_upstream_silent_resends_total
    • cg_upstream_silent_failures_total
    • cg_upstream_dropped_reuse_resends_total

How it was tested

  • New regression tests and adversarial tests in proxy/upstreamsilence_test.go.
    • Adversarial (from review): a first byte racing the deadline, 50 concurrent workers against a randomly failing gateway (no goroutine leak, sends within bounds), idle-pool close during in-flight streams. All pass under -race. The fake gateways reproduce the captured behaviour: a request read, then silence; a reused connection closed with no response.
    • Each fix's test fails without it. The end-to-end silence test hangs until killed. The EOF test returns the exact production error, Post ...: EOF. The pool test opens 6 extra connections.
    • The tests also cover:
      • a slow stream after the first byte is never resent;
      • a non-streaming request is never resent for silence;
      • a client that cancels is not resent;
      • a gateway that never answers fails after one resend.
  • go test ./... passes; the whole proxy package also passes under -race. A few dashboard and tenant tests failed with SQLITE_BUSY when the whole suite ran in parallel on a loaded host; they pass when run alone. They don't touch the changed code.
  • Real traffic. I ran an isolated proxy built from the deployed commit (core v0.3.2) against vpc-int, before and after the fix, with all three models. The traffic mix:
    • streaming one-message calls;
    • streaming multi-turn calls (thinking on);
    • non-streaming max_tokens: 1 calls;
    • pauses of 0.2–45 s and concurrent bursts.
    • Results: see Validation results below.

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-streaming max_tokens: 1 calls, pauses of 0.2–45 s, and concurrent bursts. A failure is any request without a complete response within 150 s.

Run Build Requests Failed Kind of failure
before #1 deployed 303 2 1 × EOF 502 (dropped reused connection), 1 × 150 s hang
before #2 deployed 360 0 —
after #1 silence guard only 336 1 1 × EOF 502 (not yet fixed in that build)
after #2 + pool + dropped-reuse 363 1 1 × non-streaming hang (out of scope, see below)
final this PR, after review 360 0 — (3 dropped reused connections happened and were recovered: 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):

Model before #2 final
Haiku 4.5 1.13 / 2.54 1.20 / 3.08
Sonnet 5 2.02 / 3.89 2.42 / 4.86
Opus 5 2.43 / 4.48 2.96 / 5.18

Not fixed: a NON-streaming request that the gateway never answers.

Technical notes

  • The idle-timeout question. Shortening IdleConnTimeout was the obvious fix, and the capture rules it out:
    • Hangs on fresh connections (8.8%) were as common as on reused ones (5.5%).
    • Raising the pool size removes handshakes rather than adding them.
  • Worst case of a resend: one duplicated generation on the provider (billed tokens), never a duplicated stream.
  • The hang itself is a gateway bug. It should also be reported to the LiteLLM / ai-models owners. These fixes stop it from turning into failed turns.

Assisted-By: Claude Opus 5.5 (1M context) [email protected]

Osher-Elhadad added 4 commits October 19, 2026 00:37
…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]>
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Review round 1: findings and fixes

Independent review (a separate agent, read-only), then fixed in commit "address review: fresh connection on resend, count_tokens, races".

  1. should-fix: req.Close=true does not force a new connection. Agreed and confirmed: queueForIdleConn ignores Request.Close, so a resend could take another idle pooled connection that the gateway had also dropped.
    • Fix: before each resend, freshAttempt calls CloseIdleConnections() on the transport. Busy connections are not affected.
    • The dropped-reuse case may also resend up to maxDroppedReuseRetries (2), as Go's own retry does.
    • New test TestAResendNeverReusesAnotherDroppedPooledConnection: 4 warm connections, all dropped. Without the fix it fails with the exact production error Post ...: EOF; with it, the request is answered on one freshly dialled connection.
  2. should-fix: "never processed" was overstated. Agreed. The comment now says the worst case is one duplicated generation (billed tokens, never a duplicated stream), and that the close about 1 s after the request fits the keep-alive race but does not prove it.
  3. nit: a late WroteRequest could start a timer after Do returned. Fixed: the timer is guarded by a mutex and a done flag, and it does not start when the write failed.
  4. Context and timer lifecycle: no change needed (all callers close resp.Body).
  5. Watchdog vs headers race: no change needed.
  6. Client cancel: covered by a new test, TestADroppedReuseIsNotResentAfterTheClientLeft.
  7. MaxIdleConnsPerHost=32: kept. The stale-pool risk it adds is closed by fix 1.
    • IdleConnTimeout is not shortened: the capture shows the vpc-int load balancer closes idle connections at 300 s, and hangs on fresh connections (8.8%) are as common as on reused ones (5.5%).
  8. should-fix: count_tokens used h.client.Do directly. Fixed: it goes through the guard with no silence deadline, so a dropped reused connection is resent there too. New test TestCountTokensRecoversADroppedReusedConnection.
    • The keep-alive ping uses the separate Dispatcher client. That client already sets GetBody, which is what Go's own retry needs, and a ping is cheap to lose. Not changed in this PR.
  9. Tests. The reassigned release channel race is fixed (mutex). Added: a response cut off midway (io.ErrUnexpectedEOF) is not resent (TestAResponseCutOffMidwayIsNotResent). The whole new set passes with -race. t.Context() is fine: go.mod is 1.26.
  10. nit: the silence error dropped the transport error. Fixed: it now wraps both.

…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]>
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Review round 2: independent reviewer, with runs

Result: no blockers. The reviewer ran the code, not only read it. All runs pass.

Runs

  • go build ./..., go vet ./..., gofmt -l .: clean.
  • New tests, -race -count=5: pass.
  • Whole proxy package, -race: pass on an idle machine (350 s).
    • One earlier failure, TestDashboardUnderConcurrentTraffic, happened while heavy tests ran in parallel.
    • Run alone, it passes on both this branch and the base 025fdcd2, so it is not caused by this PR.
  • Adversarial tests written by the reviewer (now added to the PR, commit 9efa71c):
    • First byte racing the 50 ms deadline, 200 iterations, -race: no lost or corrupted response, at most 2 sends per call.
    • Slow stream after headers, and a slow 4 MB upload: no resend, no cut-off. Upload time does not count as silence.
    • 50 workers × 20 requests against a gateway that randomly drops and ignores requests: every success is its own correct response, at most 4 sends (1 + 2 dropped + 1 silence), no goroutine leak.
    • Closing the idle pool during a resend while 10 streams are in flight: all 10 complete.
    • Client cancel: while waiting for headers, already cancelled, and during upload. Never resent.
    • /metrics: the 3 counters render as valid Prometheus text.

Findings (all nits)

  1. The watchdog checked "answered", then cancelled, so a byte arriving in between could have an answered attempt resent. Bounded and harmless, but now fixed: both steps run under the attempt's mutex.
  2. A caller-supplied Options.Client whose transport hides CloseIdleConnections gets no fresh-connection guarantee on a dropped-reuse resend. Bounded by the 2 retries, and documented. Not changed.
  3. A resend can happen in round ≥ 2 of the expand loop, after earlier rounds already streamed. Safe: only the current round's request is resent, and it had produced no bytes. Not changed.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. proxy/upstreamsilence.go:219 — Watchdog timer can leak if client.Do panics

    • What fails: If client.Do(req) panics after watchdog is started (line 197) but before stopWatchdog() executes (line 219), the timer continues running and eventually fires, calling cancel(errUpstreamSilent) on an already-returned context.
    • Proof: The watchdog timer is started in WroteRequest callback (line 197). Then client.Do(req) is called (line 218). If Do panics, execution jumps to the caller without reaching stopWatchdog() at line 219. The timer remains active and will fire after silence duration, accessing the answered atomic and calling cancel on a context whose owner has already returned. While Go's context.WithCancelCause is 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:
      defer func() {
          if r := recover(); r != nil {
              stopWatchdog()
              panic(r)
          }
      }()
      resp, err := client.Do(req)
      stopWatchdog()
      Or move stopWatchdog() into a single defer at the function start that checks if watchdog != nil.
  2. 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 any io.EOF on a reused connection as a dropped keep-alive. However, io.EOF can also occur if the response body is read to completion and then the connection is closed normally. If client.Do returns success but the body read (which happens later, outside this function) encounters EOF, this code path is not reached. But if Do itself returns io.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, but Do can return io.EOF for 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 is io.ErrUnexpectedEOF vs io.EOF. The implementation is likely correct because http.Client.Do wraps transport errors, and a clean EOF after partial headers would be io.ErrUnexpectedEOF. But the comment could be clearer.
    • Fix: Add a comment clarifying that io.EOF from client.Do specifically 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.

Non-blocking

  • proxy/upstreamsilence.go:45 — The constant streamSilenceTimeout = 45 * time.Second is well-justified by the comment, but consider making it configurable via Options.StreamSilenceTimeout for deployments with different upstream characteristics. (Already done - Options.StreamSilenceTimeout exists and is used.)

  • proxy/upstreamsilence.go:328-345 — upstreamTransport increases MaxIdleConnsPerHost from 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 — TestAFirstByteRacingTheWatchdogIsNeverLostOrDuplicated uses rand.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, and cg_upstream_dropped_reuse_resends_total are well-documented. Consider adding a Grafana alert template for cg_upstream_silent_failures_total > 0 since 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, TestAReusedConnectionClosedUnansweredIsResent all 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 freshAttempt closes idle connections to force new dial, preventing reuse of other dropped connections
  • Checked cancelOnClose properly releases attempt context when response body is closed
  • Confirmed maxDroppedReuseRetries = 2 bounds retry attempts to prevent infinite loops

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. 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.

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:
    1. Streaming requests silent after being written are resent once after 45s
    2. 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 WroteRequest and GotFirstResponseByte take the mutex, so a byte arriving while the watchdog fires either wins (no cancel) or loses (cancel before byte), never both. The done flag prevents a late WroteRequest from starting a timer after Do returns.
  • 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 requests
    • counttokens.go:98: Correctly uses guard with no silence timeout (non-streaming)
    • Both use doWithSilenceGuard consistently
  • Connection pool management: freshAttempt closes 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.

@amiddavid

Copy link
Copy Markdown
Collaborator

Integrator reply to reviewer 1, round 1 (head 9efa71cbe0cb). Both findings are rejected. No code change.

Finding 1 — the watchdog timer leaks if client.Do panics: rejected.

  • http.Client.Do does not panic on transport errors. It returns them.
  • If it did panic, the timer fires one time after silence and calls cancel(errUpstreamSilent). cancel of a WithCancelCause context is safe to call more than one time, and the context is already done.
  • The closure reads mu, answered and cancel. Go moves variables that a closure captures to the heap, so the timer never reads a "returned stack frame".
  • Result: one timer that fires one time and is then collected. That is not a leak and not wrong behaviour.

Finding 2 — io.EOF can be a false positive: rejected.

  • The match is reused && wrote && !answered && errors.Is(err, io.EOF) (upstreamsilence.go:233).
  • GotFirstResponseByte sets answered on the first byte of the response. A response that is cut off after any byte, in the headers or in the body, has answered == true and is never matched, whatever the error type.
  • TestAResponseCutOffMidwayIsNotResent covers this shape: the reply stops inside the headers (HTTP/1.1 200 OK\r\nContent-Le). The test requires exactly 2 upstream requests, so a resend fails it.
  • A body read happens after doWithSilenceGuard returns, so a body EOF cannot reach this code.

Tests the integrator ran on the eval box at this head: the silence-guard tests with -race -count=3: pass. The full ./proxy/... run with -race is in progress. Its result follows in a later comment.

@amiddavid

Copy link
Copy Markdown
Collaborator

Integrator test results on the eval box, head 9efa71cbe0cb.

Result: all pass. Each half of the fix has tests that fail when it is broken.

Run Result
20 silence-guard and count_tokens tests, -race -count=3 pass, 60 of 60
Full ./proxy/..., -race pass (340 s)
Mutation 1: no resend after silence 4 tests fail: TestASilentStreamingRequestIsResentOnANewConnection, TestAGatewayThatNeverAnswersFailsAfterOneResend, TestTheHandlerRecoversASilentStreamingTurn, TestClosingIdleConnectionsForAResendDoesNotBreakOtherStreams
Mutation 2: no resend after a dropped reused connection 3 tests fail: TestAReusedConnectionClosedUnansweredIsResent, TestAResendNeverReusesAnotherDroppedPooledConnection, TestCountTokensRecoversADroppedReusedConnection
  • The new tests do not compile on main, because they call the new functions. The mutations take the place of a "fails on main" run.
  • The round-1 reviewers ran 3 tests without -race. Reviewer 2's -race run lost its SSH connection, so the integrator ran it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants