Skip to content

fix(proxy): resend a stream whose watchdog fired as its first byte arrived - #684

Merged
amiddavid merged 2 commits into
mainfrom
fix/upstream-watchdog-race
Oct 23, 2026
Merged

amiddavid merged 2 commits into
mainfrom
fix/upstream-watchdog-race

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

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

  • The CI failure is the bug. The failure at upstreamsilence_test.go:607 (body="" err=upstream accepted the request but sent no response byte) means doWithSilenceGuard returned a response with no error, and the body read then failed with the watchdog's own error.
  • Under load the flaky test fails on 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.
  • A deterministic test shows it on the real net/http transport. A trace hook holds the first byte until the watchdog has cancelled. On origin/main, the bad response reaches the client in about 1 call in 20 (17 of 300).
  • The test had a second fault. Under load it also failed with 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

  1. The watchdog starts when the request is written. After the silence limit, it cancels the attempt's context if no byte has arrived.
  2. The bytes can already be in the socket buffer when it fires. The net/http transport then has a response ready.
  3. When the context is cancelled, the transport first checks for a ready response. If one is ready, it returns it with a nil error (transport.go, case <-ctxDoneChan).
  4. silenceAttempt treated a nil error as "answered" and returned the response. Its body is tied to the cancelled context, so the first read fails.
  5. No byte reached the client, but the guard did not resend. The client got a broken stream.

What changed

  • proxy/upstreamsilence.go, silenceAttempt:
    • After client.Do returns a response, it checks context.Cause(ctx). If the watchdog fired, it closes the body and returns errUpstreamSilent. doWithSilenceGuard then resends once, as for any silent attempt.
    • If the client went away too, it returns the client's error. It does not resend.
    • It now sets answered under mu, 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:
    • 3 new tests (see below).
    • TestAFirstByteRacingTheWatchdogIsNeverLostOrDuplicated now tags each call with an id. It counts sends per id after srv.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 yes processes and 16 parallel test binaries, all pinned to 1 CPU, with GOMAXPROCS=1 and -race.

