Repository navigation
fix(proxy): resend a stream whose watchdog fired as its first byte arrived - #684
Conversation
…rived
The silence watchdog can cancel an attempt a moment before its first
response byte is reported. If net/http has already read the response,
its transport still returns it with a nil error, because it prefers a
response that races its context's cancellation. silenceAttempt then
handed that response on. Its body is tied to the cancelled context, so
the first read failed with errUpstreamSilent: the client got a 200 and
an empty stream, and no resend happened.
After Do returns a response, silenceAttempt now checks the context's
cause. If the watchdog fired, it closes the body and reports the attempt
as silent, so doWithSilenceGuard resends it once. A client that went
away is not resent. answered is now set under mu with the watchdog stop,
so a watchdog that has not cancelled yet never will.
The flaky test also counted sends per loop step. Under load, a request
handler can start after its call has returned, so its send was charged
to the next call ("sent 3"). The test now counts sends per call id after
the server stops.
Refs #674
Assisted-By: Claude
Signed-off-by: DAVID AMID <[email protected]>
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.309 | offload-review skill, @amiddaid's session | fresh | 1 of 2 | 1 of 2 | 1b5ce11a07f0 |
blocking |
Verdict: blocking
Findings
- PR description vs
proxy/upstreamsilence_test.go— the PR claims a test that is not in the commit- What fails: The PR body says "3 new tests" and names
TestALateFirstByteOnTheRealTransportNeverReachesTheClient("the realnet/httptransport
and a trace hook that holds the first byte. 300 calls; each must get the full body"). The
"How it was tested" table has a row "3 new tests, count=20 | this PR | all pass". Head
1b5ce11acontains only 2 new tests:TestAResponseThatLostTheRaceToTheWatchdogIsResent
andTestALateResponseForAClientThatLeftIsNotResent. So the table row cannot be true of the
code under review. - Proof:
grep -rn "LateFirstByte\|RealTransport" --include="*.go" .over the whole worktree
returns nothing.git show --stat HEADlists onlyproxy/upstreamsilence.go(+24/-6) and
proxy/upstreamsilence_test.go. - Why it matters: the missing test is the only one that runs the race on the real
net/http
transport. The two committed tests uselateByteTransport, a fake that encodes our own
assumption of hownet/httpbehaves (it returns a ready response with a nil error when the
context is cancelled, and that body is dead). If Go changes that behavior, the fake tests
keep passing and the production bug returns. The PR body itself says this test reproduced
the bug onorigin/main17 times in 300 calls — that regression guard is what is missing. - Fix: commit the real-transport test, or correct the PR description to say 2 new tests and
drop the table rows that reference it.
- What fails: The PR body says "3 new tests" and names
Non-blocking
proxy/upstreamsilence.go:52— the file-top invariant "it happens only when not one response
byte has arrived" is now imprecise. In the new late-response case, response bytes reach the
proxy before it resends. The guarantee that matters still holds (no byte reached the client),
but the sentence should say that.proxy/upstreamsilence_test.go:624—srv.Close()is no longer deferred. At.Fatalfinside
the loop leaves the server running. Test hygiene only.
What I checked
- Read
CLAUDE.mdanddocs/design.md. - Read the full diff and both files end to end, plus the
doWithSilenceGuardcall sites
(proxy/proxy.go:2146,proxy/counttokens.go:98). - Traced every order of the
mu/answered/watchdog race:- Watchdog callback wins
mufirst: it cancels, then the transport returns the response, and
the newcontext.Cause(ctx)check atproxy/upstreamsilence.go:226catches it. Body closed,
resent once. stopWatchdogwinsmufirst: it setsansweredunder the same lock the watchdog callback
takes, so the callback then seesansweredand never cancels. No healthy response is
discarded. This closes the old gap, whereanswered.Store(true)ran outsidemuafter
Dohad already returned.
- Watchdog callback wins
- Checked the resend bounds: the new error wraps
errUpstreamSilent, sodoWithSilenceGuard
allows at most one silence resend, and a second silence fails with the existing
"on two connections" error. The bound of 1 holds. - Checked the client-left path:
parent.Err() != nilreturns the parent's cause, which does not
wraperrUpstreamSilent, sodoWithSilenceGuardreturns it without a resend. - Checked
errors.Is(context.Cause(ctx), errUpstreamSilent)cannot fire when the context was
never cancelled (Causereturnsnil;errors.Is(nil, target)is false), and cannot fire on
a parent cancellation, whose cause is the parent's own. - Checked context release on every new path: the late branch closes the body and calls
cancel(nil)itself, since the body is not wrapped incancelOnClosethere. No leak. - Checked the changed race test's counting: per-call ids fix the false "sent 3" (a handler that
starts after its call gave up was charged to the next call), and counting aftersrv.Close()
(which waits for handlers) is sound. - Compile-level:
net/http/httptraceis imported in the test file; the fake transport's trace
callbacks are always set bysilenceAttempt, so no nil-field call.
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.309 | offload-review skill, @amiddavid's session | fresh | 2 of 2 | 1 of 2 | 1b5ce11a07f0 |
approve |
Verdict: approve
Findings
None. I could not break the change. My trace of every interleaving is under "What I checked".
Non-blocking
- proxy/upstreamsilence.go:52 — the file's header contract is now slightly stale. It says a resend "happens only when not one response byte has arrived". With this change, a byte may have arrived at the transport; the true invariant is "not one byte reached the client", which the new code comment states correctly. Suggest a one-line touch-up of the header bullet so the file's own safety contract stays exact.
- proxy/upstreamsilence_test.go:624 —
srv.Close()is not deferred. At.Fatalfinside the loop leaves the server running for the rest of the test binary. Trivial. - proxy/upstreamsilence_test.go:647 — the deterministic tests drive a fake transport that calls the trace hooks by hand. The real-transport half of the race stays covered only probabilistically, by the 44–55 ms racing test. Acceptable; the fake pins the proxy logic either way (if
client.Dohad returned an error instead of the late response, the olderr != nilpath gives the same resend, so the test asserts the behavior, not the transport's choice). - Pre-existing, not this PR: a late response whose parent context was cancelled (client gone, watchdog never fired) still takes the success path and gets a body tied to a dead context. No resend happens and the client is gone, so the harm is nil. Noted only so it is on record.
What I checked
- Read
CLAUDE.md,docs/design.md, the full diff, and both changed files in full. - The race being fixed, all four orderings. The watchdog callback,
GotFirstResponseByte, andstopWatchdogall serialize onmu:- Watchdog wins
mu,answeredfalse →cancel(errUpstreamSilent)→client.Doreturns an error → the olderr != nilpath resends. Unchanged. - Watchdog wins
mu, cancels, but the transport had already read the response and returns it with a nil error (net/http prefers a delivered response over the context error, golang.org/issue/39355). Old code handed on a body tied to the cancelled context — the bug. New code closes it and reports the attempt as silent. Fixed. GotFirstResponseBytewinsmu→answeredset → the watchdog callback no-ops → response handed on. Unchanged.Doreturns, then a fired-but-blocked watchdog runs. Old code setansweredafterstopWatchdog, outsidemu, so the late callback still cancelled a good response. Nowansweredis stored insidestopWatchdogundermu, and the callback re-checks it — no late cancel is possible. Fixed.
- Watchdog wins
- The new cause check cannot misfire.
errUpstreamSilentis set only by the watchdog on this attempt's ownWithCancelCausecontext, and only whenansweredwas false undermu— that is, before any traced first byte and beforeDoreturned.context.Causeon a non-cancelled context returnsnil, and a parent's cancellation propagates the parent's cause, nevererrUpstreamSilent. Soerr == nil && cause == errUpstreamSilentmeans exactly: headers arrived after the watchdog's cancel, and nothing was forwarded.silence <= 0starts no watchdog, so the count-tokens path (counttokens.go:98) is unaffected. - Resend bounds and metrics. A late-response attempt returns a
fmt.Errorf("%w: …", errUpstreamSilent), sodoWithSilenceGuardcounts it inupstreamSilenceResends, resends at most once, and a second silent attempt becomes the "two connections" failure. Matches the counters inpromexport.go:741. - Client-gone handling.
parent.Err()is checked after the body is closed and the attempt context released, before the marker error is returned — so a departed client never triggers a resend, same rule as theerr != nilpath. - No resource leak. The new branch closes
resp.Bodyand callscancel(nil)on every exit; the success path still wraps the body incancelOnClose. - The rewritten race test. Per-call
X-Callids fix the attribution problem the oldbefore/afterdelta had (a handler that starts after its call gave up was charged to the next call).srv.Close()waits for every handler, so the per-id counts are complete; a streaming call can produce at most one silence resend and the test server never drops a reused connection, so then > 2bound is the right assertion. The map is mutex-guarded and read only afterClose. - The two new deterministic tests.
lateByteTransportcalls thehttptracehook fields directly — valid Go, and all three hooks are non-nil becausesilenceAttemptinstalls the trace on the attempt context.http.ClientwithTimeout == 0does not independently check the request context, soDoreturns the fake's(resp, nil); the first-attempt flow (<-req.Context().Done(), then a dead body) reproduces ordering 2 in a fixed order. The second test cancels the parent vialateand asserts one attempt and an error. - Call sites and scope.
proxy.go:2146(streaming silence) andcounttokens.go:98(no silence) are the only production callers; the change is local tosilenceAttempt. No library package touched, no stored data, sodocs/data-dependence.mdneeds no row. - Live tests were not run (not approved); this review is a read-only trace.
The earlier commit left out the only test that plays the race on net/http's own transport. A trace hook holds the first byte of every first attempt until the watchdog has cancelled it. The client must never get the late response that the transport still returns. Refs #674 Assisted-By: Claude Signed-off-by: DAVID AMID <[email protected]>
|
Reviewer 1 is right: commit 1b5ce11 did not include Fixed in aefe0f0. That commit adds the test as it was when I ran it, and it changes no other file. Runs on the eval box (Go 1.26.4):
The PR body's claim of 3 new tests is now true on the branch. |
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.309 | offload-review skill, @amiddavid's session | resumed | 1 of 2 | 2 of 2 | aefe0f06d45f |
approve |
Verdict: approve
Findings
None. My round-1 finding is fixed, and the new commit changes no production code.
Earlier findings
- Mine, round 1 — the PR claimed a test that was not in the commit. Fixed.
aefe0f06addsTestALateFirstByteOnTheRealTransportNeverReachesTheClient
(proxy/upstreamsilence_test.go:696). It matches the PR body's description: the real
net/httptransport (upstreamTransport(30 s),proxy/proxy.go:328), a trace hook that
holds the first byte, 300 calls.- The test is sound, and it pins the race deterministically:
buildwraps the first attempt's context with aGotFirstResponseBytehook that blocks
on<-ctx.Done().httptrace.WithClientTracecomposes with the trace already on the
context, and the new hook runs beforesilenceAttempt's ownGotFirstResponseByte. So
answeredstays false until the watchdog has cancelled — the exact production ordering.- The watchdog then always fires before
Doreturns, so attempt 1 ends in one of the two
shapes the test comment names: a transport error, or the late response with a nil error.
Both paths resend, and the assertion is that the client never sees the dead body.
- The author's comment gives run evidence: on
origin/mainthe test fails at call 7 with
the bug message (body="" err=upstream accepted...); onaefe0f06, 15 runs pass. The
PR body's "3 new tests" claim is now true of the branch.
- Reviewer 2, round 1 — approve, no findings. I checked their trace of the four
interleavings against my own round-1 trace. We agree. Their non-blocking note that the fake
transport left the real-transport half covered only probabilistically is now answered by the
new test.
Non-blocking
- Still open from round 1 (both reviewers, no reply needed to merge):
proxy/upstreamsilence.go:52— the file-top invariant says a resend happens "only when not
one response byte has arrived". In the late-response case, bytes reach the proxy before the
resend. The true invariant, "not one byte reached the client", is what the code enforces.
One-line touch-up when the file is next touched. proxy/upstreamsilence_test.go:624—srv.Close()is still not deferred in the racing test.
Test hygiene only.proxy/upstreamsilence_test.go:709— the new test gives the resend a 5 ms silence budget.
The resent request is written and answered on loopback, so 5 ms is generous normally, but a
heavily loaded 1-CPU box with-racecan exceed it and fail the test as a "two connections"
silence error. If it ever flakes, raise the deadline, not the assertion.
What I checked
- Last review: round 1, 1b5ce11, 2026-10-23T15:57:15Z.
- New commits read: 1 —
aefe0f06"test(proxy): add the real-transport test of the watchdog
race" (36 lines,proxy/upstreamsilence_test.goonly, no production change). - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three saved files).
- New items since my last review, and what I did about each:
- Commit
aefe0f06: read the diff and the test in context. Checked its mechanics — the
httptrace composition order, the closure capturing the first attempt'sctx,attempts
scoped per iteration,buildcalled at most twice per call (one silence resend bound),
and that attempt 2 carries no blocking hook. No defect found. - Author comment at 2026-10-23T16:02:15Z (reply to my finding): verified the commit it names
does what it says, and that the run evidence it reports is consistent with the code. - Reviewer 2's round-1 review (posted 15:58:48Z, after mine): read in full; no findings, and
their four-way interleaving trace matches mine.
- Commit
- Re-checked that no other file changed since my last review:
git diff 1b5ce11a..HEADtouches
only the test file. - Live tests were not run (not approved); this review is a read-only trace.
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.309 | offload-review skill, @amiddavid's session | resumed | 2 of 2 | 2 of 2 | aefe0f06d45f |
approve |
Verdict: approve
Findings
None in the new commit.
Status of earlier findings
- Reviewer 1, round 1, finding 1 (the PR body named a third test that was not in
1b5ce11a) — fixed.- Commit
aefe0f06addsTestALateFirstByteOnTheRealTransportNeverReachesTheClientand changes no other file. The PR body's "3 new tests" claim is now true on the branch. I verified the test myself (trace below). - The author's comment reports eval-box runs: the 3 new tests pass
-race -count=5onaefe0f06, and the new test fails onorigin/mainat call 7 with an empty body anderr=upstream accepted the request but sent no response byte, on 1 attempt. I did not run tests (not approved). The reported failure signature matches my trace of the unfixed code: the transport returns the already-read response with a nil error, the old code hands its dead body on, and the body read fails with the attempt context's cause, which iserrUpstreamSilent. That is the bug this PR fixes, so the test is a real regression guard.
- Commit
- My round-1 non-blocking notes — not addressed, still non-blocking. The header sentence at
proxy/upstreamsilence.go:52("only when not one response byte has arrived") is still imprecise, andsrv.Close()atproxy/upstreamsilence_test.go:624is still not deferred. Both were suggestions; the author chose not to change them. I keep them as non-blocking only. - My round-1 note that the real-transport race was covered only probabilistically — the new test answers exactly that. Resolved.
Non-blocking
- proxy/upstreamsilence_test.go:715 — the resend's silence budget is tight. Attempt 2 answers instantly, but a machine stall longer than 5 ms between the request write and the first byte would judge the resend silent too, and the call fails with "on two connections" — a spurious red, not a product bug. The author ran
-race -count=5(1500 calls) clean. A larger budget would slow the test by 300 × the budget, so the trade-off is reasonable as is. - The new test forces one ordering only. Because the test's
GotFirstResponseBytereplaces the production hook on the first attempt,answeredis never set by the byte, so the watchdog always cancels beforeDoreturns (the buggy ordering). The healthy ordering —Doreturns, then a fired watchdog is suppressed byansweredundermu— stays covered only probabilistically, by the 44–55 ms racing test. That is the safe path, so this is acceptable.
What I checked
- Last review: round 1,
1b5ce11a07f0992d4ade94304b533e004a0476c2, 2026-10-23T15:58:48Z. - New commits read: 1 —
aefe0f06"test(proxy): add the real-transport test of the watchdog race". - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three saved files; the inline file is empty).
- New items since my last review:
- Commit
aefe0f06: read the full diff (36 lines,proxy/upstreamsilence_test.goonly) and the test in the file. No defect found. - Author comment at 2026-10-23T16:02:15Z: verified its claims against the branch — the test exists as described, and the reported failure signature is consistent with the bug.
- No reviews or comments newer than that; no inline comments exist on the PR.
- Commit
- The new test's mechanism, traced.
silenceAttemptwraps the attempt context with its own trace beforebuildruns. The test'sbuildwraps that context once more, on the first attempt only, with a trace whoseGotFirstResponseByteblocks onctx.Done().httptrace.WithClientTracecomposes: hooks that are nil in the new trace (GotConn,WroteRequest) are inherited fromsilenceAttempt's trace, so the watchdog still arms at 5 ms; the non-nil test hook replaces the production first-byte hook, soansweredis not set by the byte. The hook holds the transport's read loop until the watchdog cancels; the transport then either fails the attempt (olderr != nilpath) or, per golang.org/issue/39355, returns the already-read response with a nil error — the shape the new cause check must catch. Both shapes end in one resend, and the test asserts the client always gets the full body. Forced every iteration, so the race is deterministic on the real transport. - No deadlock or leak in the test. The blocking hook waits only on the attempt context, which the watchdog cancels 5 ms after
WroteRequest— no dependency on the transport. The late branch closes the body and releases attempt 1's context; the success path wraps attempt 2's body incancelOnClose, released by the test'sresp.Body.Close(). - Closure capture. The hook closure reads the
ctxvariable afterbuildreassigns it to the traced context; cancellation propagates from theWithCancelCauseparent to it. Both the traced and the plain attempt context are done when the watchdog fires. - Branch scope unchanged.
git diff --statagainst the base still touches onlyproxy/upstreamsilence.go(+24/−6) andproxy/upstreamsilence_test.go; the production code is byte-identical to the1b5ce11aI approved in round 1, so my round-1 trace of all fourmu/answered/watchdog orderings still stands. - Live tests were not run (not approved); this review is a read-only trace.
Summary
This is a real bug, not only a flaky test. Sometimes the silence watchdog fires a moment before the first response byte arrives. Then the guard hands the client a response that is already dead: a 200 with an empty stream, and no resend. In production, a stream whose first byte arrives at about the 45 s mark can end this way. This PR resends that attempt. It also fixes a second, separate fault in the test.
Refs #674. This PR fixes only the watchdog race test. The latency guard test and the status line test stay open in #674.
What we found
upstreamsilence_test.go:607(body="" err=upstream accepted the request but sent no response byte) meansdoWithSilenceGuardreturned a response with no error, and the body read then failed with the watchdog's own error.origin/main(1 CPU, 16 runs in parallel,-race): 7 failures in 1200 runs. The load runs did not keep the failure messages, so they do not show which fault each failure was. The race window is a few microseconds, so load alone hits it only rarely.net/httptransport. A trace hook holds the first byte until the watchdog has cancelled. Onorigin/main, the bad response reaches the client in about 1 call in 20 (17 of 300).sent 3. The test counted server requests between loop steps. A handler that starts after its call has returned was charged to the next call. With the product fix only, this gave 9 failures in 1200 runs.Why it happens
net/httptransport then has a response ready.transport.go,case <-ctxDoneChan).silenceAttempttreated a nil error as "answered" and returned the response. Its body is tied to the cancelled context, so the first read fails.What changed
proxy/upstreamsilence.go,silenceAttempt:client.Doreturns a response, it checkscontext.Cause(ctx). If the watchdog fired, it closes the body and returnserrUpstreamSilent.doWithSilenceGuardthen resends once, as for any silent attempt.answeredundermu, together with the watchdog stop. So a watchdog that has not cancelled yet never cancels a response that was handed on.proxy/upstreamsilence_test.go:TestAFirstByteRacingTheWatchdogIsNeverLostOrDuplicatednow tags each call with an id. It counts sends per id aftersrv.Close(), which waits for every handler.The guarantees from #597 stay: no response is lost, duplicated or cut off; at most 1 silence resend and 2 resends for a dropped reused connection; a client that gives up is never resent.
How it was tested
All runs are on the eval box, Go 1.26.4. "Load" means 6
yesprocesses and 16 parallel test binaries, all pinned to 1 CPU, withGOMAXPROCS=1and-race.-racecount=50, 6yeson 64 CPUsorigin/mainorigin/main-raceruns under loadorigin/main-raceruns, 0 in the plain runs (messages not kept)sent 3(the test's own fault)origin/maincodeorigin/maincode, new testsif false && ...)go test -race ./proxy/...go vet ./proxy/...,gofmt -l proxyThe new tests:
TestAResponseThatLostTheRaceToTheWatchdogIsResent: a fake transport returns the late response only after the cancel. The client must get the resend's body, after exactly 2 attempts and 1 counted resend.TestALateResponseForAClientThatLeftIsNotResent: the same, but the client leaves first. It must fail with 1 attempt.TestALateFirstByteOnTheRealTransportNeverReachesTheClient: the realnet/httptransport and a trace hook that holds the first byte. 300 calls; each must get the full body.Technical notes
🤖 Generated with Claude Code