Skip to content

feat(cache): stream FilesystemOrigin + engine.add_stream (#271 PR2/4) - #517

Merged
thiras merged 1 commit into
mainfrom
cozy-conway-issue-271-pr2
May 10, 2026
Merged

thiras merged 1 commit into
mainfrom
cozy-conway-issue-271-pr2

Conversation

@thiras

@thiras thiras commented May 10, 2026

Copy link
Copy Markdown
Contributor

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

  • cargo build --workspace clean
  • cargo nextest run -p decdn-cache: 142/142 pass
  • cargo clippy / fmt / deny / pre-commit clean

🤖 Generated with Claude Code

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]>
Copilot AI review requested due to automatic review settings May 10, 2026 14:02
@thiras
thiras merged commit 55cb245 into main May 10, 2026
4 checks passed
@thiras
thiras deleted the cozy-conway-issue-271-pr2 branch May 10, 2026 14:02

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 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::ReaderStream with an I/O-layer cap (take(max+1)) plus a running-cap wrapper.
  • Change CacheEngine::pull_through from add_bytes to add_stream, and verify via TempTag::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.

Comment on lines +245 to +260
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)))
Comment on lines +1045 to +1072
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)))
Comment on lines +1045 to +1073
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)))?;

@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 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.

Comment on lines +1066 to +1071
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)));
}

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 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)));
                    }

Comment on lines +253 to +258
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)))

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

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)));
                    }

@github-actions

Copy link
Copy Markdown

Coverage report

Total: 88.02% (was 87.90%, ▲ +0.12%) — 12092/13738 lines

File Coverage Lines Δ
crates/cache/src/engine.rs 92.13% 1030/1118 ▲ +0.61%
crates/cache/src/origin/fs.rs 82.21% 268/326 ▲ +8.52%
History
Commit Total Δ vs base
ed4d321 (HEAD) 88.02% ▲ +0.12%

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: drop double BLAKE3 hash once iroh-blobs exposes verified-insert

2 participants