Skip to content

fix(testaws): lock the request-body byte counter (data race) - #515

Merged
scttfrdmn merged 2 commits into
mainfrom
fix/testaws-request-body-counter-race
Sep 17, 2026
Merged

scttfrdmn merged 2 commits into
mainfrom
fix/testaws-request-body-counter-race

Conversation

@scttfrdmn

Copy link
Copy Markdown
Owner

go test -race ./... fails about one run in twenty with a race inside the test harness, not in anything under test:

Read at 0x00c0038a1250 by goroutine 197718:
  internal/testaws.(*recorder).snapshot()   recorder.go:589
  internal/testaws.(*TestServer).GETs()
  testaws_test.TestRecorderLogsARequestBeforeItsCallerCanObserveTheResponse.func1()

Previous write at 0x00c0038a1250 by goroutine 44553:
  internal/testaws.(*countingBody).Read()   recorder.go:389
  net/http.(*transferWriter).writeBody()
  net/http.(*persistConn).writeLoop()

countingBody increments a field of a Request that has already been published, and recorder.snapshot copies that struct — so the increment has to be under the recorder's own mutex. It was a bare *c.n += int64(n).

Why the in-flight wait doesn't cover it

This is the part worth writing down, because it's why the defect survived the round of work that added that wait.

snapshot waits for inFlight == 0 before copying, which covers everything the handler goroutine does between publish and serve. But the request body is not read by the handler. The reverse proxy hands it to its transport, which forwards it to the emulator from its own writeLoop goroutine — and the transport returns from RoundTrip on the response headers. So a response can arrive, the handler return, and serve() settle the request, while writeLoop is still counting bytes with nothing ordering it against a test reading the log.

Why it matters rather than being a technicality

A racing counter is a small wrong number, not a crash. RequestBytes is what every upload-path assertion in the tree measures, so a lost increment reads as a write path that sent fewer bytes than it did — a failure that blames the code under test.

No new test, and why

The existing TestRecorderLogsARequestBeforeItsCallerCanObserveTheResponse is the detector:

go test -race -count=30 -run TestRecorderLogsARequestBeforeItsCaller ./internal/testaws/

That fails before the change and passes after (verified both ways). One run in twenty is a weak detector, so I tried to force the interleaving deterministically and dropped the attempt rather than commit a test I couldn't show fails. Neither obvious route reaches this counter:

  • a faulted request never reaches the proxy, so its body is never read through the wrapper at all;
  • net/http's post-handler drain of an unread body happens inside its own body type, below the wrapper.

The window is specifically "upstream answered early", which the emulator does not do on request. The comment on countingBody records the reproduction command and both dead ends, so the next person doesn't repeat them.

Verification

  • go test -race -count=30 -run TestRecorderLogsARequestBeforeItsCaller ./internal/testaws/ — clean (13s), was reproducing the race
  • go test -race ./internal/testaws/ ./internal/storage/s3/ ./internal/compression/ — clean
  • golangci-lint run --new-from-merge-base=main at CI's pinned v2.12.2 — 0 issues
  • gofmt, go vet — clean

go test -race ./... failed about one run in twenty with a race inside the
harness, not in anything under test:

  Read at 0x...  by goroutine N:  recorder.snapshot() <- TestServer.GETs()
  Previous write by goroutine M:  countingBody.Read() <- persistConn.writeLoop()

countingBody increments a field of a Request that has already been published,
and snapshot copies that struct, so the increment has to be under the recorder
mutex. It was not.

The recorder in-flight wait does not cover it, which is why this survived the
round of work that added that wait. The wait covers what the handler goroutine
does between publish and serve; the body is not read by the handler. The reverse
proxy hands it to its transport, which forwards it from its own writeLoop
goroutine, and the transport returns from RoundTrip on the response headers -- so
the response can arrive, the handler return, and serve() settle the request
while writeLoop is still counting.

No new test. The existing concurrency test reports it at -count=30, and a
deliberate reproduction was tried and dropped rather than committed unverified:
a faulted request never reaches the proxy so its body is never read through the
wrapper, and net/http drains an unread body inside its own body type, below the
wrapper. The window is specifically "upstream answered early", which the
emulator does not do on request. The comment on countingBody records both the
reproduction command and why there is nothing sharper.
@scttfrdmn

