Repository navigation
feat(cache): stream S3Origin via ByteStream::into_async_read (#271 PR4/4) - #516
Conversation
There was a problem hiding this comment.
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.
| 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) | ||
| } |
There was a problem hiding this comment.
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)
}| // verbatim. The engine surfaces the actionable message | ||
| // (`s3://…: body collect failed: …`) via | ||
| // `build_origin_anyhow_from_io`. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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::fetchto stream S3 bodies viaByteStream::into_async_read()→ReaderStream, removing the adapter-level full-bodycollect()and post-collect length check. - Preserve the headers-phase
Content-Lengthfast-path rejection, while relying on the engine’scount_and_cap_streamfor 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.
| /// 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. |
| // 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(); |
f5b1524 to
e286838
Compare
adbee33 to
09a39ed
Compare
|
Force-pushed Implemented:
Pushed back on:
|
|
Pushed Critical fixes
Coverage gaps closed
Comment / name rot
Pushed back on (with reasoning in commit message)
Verification
🤖 Generated with Claude Code |
e286838 to
ab1fa06
Compare
…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]>
f8f859b to
012549e
Compare
Coverage reportTotal: 88.20% (was 87.90%, ▲ +0.30%) — 12117/13738 lines
History
|
Summary
PR 4 of 4 for issue #271. Stacked on #515 (PR 3). Closes #271 once all four PRs land.
S3Origin::fetchnow streams viaByteStream::into_async_read()→tokio_util::io::ReaderStream. Thebody.collect().await.into_bytes()path and its post-collect length check are gone; the cap moves to the engine'scount_and_cap_stream(single cap layer across all three backends).Content-Length > max_bytes, before any body bytes stream.Why
into_async_read()aws_smithy_types::byte_stream::ByteStreamdoes implementfutures::Stream— but only on a private wrapper inside the SDK (theStreamtrait ispub(crate)to dodge stability concerns). The public seam isByteStream::into_async_read() -> impl tokio::io::AsyncBufRead. Going AsyncRead →ReaderStreamis one extra adapter hop versus a direct Stream, but it stays inside the SDK's stability guarantees and reuses the sametokio-utilplumbing the FS path already uses.End-to-end streaming achieved across all three backends
A 10 GB blob from any backend flows through iroh-blobs'
add_streamchunk-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_permanentrenamed tofetch_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 existingcache_engine_miss_pulls_from_s3_and_cachesintegration test which drives the cap viaCacheEngine.Test plan
cargo build --workspace— cleancargo clippy --workspace --all-targets— no warningscargo nextest run -p decdn-cache— 141/141 passcargo nextest run— 680/680 passcargo fmt -- --check— cleancargo deny check— advisories / bans / licenses / sources OKpre-commit run --all-files— all hooks pass🤖 Generated with Claude Code