Run Code Result
Flaky test, -race count=50, 6 yes on 64 CPUs origin/main 0 failures (not enough load; the plain count=200 run was stopped as too slow)
Flaky test, 400 + 400 runs, 2 CPUs origin/main 0 failures
Flaky test, 400 plain + 3 x 400 -race runs under load origin/main 7 failures in the -race runs, 0 in the plain runs (messages not kept)
Flaky test, 3 x 400 runs under load product fix, old test 9 failures; the 3 inspected were all sent 3 (the test's own fault)
Flaky test with per-call counting, 4 x 400 runs under load origin/main code 0 failures (load alone did not hit the race; the deterministic tests do)
Flaky test, 2000 runs under load this PR 0 failures
3 new tests, count=3 origin/main code, new tests all 3 fail, with the CI message
3 new tests, count=20 this PR all pass
Mutation: the new check disabled (if false && ...) this PR all 3 new tests fail
go test -race ./proxy/... this PR ok (427 s)
go vet ./proxy/..., gofmt -l proxy this PR clean

The 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 real net/http transport and a trace hook that holds the first byte. 300 calls; each must get the full body.

Technical notes

  • The fix is fail-open: the late response is only closed and replaced by a resend. If the resend is also silent, the client gets the same error it gets today for 2 silent attempts.
  • A resend happens only when no byte has reached the client, so a stream is never replayed.

🤖 Generated with Claude Code

…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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

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 (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

  1. 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 real net/http transport
      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
      1b5ce11a contains only 2 new tests: TestAResponseThatLostTheRaceToTheWatchdogIsResent
      and TestALateResponseForAClientThatLeftIsNotResent. 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 HEAD lists only proxy/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 use lateByteTransport, a fake that encodes our own
      assumption of how net/http behaves (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 on origin/main 17 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.

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. A t.Fatalf inside
    the loop leaves the server running. Test hygiene only.

What I checked

  • Read CLAUDE.md and docs/design.md.
  • Read the full diff and both files end to end, plus the doWithSilenceGuard call sites
    (proxy/proxy.go:2146, proxy/counttokens.go:98).
  • Traced every order of the mu/answered/watchdog race:
    • Watchdog callback wins mu first: it cancels, then the transport returns the response, and
      the new context.Cause(ctx) check at proxy/upstreamsilence.go:226 catches it. Body closed,
      resent once.
    • stopWatchdog wins mu first: it sets answered under the same lock the watchdog callback
      takes, so the callback then sees answered and never cancels. No healthy response is
      discarded. This closes the old gap, where answered.Store(true) ran outside mu after
      Do had already returned.
  • Checked the resend bounds: the new error wraps errUpstreamSilent, so doWithSilenceGuard
    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() != nil returns the parent's cause, which does not
    wrap errUpstreamSilent, so doWithSilenceGuard returns it without a resend.
  • Checked errors.Is(context.Cause(ctx), errUpstreamSilent) cannot fire when the context was
    never cancelled (Cause returns nil; 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 in cancelOnClose there. 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 after srv.Close()
    (which waits for handlers) is sound.
  • Compile-level: net/http/httptrace is imported in the test file; the fake transport's trace
    callbacks are always set by silenceAttempt, so no nil-field call.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

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 (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. A t.Fatalf inside 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.Do had returned an error instead of the late response, the old err != nil path 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, and stopWatchdog all serialize on mu:
    1. Watchdog wins mu, answered false → cancel(errUpstreamSilent) → client.Do returns an error → the old err != nil path resends. Unchanged.
    2. 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.
    3. GotFirstResponseByte wins mu → answered set → the watchdog callback no-ops → response handed on. Unchanged.
    4. Do returns, then a fired-but-blocked watchdog runs. Old code set answered after stopWatchdog, outside mu, so the late callback still cancelled a good response. Now answered is stored inside stopWatchdog under mu, and the callback re-checks it — no late cancel is possible. Fixed.
  • The new cause check cannot misfire. errUpstreamSilent is set only by the watchdog on this attempt's own WithCancelCause context, and only when answered was false under mu — that is, before any traced first byte and before Do returned. context.Cause on a non-cancelled context returns nil, and a parent's cancellation propagates the parent's cause, never errUpstreamSilent. So err == nil && cause == errUpstreamSilent means exactly: headers arrived after the watchdog's cancel, and nothing was forwarded. silence <= 0 starts 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), so doWithSilenceGuard counts it in upstreamSilenceResends, resends at most once, and a second silent attempt becomes the "two connections" failure. Matches the counters in promexport.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 the err != nil path.
  • No resource leak. The new branch closes resp.Body and calls cancel(nil) on every exit; the success path still wraps the body in cancelOnClose.
  • The rewritten race test. Per-call X-Call ids fix the attribution problem the old before/after delta 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 the n > 2 bound is the right assertion. The map is mutex-guarded and read only after Close.
  • The two new deterministic tests. lateByteTransport calls the httptrace hook fields directly — valid Go, and all three hooks are non-nil because silenceAttempt installs the trace on the attempt context. http.Client with Timeout == 0 does not independently check the request context, so Do returns 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 via late and asserts one attempt and an error.
  • Call sites and scope. proxy.go:2146 (streaming silence) and counttokens.go:98 (no silence) are the only production callers; the change is local to silenceAttempt. No library package touched, no stored data, so docs/data-dependence.md needs 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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Reviewer 1 is right: commit 1b5ce11 did not include TestALateFirstByteOnTheRealTransportNeverReachesTheClient. I added it after the WIP commit and did not stage it.

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

Run Code Result
The 3 new tests, -race -count=5 head aefe0f06 all 15 pass
TestALateFirstByteOnTheRealTransportNeverReachesTheClient, -race origin/main code fails: call 7: the client got a response whose watchdog had fired (1 attempts): body="" err=upstream accepted the request but sent no response byte

The PR body's claim of 3 new tests is now true on the branch.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

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 (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

  1. Mine, round 1 — the PR claimed a test that was not in the commit. Fixed.
    • aefe0f06 adds TestALateFirstByteOnTheRealTransportNeverReachesTheClient
      (proxy/upstreamsilence_test.go:696). It matches the PR body's description: the real
      net/http transport (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:
      • build wraps the first attempt's context with a GotFirstResponseByte hook that blocks
        on <-ctx.Done(). httptrace.WithClientTrace composes with the trace already on the
        context, and the new hook runs before silenceAttempt's own GotFirstResponseByte. So
        answered stays false until the watchdog has cancelled — the exact production ordering.
      • The watchdog then always fires before Do returns, 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/main the test fails at call 7 with
      the bug message (body="" err=upstream accepted...); on aefe0f06, 15 runs pass. The
      PR body's "3 new tests" claim is now true of the branch.
  2. 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 -race can 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.go only, 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's ctx, attempts
      scoped per iteration, build called 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.
  • Re-checked that no other file changed since my last review: git diff 1b5ce11a..HEAD touches
    only the test file.
  • Live tests were not run (not approved); this review is a read-only trace.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

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 (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

  1. Reviewer 1, round 1, finding 1 (the PR body named a third test that was not in 1b5ce11a) — fixed.
    • Commit aefe0f06 adds TestALateFirstByteOnTheRealTransportNeverReachesTheClient and 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=5 on aefe0f06, and the new test fails on origin/main at call 7 with an empty body and err=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 is errUpstreamSilent. That is the bug this PR fixes, so the test is a real regression guard.
  2. 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, and srv.Close() at proxy/upstreamsilence_test.go:624 is still not deferred. Both were suggestions; the author chose not to change them. I keep them as non-blocking only.
  3. 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 GotFirstResponseByte replaces the production hook on the first attempt, answered is never set by the byte, so the watchdog always cancels before Do returns (the buggy ordering). The healthy ordering — Do returns, then a fired watchdog is suppressed by answered under mu — 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.go only) 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.
  • The new test's mechanism, traced. silenceAttempt wraps the attempt context with its own trace before build runs. The test's build wraps that context once more, on the first attempt only, with a trace whose GotFirstResponseByte blocks on ctx.Done(). httptrace.WithClientTrace composes: hooks that are nil in the new trace (GotConn, WroteRequest) are inherited from silenceAttempt's trace, so the watchdog still arms at 5 ms; the non-nil test hook replaces the production first-byte hook, so answered is not set by the byte. The hook holds the transport's read loop until the watchdog cancels; the transport then either fails the attempt (old err != nil path) 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 in cancelOnClose, released by the test's resp.Body.Close().
  • Closure capture. The hook closure reads the ctx variable after build reassigns it to the traced context; cancellation propagates from the WithCancelCause parent to it. Both the traced and the plain attempt context are done when the watchdog fires.
  • Branch scope unchanged. git diff --stat against the base still touches only proxy/upstreamsilence.go (+24/−6) and proxy/upstreamsilence_test.go; the production code is byte-identical to the 1b5ce11a I approved in round 1, so my round-1 trace of all four mu/answered/watchdog orderings still stands.
  • Live tests were not run (not approved); this review is a read-only trace.

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.

1 participant