Copy link
Copy Markdown
Owner Author

CI just reproduced this race on an unrelated pull request. #516 (the #185 stage-3 read path,
which touches only internal/compression and internal/storage/s3) failed its test job on
exactly this defect:

Previous write at 0x00c007349cd0 by goroutine 14800:
  internal/testaws.(*countingBody).Read()   recorder.go:389
  net/http/httputil.(*noopCloseReader).Read()
  io.discard.ReadFrom()
  net/http.(*transferWriter).doBodyCopy()   transfer.go:417

Read at 0x00c007349cd0 by goroutine 2090:
  internal/testaws.(*recorder).snapshot()   recorder.go:589
  internal/testaws.(*TestServer).GETs()     recorder.go:645
  ...TestRecorderLogsARequestBeforeItsCallerCanObserveTheResponse

Two things this adds to what the PR already says.

main is flaky right now, not just theoretically racy. The test that tripped it is a
pre-existing test in the tree, and the PR that hit it changes nothing in internal/testaws.
Any PR can draw this, and the failure it produces points at a file the author never touched —
which is the expensive kind of flake, because the first hour goes into a diff that is innocent.

This is the interleaving I could not construct on purpose. The comment on
countingBody records two dead ends: a faulted request never reaches the proxy so its body is
never read through the wrapper, and net/http's post-handler drain of an unread body happens
inside http's own body type, below the wrapper. The stack above is the third route and the one
that actually happens — httputil.ReverseProxy forwarding the request body to the upstream on
the transport's own goroutine, via transferWriter.doBodyCopy, while a test calls GETs().
RoundTrip returns on the response headers, so the handler can return and serve() can settle
the request while that copy is still counting. That is precisely the window the fix closes, and
it is reachable from the existing suite under CI's load without any deliberate help.

I am leaving the code as it is — the fix is correct and the reproduction command in the comment
(go test -race -count=30 -run TestRecorderLogsARequestBeforeItsCaller ./internal/testaws/) is
the same test CI just failed on, so it is already the detector. I would not add a new one now
that the real route is written down.

The comment described the detector as weak — about one run in twenty locally — and
listed only the two dead ends for forcing the interleaving deliberately. #516's `test`
job then failed on this race twice in a row, on a branch touching only
internal/compression and internal/storage/s3, which says two things the comment did
not.

Under load the race is not rare. The extra parallel test load of an unrelated branch
was enough to make it reliable, and the report it produces names a file that branch's
author never touched — the expensive kind of flake, since the first hour goes into an
innocent diff.

And the interleaving that actually occurs is a third route, neither of the two the
comment ruled out: the reverse proxy forwarding the request body to the upstream on the
transport's own goroutine, via transferWriter.doBodyCopy, while a test calls GETs().
That is the window this lock closes, so it belongs in the stack sketch rather than the
persistConn.writeLoop frame that was there.

Comment only; no behaviour change.
scttfrdmn added a commit that referenced this pull request Sep 17, 2026
…an be verified

This is #515's change to internal/testaws/recorder.go, unmodified except for its
comment, and it is here only so that stage 3 gets a CI signal that means something.
The canonical fix is #515, and the CHANGELOG entry stays there rather than being
duplicated here — whichever merges first makes the other's copy a no-op.

The reason it cannot wait: this branch's `test` job failed twice in a row on that
race, in a file this branch does not touch. Locally the race reports about one run
in twenty; under CI's load, with the ~1000 lines of extra parallel test this branch
adds, it is reliable. So without the fix there is no way to tell a real stage-3
regression from the flake, which makes the whole gate uninformative.

