Skip to content

fix(proxy): detect incomplete whole-object cache hits - #249

Closed
perfloop[bot] wants to merge 13 commits into
mainfrom
perfloop-pr-open-wn2v7skqr5
Closed

perfloop[bot] wants to merge 13 commits into
mainfrom
perfloop-pr-open-wn2v7skqr5

Conversation

@perfloop

@perfloop perfloop Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

TAG now checks whole-object cache bytes against the positive recorded ContentLength before treating the local body as a successful GET. A short nil-error stream can otherwise expose a prefix while advertising the full length. Whether this occurs in production remains unmeasured.

In transparent and signing modes, a short buffered body is rejected before headers commit; when the origin fallback succeeds, TAG serves its complete response. If fallback fails before upstream headers arrive, TAG returns the error without committing the cached prefix. A short stream that has already committed headers cannot be replaced: TAG records a local request error, keeps the metadata Content-Length, and does not append origin bytes.

Tiered local reads have no upstream body path. For a short buffered local body, TAG discards the prefix, attempts version-guarded metadata cleanup, records a local error, and returns the documented NoSuchKey miss so the caller can fall back to its authoritative store. A committed short tiered stream remains incomplete, is recorded as a local error, and has no upstream append. Ordinary tiered misses keep their existing response accounting.

The shared whole-body helper also serves non-range 304 and stale responses. Proxy GET, revalidation, and stale paths use the existing ETag guard; tiered local cleanup uses the metadata version read for the request. Cleanup is best effort. If it fails, another request may encounter the same mismatch until metadata expires. Range and block-cache reads, zero-length objects, and unknown-length objects keep their separate existing paths.

The original-defect test TestHandleGetObject_CacheBodyLength injects a short nil-error body into authorized, non-range BlockSize == 0 GETs below and above 64 KiB. It checks the response body and advertised length, origin calls, request accounting, exact-size and zero-length controls, and tiered local outcomes. The preservation test TestTieredLargeShortBodyCleanupKeepsNewerSameETagPut gates a concurrent identical-content replacement and verifies that cleanup retains its newer metadata version. Additional tests cover repeated GET recovery, non-range revalidation/stale paths, overlong bodies, and pre-header fallback errors.

The correctness check recorded violated on test-only comparison revision 2d3e6fede525d4f8127c9b13c5358122f37f5c1d and satisfied on this change. The Python assertion adapter is proof-only support and is not included in the pull request. The injected cache fault does not measure production incidence.

The recorded local repository checks passed: make lint-ci, make build, make test, make test-integration, make test-race, and make test-coverage. make test-sdk and make s3-tests were not run because AWS credentials and a running local TAG were unavailable. Relevant SDK coverage includes TestSDK_GetObject_WithCache, TestSDK_LocalAuth_CacheHitAfterKeyLearning, and the sub-block case of TestSDK_BlockCache_FullGET_SizeRegimes in tests/s3compat/sdk; the Python suite selects test_s3.py::test_object_write_read_update_read_delete. Full repository CI remains pending.


Generated by Perfloop.


Note

High Risk
Changes core GET/cache-hit, revalidation, and tiered-local semantics where wrong length handling could truncate responses or mis-report object existence; cleanup paths differ between CAS and legacy coordinators.

Overview
TAG now validates positive-length whole-object cache bodies against metadata ContentLength on GET (and related paths), instead of treating a short or overlong stream as a successful hit.

In transparent/signing proxy modes, a mismatch detected before response headers commit triggers an upstream refetch; if that fails before origin headers arrive, the client gets the error with no committed cached prefix. After headers are committed, the response is recorded as a local error and no origin body is appended. Tiered-local reads have no body fallback: pre-commit mismatches return authoritative NoSuchKey without leaking bytes; post-commit mismatches are errors only. HEAD and metadata-only 304 paths (including tiered) add a final-byte range probe when length is known.

Cleanup uses version-guarded metadata delete where CAS allows it; legacy coordination stores TTL-bound length-mismatch hints (scoped by body identity and length) because it cannot delete by version, with readers rechecking before acting. Request coalescing broadcasts now surface terminal errors before headers to late listeners. Docs and broad proxy/cache/broadcast tests cover fallback, revalidation, overlong bodies, and same-ETag replacement safety.

Reviewed by Cursor Bugbot for commit ff287a7. Bugbot is set up for automated code reviews on this repo. Configure here.

@greptile-apps

greptile-apps Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5 Tier: plus

