Skip to content

fix: reject short cache range reads - #251

Merged
ovaistariq merged 1 commit into
mainfrom
perfloop-pr-open-y103a1fep6
Oct 21, 2026
Merged

ovaistariq merged 1 commit into
mainfrom
perfloop-pr-open-y103a1fep6

Conversation

@perfloop

@perfloop perfloop Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

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: HIT marks 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_ShortPositiveReadRecoversSameETagRemainder checks exact same-ETag suffix completion.
  • TestBlockCache_ShortPositiveReadRejectsChangedETagRemainder checks no changed-version bytes are appended and the request is an error.
  • TestWholeBodyRange_ShortPositiveReadReturnsError checks a positive short cached Range is not counted as success.
  • TestWholeBodyRange_FirstClientWriteFailureIsError checks error accounting and no retry after a failed write.

Three preservation tests pass on both the comparison base and final source:

  • TestBlockCache_ShortFirstBlockFallsThroughBeforeCommit checks pre-commit upstream fall-through.
  • TestWholeBodyRange_ExactCachedReadSucceeds checks exact cached Range bytes and success.
  • TestServeFromCache_PostCommitErrorIsRecordedAsError checks 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, and env 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-blocks followed by make s3-tests, was also attempted: TAG built and passed the jemalloc check, but startup stopped without credentials, so make s3-tests did 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 getRangeStreamByKey now requires an inclusive range read to deliver exactly the requested byte span; partial reads surface io.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 RecordRequestResult on cache-backed GetObject paths so stream failures after X-Cache: HIT is set record tag_requests_total{status="error"} instead of success (whole-object cache serve, cached ranges, and block serves). Docs and comments clarify that X-Cache: HIT is 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.

@greptile-apps

greptile-apps Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5 Tier: plus

[Medium impact] The PR appears safe to merge; no actionable new issues were found.

Summary

Rejects cache range reads that return fewer bytes than requested and records committed stream failures as request errors.

  • Cached range reads now have to return every requested byte.
  • Cache stream failures now count as request errors.

Reviews (2) · Last reviewed commit: "fix: validate cached range lengths" · Reviewed by Greptile

@perfloop
perfloop Bot force-pushed the perfloop-pr-open-y103a1fep6 branch from af4effd to bd9f9a8 Compare October 21, 2026 12:48
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
ovaistariq merged commit 3f2c8dd into main Oct 21, 2026
11 checks passed
@ovaistariq
ovaistariq deleted the perfloop-pr-open-y103a1fep6 branch October 21, 2026 18:59
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 21, 2026
@tigrisdata-argocd-bot

Copy link
Copy Markdown

🎉 This PR is included in version 1.22.3 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants