Repository navigation
fix: reject short cache range reads - #251
Merged
Merged
Conversation
[Medium impact] The PR appears safe to merge; no actionable new issues were found. SummaryRejects cache range reads that return fewer bytes than requested and records committed stream failures as request errors.
Reviews (2) · Last reviewed commit: "fix: validate cached range lengths" · Reviewed by Greptile |
Signed-off-by: Perfloop Agent <[email protected]>
perfloop
Bot
force-pushed
the
perfloop-pr-open-y103a1fep6
branch
from
October 21, 2026 12:48
af4effd to
bd9f9a8
Compare
ovaistariq
added a commit
that referenced
this pull request
Oct 21, 2026
PR #263 fixed two real bugs: a slow-consumer disconnect dropped its ErrSlowConsumer on the floor when the listener's buffer was full (so the cache listener drained to a clean close and committed a truncated body under the full Content-Length), and an upstream mid-body drop surfaced as io.ErrUnexpectedEOF, which the ocache backend accepted as "small value, done". The cachePipeReadError wrapping for the second bug is kept as is. Its fix for the first bug was unsafe: closeWithError made room for the error chunk by receiving one queued chunk. Channels are FIFO, so that removed the OLDEST unread chunk, and a consumer that had read chunks 0..k-1 next received k+1 at k's offset - wrong bytes on the wire before the error arrived. Replace the displacement with a terminal-error field on Listener: - closeWithError now records the error in Listener.termErr (written under Broadcaster.mu before close(ch)), tries a best-effort non-blocking send of Chunk{Err: err}, and closes the channel. Queued data chunks are never dropped or reordered. - Listener.Err() exposes the terminal error. It is valid once Chunks() has closed: the close happens-before the receive that observes it, so consumers read it without extra locking after their range loop ends. - Both consumers honour it. writeChunksToResponse (client path) returns Err() after the loop exactly as it would an error chunk, so a disconnected client never gets a clean EOF with a short body. setupCacheListener (cache path) sets chunkErr from Err() when the loop ended on a clean close, so the pipe fails and no metadata is committed. - Subscribe's already-done path records termErr too, for consistency. Defense in depth: PutWithMetaStreamIfVersion now counts the bytes the store consumed and refuses the meta commit with ErrBodyLengthMismatch when they differ from meta.ContentLength (short or long), mirroring the io.ReadFull guard in putBlocksFromStream. This closes the root cause behind #251 and #249 even if some future producer loses the error signal. The versioned body is left to age out via TTL, as with a lost precondition. Tests: the slow-consumer test now reads Err() after the loop (the error chunk is best-effort on a full queue); new broadcaster tests assert that a full-buffer disconnect delivers every queued chunk in order with no hole and then surfaces the error via Err(), and that a failed Complete on a full queue does the same; new cache tests assert a short or long body is not committed and an exact or unknown length still is. The PR's handler-level tests pass unchanged. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NGTev5ePU5jHubGtdoUfK6
ovaistariq
pushed a commit
that referenced
this pull request
Oct 21, 2026
Fixed two real bugs: a slow-consumer disconnect dropped its
ErrSlowConsumer on the floor when the listener's buffer was full (so the
cache listener drained to a clean close and committed a truncated body
under the full Content-Length), and an upstream mid-body drop surfaced as
io.ErrUnexpectedEOF, which the ocache backend accepted as "small value,
done". The cachePipeReadError wrapping for the second bug is kept as is.
Its fix for the first bug was unsafe: closeWithError made room for the
error chunk by receiving one queued chunk. Channels are FIFO, so that
removed the OLDEST unread chunk, and a consumer that had read chunks
0..k-1 next received k+1 at k's offset - wrong bytes on the wire before
the error arrived.
Replace the displacement with a terminal-error field on Listener:
- closeWithError now records the error in Listener.termErr (written
under Broadcaster.mu before close(ch)), tries a best-effort
non-blocking send of Chunk{Err: err}, and closes the channel. Queued
data chunks are never dropped or reordered.
- Listener.Err() exposes the terminal error. It is valid once Chunks()
has closed: the close happens-before the receive that observes it, so
consumers read it without extra locking after their range loop ends.
- Both consumers honour it. writeChunksToResponse (client path) returns
Err() after the loop exactly as it would an error chunk, so a
disconnected client never gets a clean EOF with a short body.
setupCacheListener (cache path) sets chunkErr from Err() when the loop
ended on a clean close, so the pipe fails and no metadata is committed.
- Subscribe's already-done path records termErr too, for consistency.
Defense in depth: PutWithMetaStreamIfVersion now counts the bytes the
store consumed and refuses the meta commit with ErrBodyLengthMismatch
when they differ from meta.ContentLength (short or long), mirroring the
io.ReadFull guard in putBlocksFromStream. This closes the root cause
behind #251 and #249 even if some future producer loses the error
signal. The versioned body is left to age out via TTL, as with a lost
precondition.
Tests: the slow-consumer test now reads Err() after the loop (the error
chunk is best-effort on a full queue); new broadcaster tests assert that
a full-buffer disconnect delivers every queued chunk in order with no
hole and then surfaces the error via Err(), and that a failed Complete
on a full queue does the same; new cache tests assert a short or long
body is not committed and an exact or unknown length still is. The PR's
handler-level tests pass unchanged.
ovaistariq
approved these changes
Oct 21, 2026
|
🎉 This PR is included in version 1.22.3 🎉 The release is available on GitHub release Your semantic-release bot 📦🚀 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
TAG could accept a positive short cache range as a complete hit, letting a GET end before its advertised Content-Length. The shared cache reader now checks the inclusive requested length. A committed block GET can recover only the exact unwritten suffix from an upstream 206 with the cached ETag, exact Content-Range, and full body length.
A short first block is detected before headers commit and still falls through to upstream. After a block response commits, an ETag mismatch or failed remainder leaves the sent 200 and Content-Length; the handler reports an error, and the client may receive an incomplete body. Changed-version bytes are never appended. A cached whole-object Range commits 206 when the first nonempty chunk arrives and cannot restart upstream; a positive short read returns an error with 206 and Content-Length unchanged. Client write failures are not retried.
X-Cache: HITmarks cache selection at commitment, not every byte's origin or successful completion; request success/error metrics remain separate from cache-hit counts.The regression fixture uses the pinned ocache v1.13.0 in-memory client with a block shorter than its metadata, plus a local HTTP upstream through the real forwarder. Four added regression tests fail on the comparison base and pass on the final source:
TestBlockCache_ShortPositiveReadRecoversSameETagRemainderchecks exact same-ETag suffix completion.TestBlockCache_ShortPositiveReadRejectsChangedETagRemainderchecks no changed-version bytes are appended and the request is an error.TestWholeBodyRange_ShortPositiveReadReturnsErrorchecks a positive short cached Range is not counted as success.TestWholeBodyRange_FirstClientWriteFailureIsErrorchecks error accounting and no retry after a failed write.Three preservation tests pass on both the comparison base and final source:
TestBlockCache_ShortFirstBlockFallsThroughBeforeCommitchecks pre-commit upstream fall-through.TestWholeBodyRange_ExactCachedReadSucceedschecks exact cached Range bytes and success.TestServeFromCache_PostCommitErrorIsRecordedAsErrorchecks the existing committed body-stream error mapping.The fixture demonstrates a possible backend short-read witness, not that normal population creates short blocks or how often deployed traffic sees one. The standalone program used for the source comparison is separate from this pull request.
This condition holds with this change and does not hold at
45b3f0a208a5aa6a5fd2e064d8fed7c60b836f40:For a cache-backed two-block BlocksComplete GET with an intact first block and a positive short nil-error read of block 1, HandleGetObject must not return success with fewer bytes than Content-Length: it must either return the complete byte-exact body under the cached ETag or return an error without recording success. If a committed response uses an upstream remainder, bytes from a different ETag must never be appended. A metadata-bounded cached whole-object Range GET with a positive short nil-error read must likewise return the exact requested bytes or surface an error; in each short-read case, a committed incomplete transfer must be recorded as an error rather than success. On a metadata-bounded cached whole-object Range GET with exact cached bytes, if the first downstream write fails after the 206 response commits, HandleGetObject must return that write error, record an error rather than success, and perform no further response writes or upstream requests..Local validation passed:
make lint-ci,env TAR_OPTIONS=--no-same-owner make test, andenv TAR_OPTIONS=--no-same-owner make test-integration.The default/tiered S3 profiles and SDK CI job were not run locally because the required AWS credentials were unavailable; those suites remain CI-owned checks. The repository-required block-mode sequence,
make s3-test-local-blocksfollowed bymake s3-tests, was also attempted: TAG built and passed the jemalloc check, but startup stopped without credentials, somake s3-testsdid not run. The workflow omits the block-cache profile; it remains a required credentialed pre-merge check.Generated by Perfloop.
Note
Medium Risk
Changes GetObject/range and block-cache streaming semantics and error accounting on committed responses; clients may see handler errors with partial bodies where success was previously reported incorrectly.
Overview
Fixes a bug where positive short cache range reads could be treated as complete hits, letting GET/206 responses stop before Content-Length while still counting success.
The shared cache reader in
getRangeStreamByKeynow requires an inclusive range read to deliver exactly the requested byte span; partial reads surfaceio.ErrUnexpectedEOF(bytes already written stay on the wire). Block-mode behavior after headers are committed is unchanged in spirit but documented and tested: same-ETag upstream remainder recovery, rejection of changed-version suffixes, and no upstream retry on client write failures.Request metrics now use
RecordRequestResulton cache-backed GetObject paths so stream failures afterX-Cache: HITis set recordtag_requests_total{status="error"}instead of success (whole-object cache serve, cached ranges, and block serves). Docs and comments clarify thatX-Cache: HITis the cache decision at commitment, not per-byte provenance or transfer completion.Adds integration/regression tests for short blocks, ETag mismatch, short whole-object ranges, and post-commit client write failures.
Reviewed by Cursor Bugbot for commit bd9f9a8. Bugbot is set up for automated code reviews on this repo. Configure here.