[High impact] The PR appears safe to merge; all previous findings are addressed and no new actionable issue was found.

Summary

TAG checks positive-length whole-object cache bodies before counting them as successful local reads.

  • Whole-object cache reads check that the body matches its recorded length.
  • Tiered local reads reject cached bodies shorter than their recorded length.
  • Listeners receive fetch errors even when response headers never arrive.

All three previous findings are addressed. Tests were inspected but not run during this review.

Reviews (2) · Last reviewed commit: "fix(proxy): guard short unexpected EOF c..." · Reviewed by Greptile

Comment thread proxy/revalidation.go Outdated
if !cw.committed {
return fmt.Errorf("cache body empty for %s/%s", bucket, key)
}
if bodyErr == nil && meta.ContentLength > 0 && cw.written != meta.ContentLength {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Oversized bodies bypass cleanup If the HTTP writer rejects a cached body for exceeding its declared Content-Length, ocache propagates the write error. Because this condition requires bodyErr == nil, TAG skips invalidation after committing the response. Later GETs can encounter the same damaged entry repeatedly. The overlong-body test uses a response recorder that accepts the extra bytes, so it does not cover this path.

Fix in Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this is valid. A Content-Length write error can make the cache stream return non-nil before the current nil-error length check runs, leaving an overlong entry in place. I’ll detect bytes offered beyond the recorded length, clean up only the observed metadata version, and test with a writer that enforces Content-Length.

Source feedback

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Response to this feedback.

Valid. An overlength stream remains a confirmed length mismatch even if the HTTP writer returns an error while rejecting excess bytes. I will make mismatch cleanup independent of a nil stream error and test a writer that rejects bytes beyond Content-Length.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in ff287a74e4e2b655ae24737b88aec989ccf92022. Response to this feedback.

The overrun check now detects the real HTTP writer's error after commitment. CAS removes only the observed metadata version; legacy records a TTL-bound length/body hint and rechecks the current body before a later cache stream. The server-backed test verifies the later request returns the complete origin response instead of replaying the overlong body.

Comment thread proxy/get_object.go Outdated
Comment on lines +222 to +223
} else if cacheBodyErr := s.serveFromCache(ctx, w, bucket, key, meta, start, func() {
s.invalidateStaleMeta(bucket, key, meta.ETag)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Fresh replacement can be removed If an identical-content replacement commits while an older short body is streaming, the mismatch callback checks only the ETag. The replacement has the same ETag, so cleanup can delete its fresh metadata, causing an unnecessary cache miss and origin refetch. Unlike the tiered cleanup path, this callback does not guard against the version observed by the request.

Fix in Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this is valid. An ETag does not distinguish an identical-content replacement, so the streaming cleanup must be tied to the exact metadata version observed by the request. I’ll use the version-guarded deletion path and test a replacement committed while the older stream is held.

Source feedback

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Response to this feedback.

Valid. An ETag alone is not a safe cleanup identity when an identical-content replacement can reuse it. I will guard cleanup with the version observed by the failing request and test that the replacement survives an older short stream.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in ff287a74e4e2b655ae24737b88aec989ccf92022. Response to this feedback.

The short-body path now uses the observed snapshot callback for both nil-error length mismatches and buffered io.ErrUnexpectedEOF short reads. Deterministic tests hold an older stream while a same-ETag replacement commits, then verify the replacement remains readable through ordinary GET, 304 revalidation, and stale fallback. Legacy uses the TTL-bound body/length hint rather than ETag-only deletion.

Comment thread proxy/localstore.go Outdated
Comment on lines +195 to +198
if errors.Is(serveErr, errCacheBodyLengthMismatch) {
// A damaged body still produces the mode's authoritative miss, but it
// must not be counted as a successful local object read.
return s.originlessMissWithRequestStatus(w, r, operation, start, "error")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Error classification is duplicated This branch classifies a body-length mismatch as an "error" request, while the streaming path separately assigns that status. The repository requires new error classification to be centralized in the metrics layer rather than duplicated in worker code. This requirement must be satisfied before merging so the two paths do not drift.

Rule Used: When adding error classification logic, prefer to centralize it in the metrics layer rather than duplicating the logic across multiple call sites in worker code. Move error classification functions to metrics.go and handle the branching logic within ... (source)

Learned From
tigrisdata/tigris-os#3043

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. The incomplete-body outcome should not set the request status independently in buffered and streaming worker branches. I’ll centralize the local request status classification in the metrics layer and route both paths through it.

Source feedback

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Response to this feedback.

Valid. The shared request-outcome mapping belongs in the metrics layer; buffered and streaming paths should retain their local detection but use the same mapping. I will centralize that classification and cover both paths.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in ff287a74e4e2b655ae24737b88aec989ccf92022. Response to this feedback.

Buffered and committed cache-length mismatches now use the shared request-outcome mapping in the metrics layer; length detection and response-commit handling remain path-specific. The native tests exercise both paths and assert the shared error outcome.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Want higher recall? High effort reviews run extra passes and find more bugs. A team admin can switch effort levels in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit ef96731. Configure here.

Comment thread proxy/localstore.go Resolved
@perfloop
perfloop Bot force-pushed the perfloop-pr-open-wn2v7skqr5 branch from ef96731 to ff287a7 Compare October 14, 2026 19:41
@perfloop

perfloop Bot commented Oct 14, 2026

Copy link
Copy Markdown
Contributor Author

Addressed in ff287a74e4e2b655ae24737b88aec989ccf92022. Response to this feedback.

The update distinguishes tiered-local authoritative misses from proxy metadata answers. Tiered-local HEAD and conditional responses now verify short bodies before returning a metadata-based success, while proxy metadata-only HEAD and 304 behavior remains unchanged.

@perfloop

perfloop Bot commented Oct 14, 2026

Copy link
Copy Markdown
Contributor Author

Whole-object cache hits can expose a prefix while their response advertises the full metadata length when a cache stream ends early. TAG now checks positive-length body size before treating a hit as complete.

Before headers commit, a short proxy body is rejected and the normal origin fallback can provide a complete response when the origin succeeds. After commitment, TAG retains the advertised length, records an error, and never appends an origin body. Exact-length bodies and zero-length objects remain valid on their existing paths. The shared whole-body path also covers revalidation and stale responses. A precommit io.ErrUnexpectedEOF with fewer bytes also uses the length-mismatch cleanup path; unrelated cache stream errors keep their existing handling.

Tiered-local metadata answers that would otherwise satisfy a positive-length HEAD or matching conditional 304 now verify the body after the existing first-byte presence check. Short bodies return NoSuchKey rather than a local hit, so the authoritative store can be consulted. Failed If-Match precedence remains unchanged for bodies passing the existing first-byte check. CAS cleanup removes only the metadata version read by the request. Legacy coordination lacks atomic version deletion, so a TTL-bound sidecar hint records body identity and expected length; subsequent reads recheck the current body before streaming. This avoids deleting a same-ETag replacement, but metadata can remain until replacement or expiry, old readers ignore the hint, and the extra legacy lookup's latency is unmeasured.

A failed upstream response before headers now wakes waiting and late broadcast subscribers without committing a cache prefix. README, architecture, cache-control, and tiered-mode docs describe these distinctions.

TestHandleGetObject_CacheBodyLength exercises nil-error short bodies below and above 64 KiB, exact and zero-length controls, and tiered metadata paths. The small-overlong case is covered separately by TestServeFromCache_OverlongBodyIsNotSuccessfulInCAS; TestLegacyOverlongHintPreventsIncompleteReplay exercises overlong streaming through the real HTTP writer and later recovery. TestHandleGetObject_EmptyCacheBodyPreservesSameETagReplacement gates a same-ETag replacement across empty and io.ErrUnexpectedEOF streams in ordinary GET, 304 revalidation, and stale fallback, including a large precommit read. TestHandleGetObject_LargeCacheHitPostCommitErrorDoesNotFallBack retains the generic post-commit cache-stream error case under the default legacy coordinator. The Python adapter used for the comparison is retained proof support and is not part of the pull request.

The stated condition holds with this change; it does not hold at b1ab9695c69a3255b5fe51e3422bdb1c7739fdf8.

Local lint, build, unit, integration, race, and coverage checks passed. Credentialed SDK checks and the s3-tests workflow remain for target CI. The injected cache fault establishes handling, not production frequency.


Generated by Perfloop.

@ovaistariq

Copy link
Copy Markdown
Contributor

Superseded by #269, which keeps the serve-side length check from this PR (pre-commit for buffered bodies, post-commit abort plus ETag-guarded invalidation for streamed bodies) and drops the persisted length-mismatch hint keys, the pre-serve probe and the HEAD/304 range reads. The write-side cause is closed in #263.

@ovaistariq ovaistariq closed this Oct 21, 2026
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 21, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants