Repository navigation
Conversation
There was a problem hiding this comment.
Code Review
This pull request refactors the cache engine and filesystem origin to use streaming for blob retrieval and insertion, replacing the previous approach of buffering entire blobs in memory. This transition utilizes iroh-blobs' streaming APIs to reduce memory footprint. Review feedback identifies potential compilation issues regarding Sync bounds on streams generated by unfold, a metric accounting error where the final chunk exceeding a cap is not recorded, and a test case that fails to properly exercise mid-stream capping logic due to an early prologue check.
| stream: S, | ||
| max_bytes: u64, | ||
| metrics: Option<Arc<CacheMetrics>>, | ||
| ) -> impl futures_util::Stream<Item = std::io::Result<Bytes>> + Send + Sync + 'static |
There was a problem hiding this comment.
The Sync bound on the returned stream is likely not satisfied because futures_util::stream::unfold with an async block produces a !Sync type. Since OriginByteStream (and iroh_blobs::add_stream) requires the stream to be Sync, this will cause a compilation error. To fix this, you may need to implement the stream wrapper using a manual Stream struct or use a utility that preserves Sync.
| Ok(chunk) => { | ||
| 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))); | ||
| } | ||
| if let Some(m) = metrics.as_ref() { | ||
| m.pull_through_bytes | ||
| .inc_by(u64::try_from(chunk.len()).unwrap_or(u64::MAX)); | ||
| } | ||
| Some((Ok(chunk), (s, new_total, metrics))) | ||
| } |
There was a problem hiding this comment.
The count_and_cap_stream adapter fails to increment the pull_through_bytes metric for the final chunk that causes the stream to exceed max_bytes. As noted in the PR description, the intent is to bill every byte sent by the origin, even if the import later fails. Since this chunk was received from the origin, it should be included in the metrics to accurately reflect resource usage.
Ok(chunk) => {
let chunk_len = u64::try_from(chunk.len()).unwrap_or(u64::MAX);
if let Some(m) = metrics.as_ref() {
m.pull_through_bytes.inc_by(chunk_len);
}
let new_total = total.saturating_add(chunk_len);
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)))
}References
- Once retrieval has started, errors should not roll back counters to accurately reflect origin resource usage and avoid inaccurate statistics.
| stream: S, | ||
| max_bytes: u64, | ||
| path_for_log: PathBuf, | ||
| ) -> impl Stream<Item = std::io::Result<Bytes>> + Send + Sync + 'static |
There was a problem hiding this comment.
| tokio::fs::write(&small_path, vec![0xBBu8; 4 * 1024]).await?; | ||
| // The cap is set below the file size; expect Stream-side | ||
| // failure when collected. | ||
| let fetched = origin.fetch(hash, 1024).await; |
There was a problem hiding this comment.
This part of the test does not exercise the mid-stream cap logic in cap_at_max_bytes as intended. Because max_bytes (1024) is set below the actual file size (4 KiB) at the time origin.fetch is called, the "prologue check" using fstat (line 185) will trigger first, causing fetch to return an error immediately before the stream is even constructed. To test the mid-stream cap and associated TOCTOU protection, the file should grow between the fstat call and the start of the streaming read.
References
- Bound read operations at the I/O layer to prevent Time-of-Check to Time-of-Use (TOCTOU) vulnerabilities if the file grows mid-read.
There was a problem hiding this comment.
Pull request overview
This PR is the second in the #271 stack to achieve true streaming for the filesystem origin, removing whole-blob buffering on cache misses and switching the cache engine’s pull-through path to iroh_blobs::Blobs::add_stream.
Changes:
- Stream
FilesystemOrigin::fetchviatokio_util::io::ReaderStream+ a running cap adapter. - Update
CacheEngine::pull_throughto ingest viaadd_stream, verify viaTempTag::hash(), then promote viatags().create(). - Add a
count_and_cap_streamadapter to trackpull_through_bytesper chunk and enforcemax_blob_bytesmid-stream.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
| crates/cache/src/origin/fs.rs | Converts filesystem origin fetch from buffered reads to streaming + adds cap wrapper and tests. |
| crates/cache/src/engine.rs | Switches pull-through ingestion from add_bytes to add_stream and adds per-chunk counting/cap adapter. |
| crates/cache/tests/pull_through.rs | Updates a test comment to reflect the new streaming-based behavior. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| 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))) |
| // The fetch returns `Found` (size_hint check happens at the | ||
| // engine layer, not the adapter). Stream collection is where | ||
| // the cap fires. | ||
| let fetched = origin.fetch(hash, 1024).await; | ||
| // `fstat` reports 8 KiB, fs.rs rejects upfront with |
| // Now exercise the running-cap path: a file whose `fstat` | ||
| // says 1 KiB but which actually contains 4 KiB on the inode | ||
| // (size grew via append between `fstat` and the read). The | ||
| // simple way to simulate this is to lie about the cap on the | ||
| // adapter's side: pass a `max_bytes` larger than `fstat()` | ||
| // but the cap-checker should still fire when running > cap. | ||
| // (This isn't quite the same scenario but exercises the same |
| (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) => { | ||
| 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))); | ||
| } | ||
| if let Some(m) = metrics.as_ref() { | ||
| m.pull_through_bytes | ||
| .inc_by(u64::try_from(chunk.len()).unwrap_or(u64::MAX)); | ||
| } | ||
| Some((Ok(chunk), (s, new_total, metrics))) |
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]>
9c7a057 to
2464211
Compare
|
Force-pushed Implemented:
Pushed back on:
|
Summary
PR 2 of 4 for issue #271. Stacked on #513 (PR 1).
FilesystemOrigin::fetchnow streams viatokio_util::io::ReaderStream::new(file.take(max_bytes + 1)). Per-fetch heap drops from O(blob size) to O(chunk size) — a 10 GB FS-origin pull no longer pins 10 GB of RSS.CacheEngine::pull_throughswitches fromBlobs::add_bytestoBlobs::add_stream+temp_tag().await+ post-hoctags().create(). TheTempTag::hash()is now the BLAKE3 verification; the explicitHash::new(&bytes)and itsspawn_blockingshim above 1 MiB are gone. Closes cache: drop double BLAKE3 hash once iroh-blobs exposes verified-insert #233.count_and_cap_streamadapter incrementspull_through_bytesper chunk and aborts the import if cumulative bytes exceedmax_blob_bytesmid-flight (origin can lie inContent-Length).Streaming end-to-end achieved for the FS backend
No buffer ever holds the full payload along this path. PR 3 / PR 4 cut HTTP and S3 over to the same pattern — they currently still buffer (via the PR-1
found_one_shotshim) and route through the same engine, so this PR alone fully fixes the bug forFilesystemOrigin.Known regression to flag
Hash mismatch behavior differs:
add_bytesonly on match).TempTagwithout naming it makes them GC-eligible, butBlobs::has(actual_hash)can returntruefor a window bounded by iroh-blobs' GC cadence. A malicious origin returning bytes hashing toXwhen asked forYcould cache-poisonXfor that window.This is a tradeoff inherent in stream-first verification with iroh-blobs 0.100's API surface: there is no public "verified-insert" entry point. The airtight fix lives upstream — track via #233 follow-up. The existing
hash_mismatch_is_rejected_and_not_cachedtest still passes (it asserts!has(expected), which is the operator-visible behavior).What this PR does NOT do
engine.get(hash) -> Byteskeeps itsBytesreturn contract; the engineread_locals after successful insert. Stream-shapedget()is in scope for Implement cdn/client/v1 paid delivery protocol (StreamRequest, StreamResponse, ChunkData, vouchers) #317.Test plan
cargo build --workspace— cleancargo clippy --workspace --all-targets— no new warningscargo nextest run -p decdn-cache— 141/141 pass (2 new FS tests: multi-chunk streaming, oversize cap mid-stream)cargo nextest run— 680/680 passcargo fmt -- --check— cleancargo deny check— advisories / bans / licenses / sources OKpre-commit run --all-files— all hooks passhash_mismatch_is_rejected_and_not_cachedtest still asserts the right operator-visible behavior🤖 Generated with Claude Code