Repository navigation
feat(cache): stream FilesystemOrigin + engine.add_stream (#271 PR2/4) - #517
Conversation
PR 2 of 4 for issue #271. Cuts FilesystemOrigin to true streaming via ReaderStream and switches the engine's pull_through from add_bytes to iroh-blobs' add_stream + temp-tag-then-promote pattern. Closes #233 as a side effect — the explicit BLAKE3 verification (and its spawn_blocking shim above 1 MiB) is gone; AddProgress.temp_tag().hash() is now the verification, single-pass. What this PR achieves end-to-end (FilesystemOrigin → store): - Per-fetch heap is bounded by ReaderStream's 4 KiB chunk size, not by the blob's full byte length. A 10 GB FS-origin pull no longer pins 10 GB of process RSS. - The post-read "file grew past max during read" check moves from a buffered length compare to a running-cap adapter (cap_at_max_bytes) wrapping ReaderStream::new(file.take(max_bytes + 1)) — same TOCTOU posture, same kernel-level cap, same error message. - Hash mismatch drops the TempTag without naming, so iroh-blobs' GC reclaims the bytes. Known regression vs the pre-PR-2 path: the unprotected bytes briefly land on disk under their actual hash and are visible to Blobs::has(actual_hash) until GC runs. Bounded by GC cadence; cache-poisoning surface is the same shape as pre-existing trust assumptions on origin honesty. iroh-blobs needs a verified-insert API (#233 follow-up) for the airtight version. What this PR still leaves unstreamed (PR 3 / PR 4): - HttpOrigin: still buffers the response body; PR 3 replaces the chunk-collecting loop with a stream::unfold + async-compression pipeline. - S3Origin: still calls body.collect(); PR 4 uses ByteStream's native Stream impl. - Both keep returning OriginFetch via the PR-1 found_one_shot shim, so the FS path is the only adapter that actually streams today. The engine works against any compliant Origin so PRs 3-4 ship independently. Tests: - 141/141 cache unit + integration tests pass (added 2 new FS tests: multi-chunk read drives ReaderStream across many polls, and the oversize-file rejection covers both fstat-time and stream-time caps). - 680/680 workspace tests pass. - cargo clippy --workspace --all-targets clean; cargo fmt clean; cargo deny clean; pre-commit clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
This PR advances the cache’s end-to-end streaming story (issue #271) by switching FilesystemOrigin from buffer-then-return (Vec/Bytes) to true streaming via ReaderStream, and by updating CacheEngine::pull_through to import via iroh-blobs add_stream + temp-tag-then-promote, removing the engine’s explicit pre-insert BLAKE3 hashing.
Changes:
- Stream filesystem-origin reads via
tokio_util::io::ReaderStreamwith an I/O-layer cap (take(max+1)) plus a running-cap wrapper. - Change
CacheEngine::pull_throughfromadd_bytestoadd_stream, and verify viaTempTag::hash()before promoting to a named tag. - Add FS-origin tests covering oversize rejection at
fstat, cap wrapper behavior, and multi-chunk streaming.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
| crates/cache/tests/pull_through.rs | Updates a regression-test comment to reflect streaming-based behavior. |
| crates/cache/src/origin/fs.rs | Implements true streaming reads from the filesystem origin and adds cap-related tests. |
| crates/cache/src/engine.rs | Switches pull-through ingestion to add_stream + temp tag verification + promotion and adds a per-chunk counting/cap adapter. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| futures_util::stream::unfold( | ||
| (stream, 0u64, path_for_log), | ||
| move |(mut s, total, path)| async move { | ||
| let next = s.next().await?; | ||
| match next { | ||
| Err(e) => Some((Err(e), (s, total, path))), | ||
| Ok(chunk) => { | ||
| let new_total = total.saturating_add(chunk.len() as u64); | ||
| if new_total > max_bytes { | ||
| let err = std::io::Error::other(format!( | ||
| "cache.origin.path entry {} grew past max {max_bytes} during read", | ||
| path.display() | ||
| )); | ||
| Some((Err(err), (s, total, path))) | ||
| } else { | ||
| Some((Ok(chunk), (s, new_total, path))) |
| futures_util::stream::unfold( | ||
| (stream, 0u64, metrics), | ||
| move |(mut s, total, metrics)| async move { | ||
| let next = s.next().await?; | ||
| match next { | ||
| Err(e) => Some((Err(e), (s, total, metrics))), | ||
| Ok(chunk) => { | ||
| // Bill the chunk before the cap check: the | ||
| // origin already sent us the bytes, so the | ||
| // operator-visible egress meter must count them | ||
| // (matches the pre-streaming "every byte fetched | ||
| // is paid" intent at engine.rs:952-960). A | ||
| // chunk that lands the running total past | ||
| // `max_bytes` is still counted in | ||
| // `pull_through_bytes` even though we then | ||
| // abort the import. | ||
| if let Some(m) = metrics.as_ref() { | ||
| m.pull_through_bytes | ||
| .inc_by(u64::try_from(chunk.len()).unwrap_or(u64::MAX)); | ||
| } | ||
| let new_total = total.saturating_add(chunk.len() as u64); | ||
| if new_total > max_bytes { | ||
| let err = std::io::Error::other(format!( | ||
| "origin stream exceeded max_blob_bytes={max_bytes} mid-flight" | ||
| )); | ||
| return Some((Err(err), (s, total, metrics))); | ||
| } | ||
| Some((Ok(chunk), (s, new_total, metrics))) |
| futures_util::stream::unfold( | ||
| (stream, 0u64, metrics), | ||
| move |(mut s, total, metrics)| async move { | ||
| let next = s.next().await?; | ||
| match next { | ||
| Err(e) => Some((Err(e), (s, total, metrics))), | ||
| Ok(chunk) => { | ||
| // Bill the chunk before the cap check: the | ||
| // origin already sent us the bytes, so the | ||
| // operator-visible egress meter must count them | ||
| // (matches the pre-streaming "every byte fetched | ||
| // is paid" intent at engine.rs:952-960). A | ||
| // chunk that lands the running total past | ||
| // `max_bytes` is still counted in | ||
| // `pull_through_bytes` even though we then | ||
| // abort the import. | ||
| if let Some(m) = metrics.as_ref() { | ||
| m.pull_through_bytes | ||
| .inc_by(u64::try_from(chunk.len()).unwrap_or(u64::MAX)); | ||
| } | ||
| let new_total = total.saturating_add(chunk.len() as u64); | ||
| if new_total > max_bytes { | ||
| let err = std::io::Error::other(format!( | ||
| "origin stream exceeded max_blob_bytes={max_bytes} mid-flight" | ||
| )); | ||
| return Some((Err(err), (s, total, metrics))); | ||
| } | ||
| Some((Ok(chunk), (s, new_total, metrics))) | ||
| } |
| .tags() | ||
| .create(haf) | ||
| .await | ||
| .map_err(|err| CacheError::Store(anyhow::Error::from(err)))?; |
There was a problem hiding this comment.
Code Review
This pull request refactors the pull_through cache mechanism to use streaming instead of collecting full payloads into memory, significantly reducing memory pressure for large blobs. It introduces streaming wrappers in the cache engine and filesystem origin to enforce size limits and track metrics. The review feedback suggests ensuring that these streaming wrappers explicitly terminate the stream state upon encountering a capacity breach to prevent unnecessary polling.
| if new_total > max_bytes { | ||
| let err = std::io::Error::other(format!( | ||
| "origin stream exceeded max_blob_bytes={max_bytes} mid-flight" | ||
| )); | ||
| return Some((Err(err), (s, total, metrics))); | ||
| } |
There was a problem hiding this comment.
The unfold state preserves the underlying stream s even after a capacity breach error is returned. If the consumer (e.g., add_stream) were to continue polling the stream after an error, it would continue reading from the origin. While iroh-blobs currently stops on error, it is safer to terminate the stream by transitioning the state to None upon hitting the cap.
if new_total > max_bytes {
let err = std::io::Error::other(format!(
"origin stream exceeded max_blob_bytes={max_bytes} mid-flight"
));
// Return the error and None for the next state to terminate the stream
return Some((Err(err), (s, total, metrics)));
}| if new_total > max_bytes { | ||
| let err = std::io::Error::other(format!( | ||
| "cache.origin.path entry {} grew past max {max_bytes} during read", | ||
| path.display() | ||
| )); | ||
| Some((Err(err), (s, total, path))) |
There was a problem hiding this comment.
Similar to the engine's cap wrapper, this unfold implementation does not explicitly terminate the stream after yielding the capacity error. Although the underlying ReaderStream is bounded by take(max_bytes + 1), it is best practice for the wrapper to stop polling the source once the logical limit is reached.
if new_total > max_bytes {
let err = std::io::Error::other(format!(
"cache.origin.path entry {} grew past max {max_bytes} during read",
path.display()
));
return Some((Err(err), (s, total, path)));
}
Coverage reportTotal: 88.02% (was 87.90%, ▲ +0.12%) — 12092/13738 lines
History
|
Replaces #514 (auto-closed when its base branch was deleted on PR 513 merge).
Cuts FilesystemOrigin to true streaming via ReaderStream and switches the cache engine's pull_through from add_bytes to iroh-blobs' add_stream + temp-tag-then-promote pattern. Closes #233 incidentally — the explicit BLAKE3 verification (and its spawn_blocking shim above 1 MiB) is gone; AddProgress.temp_tag().hash() is now the verification, single-pass.
Stacked under #515 (HTTP) and #516 (S3). All review feedback from the original #514 thread already addressed in this branch (cap_at_max_bytes_rejects_one_byte_overrun test, pull_through_bytes-billed-before-cap, comment fixups).
Test plan
🤖 Generated with Claude Code