Skip to content

feat(cache): stream S3Origin via ByteStream::into_async_read (#271 PR4/4) - #516

Merged
thiras merged 2 commits into
mainfrom
cozy-conway-issue-271-pr4
May 10, 2026
Merged

thiras merged 2 commits into
mainfrom
cozy-conway-issue-271-pr4

Conversation

@thiras

@thiras thiras commented May 10, 2026

Copy link
Copy Markdown
Contributor

Summary

PR 4 of 4 for issue #271. Stacked on #515 (PR 3). Closes #271 once all four PRs land.

  • S3Origin::fetch now streams via ByteStream::into_async_read() → tokio_util::io::ReaderStream. The body.collect().await.into_bytes() path and its post-collect length check are gone; the cap moves to the engine's count_and_cap_stream (single cap layer across all three backends).
  • The fast-path Content-Length short-circuit at the headers phase still fires for Content-Length > max_bytes, before any body bytes stream.

Why into_async_read()

aws_smithy_types::byte_stream::ByteStream does implement futures::Stream — but only on a private wrapper inside the SDK (the Stream trait is pub(crate) to dodge stability concerns). The public seam is ByteStream::into_async_read() -> impl tokio::io::AsyncBufRead. Going AsyncRead → ReaderStream is one extra adapter hop versus a direct Stream, but it stays inside the SDK's stability guarantees and reuses the same tokio-util plumbing the FS path already uses.

End-to-end streaming achieved across all three backends

FilesystemOrigin:  File::take → ReaderStream → cap_at_max_bytes ─┐
HttpOrigin:        unfold(resp.chunk) → async-compression decoder┼→ count_and_cap_stream → iroh_blobs::Blobs::add_stream → store
S3Origin:          ByteStream::into_async_read → ReaderStream ───┘

A 10 GB blob from any backend flows through iroh-blobs' add_stream chunk-by-chunk. Per-fetch process heap is bounded by the chunk-buffer working set (a few KiB to a few MiB depending on the backend), not the blob size.

Test changes

fetch_oversize_body_is_permanent renamed to fetch_oversize_body_streams_through_for_engine_cap. The adapter-level test now confirms the stream produces all bytes and documents that the engine cap is the load-bearing defense — covered end-to-end by the existing cache_engine_miss_pulls_from_s3_and_caches integration test which drives the cap via CacheEngine.

Test plan

  • cargo build --workspace — clean
  • cargo clippy --workspace --all-targets — no warnings
  • cargo nextest run -p decdn-cache — 141/141 pass
  • cargo nextest run — 680/680 pass
  • cargo fmt -- --check — clean
  • cargo deny check — advisories / bans / licenses / sources OK
  • pre-commit run --all-files — all hooks pass

🤖 Generated with Claude Code

Copilot AI review requested due to automatic review settings May 10, 2026 13:03

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request transitions the S3 origin adapter to a streaming implementation using ReaderStream, which prevents large objects from pinning excessive memory. The size-capping logic has been moved from the adapter to the CacheEngine, and the test suite was updated to reflect this architectural shift. Review feedback suggests removing a redundant size check in the S3 adapter to allow for more specific error types from the engine and identifies a potential loss of origin-specific context in mid-stream error reporting that should be addressed for better observability.

Comment on lines +513 to 522
Some(len) => {
#[allow(clippy::cast_sign_loss)] // checked >= 0 above.
let len_u64 = len as u64;
if len_u64 > max_bytes {
return Err(OriginPullError::Permanent(anyhow::anyhow!(
"{log_target}: Content-Length={len} exceeds max {max_bytes}"
)));
}
Some(len_u64)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The max_bytes check here is redundant with the pre-stream check performed by the CacheEngine (in engine.rs). By removing this check and only providing the size_hint, the engine can return a more specific CacheError::BlobTooLarge instead of wrapping this anyhow error in a generic CacheError::OriginError. This centralizes the capping logic as intended by the PR description.

                Some(len) => {
                    #[allow(clippy::cast_sign_loss)] // checked >= 0 above.
                    Some(len as u64)
                }

Comment thread crates/cache/src/origin/s3.rs Outdated
Comment on lines +542 to +544
// verbatim. The engine surfaces the actionable message
// (`s3://…: body collect failed: …`) via
// `build_origin_anyhow_from_io`.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

This comment suggests that the engine surfaces the s3:// prefix for mid-stream errors via build_origin_anyhow_from_io. However, build_origin_anyhow_from_io in engine.rs only flattens the io::Error chain and does not have access to the log_target or origin-specific context. Unless the underlying SDK reader includes this information in its io::Error, the prefix will be lost for mid-stream failures. Consider updating the comment or wrapping the stream to preserve this context for better observability.

Copilot AI 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.

Pull request overview

This PR completes the #271 S3 backend portion by switching S3Origin::fetch from fully buffering S3 ByteStream bodies to returning a streaming OriginFetch::Found built from ByteStream::into_async_read() adapted via tokio_util::io::ReaderStream, aligning S3 with the filesystem and HTTP origins’ end-to-end streaming model and centralizing size enforcement in the cache engine.

Changes:

  • Update S3Origin::fetch to stream S3 bodies via ByteStream::into_async_read() → ReaderStream, removing the adapter-level full-body collect() and post-collect length check.
  • Preserve the headers-phase Content-Length fast-path rejection, while relying on the engine’s count_and_cap_stream for the running cap.
  • Adjust/rename the S3 origin oversize test to assert the adapter stream delivers the full payload (with the cap validated by engine-level integration coverage).

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
crates/cache/src/origin/s3.rs Switch S3 body handling to streaming via into_async_read() + ReaderStream, and plumb size_hint from Content-Length.
crates/cache/tests/s3_origin.rs Update oversize-body test to validate adapter streaming behavior and document cap responsibility moving to the engine.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread crates/cache/tests/s3_origin.rs Outdated
Comment on lines +432 to +449
/// Bodies larger than `max_bytes` are rejected when the consumer
/// drains the stream. Post-#271 the cap moved out of the adapter
/// (which now returns a chunk stream) and into the engine's
/// `count_and_cap_stream`. The adapter-level test confirms the
/// stream itself produces all bytes (no truncation, no silent
/// drop) — the engine integration test
/// `cache_engine_miss_pulls_from_s3_and_caches` end-to-end confirms
/// the engine cap actually rejects oversize bodies.
///
/// An origin can still lie in the `Content-Length` header (or omit
/// it for chunked responses), so the engine's running cap on the
/// streamed bytes is the load-bearing defense.
#[tokio::test]
async fn fetch_oversize_body_is_permanent() -> anyhow::Result<()> {
// 256 KiB payload, cap at 64 KiB. The SDK's mock layer doesn't set
// Content-Length unless we provide one explicitly, so this exercises
// the post-collect byte-count check rather than the fast-path
// `content_length()` short-circuit.
async fn fetch_oversize_body_streams_through_for_engine_cap() -> anyhow::Result<()> {
// 256 KiB payload, cap at 64 KiB. The SDK's mock layer doesn't
// set Content-Length unless we provide one explicitly, so this
// exercises the running cap on the streamed bytes rather than
// the fast-path `content_length()` short-circuit.
Comment on lines +526 to +545
// Stream the body chunk-by-chunk into the engine
// (issue #271). `ByteStream::into_async_read` yields a
// `tokio::io::AsyncBufRead` over the wire body —
// `aws_smithy_types`'s `Stream` impl is
// crate-private so we go through the AsyncRead seam,
// then back to `Stream<io::Result<Bytes>>` via
// `ReaderStream`. Chunks reach iroh-blobs'
// `add_stream` without the body ever sitting in
// process memory in full — a 10 GB S3 object no longer
// pins 10 GB of RSS.
//
// Mid-stream errors flow through the engine's
// side-channel just like the HTTP path:
// `aws_smithy_types::byte_stream::error::Error` is
// wrapped into the `io::Error` that `ReaderStream`
// emits, and `count_and_cap_stream` captures it
// verbatim. The engine surfaces the actionable message
// (`s3://…: body collect failed: …`) via
// `build_origin_anyhow_from_io`.
let async_read = resp.body.into_async_read();
@thiras
thiras force-pushed the cozy-conway-issue-271-pr3 branch from f5b1524 to e286838 Compare May 10, 2026 13:21
@thiras
thiras force-pushed the cozy-conway-issue-271-pr4 branch from adbee33 to 09a39ed Compare May 10, 2026 13:23
@thiras

thiras commented May 10, 2026

Copy link
Copy Markdown
Contributor Author

Force-pushed 09a39ed (rebased on updated PR 3 + review fixups).

Implemented:

  • Stale s3://...: body collect failed: ... comment (Gemini MEDIUM): rewrote. The streaming path no longer adds a log_target context to body errors — aws_smithy_types::byte_stream::error::Error flows through ReaderStream to count_and_cap_stream's side channel without the s3:// prefix. Comment now documents this honestly and notes that adding a body-phase context wrapper is a follow-up (would need a bespoke Stream::map(io_err → io::Error::other(format!("{log_target}: ..."))) adapter).
  • Test doc was misleading about "drains the stream" (Copilot): rewrote fetch_oversize_body_streams_through_for_engine_cap's doc to say "the adapter's body stream produces every byte the wire emits" and reference cache_engine_miss_pulls_from_s3_and_caches as the engine-level cap test. The previous doc claimed oversize bodies were rejected on drain, contradicting what the test actually asserts (the stream succeeds; engine-level rejection lives elsewhere).

Pushed back on:

  • Gemini MEDIUM "redundant max_bytes check vs engine pre-stream check": kept the adapter's Content-Length > max_bytes short-circuit. It produces a more specific operator-visible error (Content-Length=N exceeds max) than the engine's generic BlobTooLarge, and saves opening the body stream when the rejection is determinable from headers alone. The engine's running cap on streamed bytes still catches origins that lie in Content-Length (or omit it) — both checks have value at different layers.

@thiras

thiras commented May 10, 2026

Copy link
Copy Markdown
Contributor Author

Pushed f8f859b — aggregated review-fixup commit on top of the stack addressing findings from a 5-agent comprehensive review (code-review, silent-failure-hunter, comment-analyzer, pr-test-analyzer, type-design-analyzer).

Critical fixes

  • Cache-poisoning mitigation (engine.rs::pull_through). On hash mismatch, logically evict the actual hash via self.evict(actual) so the partial-import bytes briefly resident in iroh-blobs cannot be served by engine.has(actual) / engine.get(actual). Best-effort: a poisoned mutex or a full evicted-set cap surfaces only as tracing::warn! (primary returned error stays HashMismatch). Disk-side reclaim still depends on iroh-blobs GC integration (deferred to cache: drop double BLAKE3 hash once iroh-blobs exposes verified-insert #233 follow-up); engine-side reachability is closed.
  • Store-vs-origin error classification (engine.rs:1011-1019). When temp_tag() errors with no upstream-captured error, the failure is on iroh-blobs' side. Surface as CacheError::Store, not CacheError::OriginError.
  • Mid-flight BlobTooLarge typing. max_blob_bytes overruns now surface as the typed CacheError::BlobTooLarge variant (matching pre-streaming behavior). Implemented via a BlobTooLargeMarker packed into the side-channel io::Error and downcast at the engine boundary. Tests updated.

Coverage gaps closed

  • Added cache_engine_rejects_s3_body_larger_than_max_blob_bytes (the S3 counterpart to mid_stream_overrun_is_rejected_by_http_origin).
  • Strengthened hash_mismatch_is_rejected_and_not_cached to assert engine.has(actual) is also false — pins the cache-poisoning mitigation.

Comment / name rot

  • Renamed pull_through_succeeds_above_blocking_hash_threshold (the constant it referenced was removed).
  • Generalized PR-N temporal references in origin/mod.rs and origin/fs.rs.
  • Fixed cap_at_max_bytes doc that said "yields Err propagates through add_stream" — reality is the engine wrapper intercepts via side channel.

Pushed back on (with reasoning in commit message)

  • pub → pub(crate) for OriginByteStream/OriginFetch: workspace-internal crate; semver commitment doesn't apply.
  • Arc<Mutex<Option<io::Error>>> → OnceLock<StreamError> redesign: right long-term, deferred. The BlobTooLargeMarker addition satisfies the typed-error requirement without the full enum redesign.
  • Mid-stream retry-classification regression: out of scope; would need engine-level abort-and-restart-import.
  • iroh-blobs GC integration: tracked under cache: drop double BLAKE3 hash once iroh-blobs exposes verified-insert #233.

Verification

  • 143/143 cache tests pass (added 1 new S3 test, kept the typed-DecompressionFailed tests, updated 2 cap-error tests).
  • 682/682 workspace tests pass.
  • cargo clippy / fmt / deny / pre-commit all clean.

🤖 Generated with Claude Code

@thiras
thiras force-pushed the cozy-conway-issue-271-pr3 branch from e286838 to ab1fa06 Compare May 10, 2026 14:03
Base automatically changed from cozy-conway-issue-271-pr3 to main May 10, 2026 14:04
thiras and others added 2 commits May 10, 2026 17:04
…4/4)

PR 4 of 4 for issue #271 — final adapter cut-over to true streaming.
S3Origin::fetch swaps the buffered `body.collect().await.into_bytes()`
path for `ByteStream::into_async_read()` → `ReaderStream` → engine's
`add_stream`, so the body never materializes in memory in full.

`aws_smithy_types::byte_stream::ByteStream` doesn't implement
`futures::Stream` publicly (the Stream trait is `pub(crate)` in the
SDK), so we go through the AsyncBufRead seam exposed by
`into_async_read()` and convert back via `tokio_util::io::ReaderStream`.
The engine's `count_and_cap_stream` adapter handles the cap +
side-channel-on-error wiring uniformly across all three backends —
no S3-specific running-cap or post-collect length check needed in
this adapter.

The fast-path Content-Length short-circuit at headers phase still
fires (`Content-Length` > `max_bytes` → `OriginPullError::Permanent`
before any body bytes stream); origins that lie in the header are
caught by the engine's running cap mid-flight.

End-to-end memory check across all three backends:
- FilesystemOrigin: ReaderStream over `File::take(max_bytes + 1)` →
  engine. Per-fetch heap = chunk size.
- HttpOrigin: stream::unfold over `resp.chunk()` + async-compression
  bufread decoders → engine. Per-fetch heap = chunk size,
  decompression included.
- S3Origin: ByteStream::into_async_read → ReaderStream → engine.
  Per-fetch heap = chunk size.

A 10 GB blob from any of the three backends now flows through
iroh-blobs' `add_stream` chunk-by-chunk, capping process RSS at the
chunk-buffer working set rather than the blob size. Closes #271.

Test changes:
- `fetch_oversize_body_is_permanent` renamed to
  `fetch_oversize_body_streams_through_for_engine_cap` and updated:
  the adapter no longer enforces the cap (it streams chunks); the
  test confirms the stream produces all bytes and notes the engine
  cap is the load-bearing defense (covered by the existing
  `cache_engine_miss_pulls_from_s3_and_caches` engine integration
  test).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Aggregated review feedback from 5 specialized review agents (code-reviewer,
silent-failure-hunter, comment-analyzer, pr-test-analyzer, type-design-
analyzer) and fixed the highest-leverage findings here in a single fixup
commit on top of the 4-PR stack:

**Critical fixes:**

- **Cache-poisoning mitigation** (engine.rs::pull_through). Hash mismatch
  now logically evicts the actual hash via `self.evict(actual)` so the
  partial-import bytes briefly resident in iroh-blobs cannot be served by
  `engine.has(actual)` / `engine.get(actual)`. Best-effort: a poisoned
  mutex or a full evicted-set cap surfaces only as a `tracing::warn!`
  (the primary returned error stays `HashMismatch`). Comment now
  acknowledges that disk-side reclaim still depends on iroh-blobs GC
  (untracked under #233 follow-up); engine-side reachability is closed.

- **Store-vs-origin error classification** (engine.rs:1011-1019). When
  `temp_tag()` errors with no upstream-captured error, the failure is on
  iroh-blobs' side (disk write, actor crash, serialization-task panic).
  Surface as `CacheError::Store` rather than `CacheError::OriginError`
  so operators routing on origin-vs-store don't misclassify a local
  store problem as a remote origin one.

- **Mid-flight `BlobTooLarge` typing.** Pre-streaming, `max_blob_bytes`
  overruns surfaced as the typed `CacheError::BlobTooLarge` variant.
  After the streaming refactor they were flattening to generic
  `CacheError::OriginError`. Added a private `BlobTooLargeMarker` error
  type that the cap-breach paths in `count_and_cap_stream` (engine) and
  `response_chunk_stream` (HTTP) pack into the side-channel `io::Error`;
  the engine downcasts it via `io::Error::get_ref` and surfaces
  `CacheError::BlobTooLarge` with the right `limit_bytes`. Operators
  alerting on the typed variant continue to see the same shape they
  did before. Tests updated.

**Coverage fixes:**

- Added `cache_engine_rejects_s3_body_larger_than_max_blob_bytes`
  (s3_origin.rs) — the S3 counterpart to the HTTP `mid_stream_overrun`
  test. Without it the S3 path could regress (re-buffer in adapter,
  skip the engine wrapper) and #271's memory fix wouldn't actually
  constrain S3-fed pulls.

- Strengthened `hash_mismatch_is_rejected_and_not_cached` (pull_through.rs)
  to confirm `engine.has(actual)` is also false — pins the
  cache-poisoning mitigation above.

- Updated `http_origin_rejects_decompression_bomb` and
  `mid_stream_overrun_is_rejected_by_http_origin` to assert
  `CacheError::BlobTooLarge` rather than the generic `OriginError`
  they were flattening to before the marker.

**Comment / name rot:**

- Renamed `pull_through_succeeds_above_blocking_hash_threshold` →
  `pull_through_succeeds_above_one_mib_payload`. Old name referenced
  `BLOCKING_HASH_THRESHOLD`, a constant that was removed.

- Generalized PR-N temporal references in `origin/mod.rs` and
  `origin/fs.rs` — the docs no longer describe a transitional state
  that doesn't exist post-stack-merge.

- `cap_at_max_bytes` doc was stale ("yields `Err`, propagates through
  add_stream as a stream-side failure"). Reality: the engine wrapper
  intercepts the `Err` into the side channel and yields `None` to
  add_stream; the error surfaces back via the side-channel inspection.
  Doc rewritten to match.

**Pushed back on (not implemented):**

- `OriginByteStream` and `OriginFetch` `pub` visibility (code-reviewer).
  `decdn-cache` is workspace-internal; if it's ever published to
  crates.io the alias becomes a hard semver commitment. Until that
  changes, leaving `pub` is correct.

- `Arc<Mutex<Option<io::Error>>>` → `OnceLock<StreamError>` typed
  redesign (type-design-analyzer). Right call long-term but the
  `Mutex` isn't actually wrong (single-task write+read, poison
  recovery handled), and the `BlobTooLargeMarker` addition above
  satisfies the operator-visible typed-error requirement without the
  full enum redesign. Tracking as a follow-up.

- iroh-blobs GC integration (silent-failure-hunter). Out of scope for
  #271; tracked under #233. The cache-poisoning mitigation above
  closes the engine-side reachability angle without depending on GC.

- Mid-stream retry regression (silent-failure-hunter). The
  `OriginByteStream` doc explicitly admits stream errors bypass
  `retry_fetch`. Restoring transient-classification mid-stream would
  need engine-level abort-and-restart-the-import logic; out of scope.

Tests: 143/143 cache, 682/682 workspace pass. cargo clippy / fmt /
deny / pre-commit all clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@thiras
thiras force-pushed the cozy-conway-issue-271-pr4 branch from f8f859b to 012549e Compare May 10, 2026 14:05
@thiras
thiras merged commit 11cd4e5 into main May 10, 2026
0 of 10 checks passed
@thiras
thiras deleted the cozy-conway-issue-271-pr4 branch May 10, 2026 14:05
@github-actions

Copy link
Copy Markdown

Coverage report

Total: 88.20% (was 87.90%, ▲ +0.30%) — 12117/13738 lines

File Coverage Lines Δ
crates/cache/src/engine.rs 92.33% 1071/1160 ▲ +0.81%
crates/cache/src/origin/fs.rs 82.26% 269/327 ▲ +8.58%
crates/cache/src/origin/http.rs 93.66% 325/347 ▲ +6.00%
crates/cache/src/origin/mod.rs 81.16% 56/69 ▼ 18.84%
crates/cache/src/origin/s3.rs 91.46% 332/363 ▲ +1.30%
History
Commit Total Δ vs base
012549e (HEAD) 88.20% ▲ +0.30%

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.

cache: FilesystemOrigin.fetch reads the entire blob into memory before returning Bytes, preventing streaming delivery to the client for large blobs

2 participants