The comment is updated with what those two failures taught: the interleaving that
actually happens is the proxy forwarding the request body to the upstream on the
transport's goroutine, via transferWriter.doBodyCopy, while a test calls GETs(). The
comment previously recorded only the two dead ends for forcing it deliberately and
described the detector as weak, which understates it — weak locally, reliable under
load.
@scttfrdmn
scttfrdmn merged commit 6fd9d4c into main Sep 17, 2026
43 checks passed
scttfrdmn added a commit that referenced this pull request Sep 17, 2026
…stage 3) (#516)

* feat(s3): serve ranged reads of a framed object from its frames (#185 stage 3)

Stages 1 and 2 made a compressed object seekable; this is what makes a ranged
read of one cheap. A 4 KiB read of a 1 MiB ~50%-compressible object went from
transferring the whole 1,074,071-byte stored body to 134,554 bytes: the frame
index plus the one frame covering the offset. The saving scales with the object
rather than the read.

readFramed sizes its first request from the objectfs-seekable descriptor the
write path records, parses the index, and fetches the frames covering the range
as one Range — CompressFramed lays frames down contiguously, so a contiguous
span of content is a contiguous span of stored bytes. Both encoded arms of
GetObject's switch try it: the 206 arm, and the 416 arm that a large
well-compressed object is most often read through.

Integrity is per frame and, for a partial read, stronger than what it replaces.
The whole-content objectfs-sha256 cannot be checked by a read that deliberately
never holds the whole content, so DecodeFrames verifies each frame's SHA-256
against the index instead — covering exactly the bytes returned, at frame
granularity. A read covering every frame is sent down the whole-object path,
which restores the whole-content check and is also the cheaper request. A frame
that does not match its hash is non-retryable DATA_CORRUPTION rather than a
fallback: the whole-object path is not a second opinion, since the same damaged
bytes are in that stream too.

Every other decline is counted with its reason, because none of them fails. A
declined framed read still returns the object byte for byte, so the failure mode
is a silent return to whole-object transfer with no evidence attached. Hence
seekable_reads, seekable_read_bytes, seekable_whole_fallbacks and
seekable_last_fallback_reason, each decline logged at warn rather than debug, and
an object that was never framed left uncounted so the number does not become a
measure of how much of the bucket is unframed.

An overwrite between the index fetch and the frame fetch is otherwise entirely
silent — both succeed, the lengths add up, and the frames are decoded against an
index that no longer describes them. The two ETags are compared and a mismatch
falls back. ETag comparison rather than If-Match, per CLAUDE.md's rule about
establishing capabilities by probing: a store that accepts a precondition and
ignores it is indistinguishable from one that honours it, and a comparison of two
values this process holds cannot be silently dropped.

Tests: a 50-case sweep either side of every frame boundary, aimed at the
frame-relative slice, whose failure mode is a uniform shift that errors nothing
and has the right length; the byte budget on both discovery routes, derived from
the object's own index; all five fallback reasons reached with real damaged
fixtures and the recorded reason asserted, since every one of these states
declines and a table checking only "a fallback happened" would pass with every
reason wired to the same string; the uncounted no-descriptor case; the mid-read
overwrite, made deterministic with Fault.OnFire; and the damaged-frame hard error.

Two existing tests asserted the pre-framing invariant and both had said in their
own comments that this was the change on which to revisit them rather than
quietly satisfy them, so both are revisited: read_amplification_test's
whole-body-was-transferred check becomes a budget, and
parallel_read_encoding_test's "an unranged GET was issued" is inverted to "every
GET was ranged". Both gain a guard asserting the fixture actually framed, so
neither can pass vacuously.

Filed #514: above parallel_read_threshold the fan-out is attempted first and
abandoned on finding the object encoded, and the chunks already launched have by
then transferred bytes framing would have avoided — 98% of the stored body in the
worst measured case. Bounded by concurrency x chunk size and correct in every
case, but it defeats framing where framing is worth most.

* test(s3,compression): cover the five paths a mutation run found untested (#185)

A mutation run over stage 3 caught 12 of 18 seeded defects. The five survivors
and what each needed:

- A read at exactly offset == UncompressedSize. This is the last request of
  every full-file read, and an off-by-one there is invisible to a correctness
  test because the whole-object fallback returns the same empty slice. The
  assertion is the request count and the fallback counter, not the bytes.

- Damaged frames. The existing test asserted a corruption error, which the
  fallback path also produces: reading the object whole fails its own
  objectfs-sha256 check over the same damaged bytes. It now asserts which check
  fired, via the message and the frame-level details only the framed path has.

- Open-ended reads (size <= 0). Resolving the length to UncompressedSize
  instead of UncompressedSize-offset still returns correct bytes, because
  FramesCovering clamps; it just fetches every frame to the end of the object.
  Asserted as a transfer budget.

- A non-zstd body carrying a seekable descriptor, read past the end of its
  stored body. That 416 route is where the post-index decoder check is the only
  decoder check there is; the previous fixture took the 206 route and was
  declined by the pre-fetch check instead.

- DecodeFrames and FrameDecoder had no direct tests at all. The body-length
  guard is unreachable from the backend, which computes the Range from the same
  index, so it is tested against the function: truncated, over-long, the whole
  object, and empty, each asserted to wrap ErrIndexCorrupt rather than to fail
  some later frame hash.

* style(s3): satisfy the pinned linter on the seekable read path (#185)

CI pins golangci-lint v2.12.2, which reports eight findings this branch
introduced. None is a defect; all eight are house style.

The three `tparallel` findings are the interesting ones. Each of the three
tests they name shares one backend and asserts on that backend's request
log and metrics, so their subtests cannot run in parallel — the transfer
budget a subtest checks is only meaningful if no other subtest is issuing
requests into the same recorder. `paralleltest` reports that at the range
statement and `tparallel` reports it at the function declaration, so a test
that legitimately cannot parallelise needs a suppression in both places.

* test(testaws): carry #515's request-body counter fix so this branch can be verified

This is #515's change to internal/testaws/recorder.go, unmodified except for its
comment, and it is here only so that stage 3 gets a CI signal that means something.
The canonical fix is #515, and the CHANGELOG entry stays there rather than being
duplicated here — whichever merges first makes the other's copy a no-op.

The reason it cannot wait: this branch's `test` job failed twice in a row on that
race, in a file this branch does not touch. Locally the race reports about one run
in twenty; under CI's load, with the ~1000 lines of extra parallel test this branch
adds, it is reliable. So without the fix there is no way to tell a real stage-3
regression from the flake, which makes the whole gate uninformative.

The comment is updated with what those two failures taught: the interleaving that
actually happens is the proxy forwarding the request body to the upstream on the
transport's goroutine, via transferWriter.doBodyCopy, while a test calls GETs(). The
comment previously recorded only the two dead ends for forcing it deliberately and
described the detector as weak, which understates it — weak locally, reliable under
load.
scttfrdmn added a commit that referenced this pull request Sep 17, 2026
…s own backoff (#519)

main is red. TestTheAccelerateEndpointComesBackWithinTheBackoff failed its vacuity
guard — "acceleration is still active, so nothing was withdrawn and this test cannot
observe a recovery" — and that diagnosis was wrong. The withdrawal did happen; the log
line immediately above the failure is "Retrying S3 Transfer Acceleration after backoff
backoff=25ms". The 25ms backoff had already expired by the time the guard looked.

So the guard conflated two states it cannot tell apart: never withdrawn, and withdrawn
and already recovered. Reading Active is also what performs the open→half-open
transition that sets it back to true — TestAccelerationStatsDoesNotReportAStateItJust-
Changed asserts that exact mechanism from the other side — so under load the guard could
cause the recovery it exists to rule out, then blame the gate for a fault that was the
clock's.

The fix is to assert on something monotonic. Fallbacks counts exactly this withdrawal
and only ever counts up, so no amount of elapsed time can make it lie in either
direction. Verified by mutation: dropping the injected fault leaves the guard firing
with the right message, so it still catches the vacuous run it exists for. 20 runs
under -race with the sibling acceleration test alongside it, clean.

Only this one assertion needed it. The file's four other Active reads are safe on
purpose: three are in tests configuring a one-hour retry, where the gate cannot reopen
underneath them, and the fourth deliberately sleeps 2*retry and asserts the
post-transition state.

Exposed rather than caused by #516: that PR added ~1000 lines of parallel test to this
package, and the extra load is what made a 25ms window get missed. The same load made
the #515 race deterministic in the same job. No CHANGELOG entry — this is a test
precondition, with no user-facing behaviour attached.
@scttfrdmn
scttfrdmn deleted the fix/testaws-request-body-counter-race branch September 17, 2026 04:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant