Skip to content

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

Closed
thiras wants to merge 1 commit into
cozy-conway-issue-271-pr1from
cozy-conway-issue-271-pr2
Closed

thiras wants to merge 1 commit into
cozy-conway-issue-271-pr1from
cozy-conway-issue-271-pr2

Conversation

@thiras

@thiras thiras commented May 10, 2026

Copy link
Copy Markdown
Contributor

Summary

PR 2 of 4 for issue #271. Stacked on #513 (PR 1).

  • FilesystemOrigin::fetch now streams via tokio_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_through switches from Blobs::add_bytes to Blobs::add_stream + temp_tag().await + post-hoc tags().create(). The TempTag::hash() is now the BLAKE3 verification; the explicit Hash::new(&bytes) and its spawn_blocking shim above 1 MiB are gone. Closes cache: drop double BLAKE3 hash once iroh-blobs exposes verified-insert #233.
  • A new count_and_cap_stream adapter increments pull_through_bytes per chunk and aborts the import if cumulative bytes exceed max_blob_bytes mid-flight (origin can lie in Content-Length).

Streaming end-to-end achieved for the FS backend

FilesystemOrigin::fetch → ReaderStream → cap_at_max_bytes
  → count_and_cap_stream → iroh_blobs::Blobs::add_stream → store

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_shot shim) and route through the same engine, so this PR alone fully fixes the bug for FilesystemOrigin.

Known regression to flag

Hash mismatch behavior differs:

  • Before: the wrong bytes were never written to the iroh-blobs store (we hashed first, compared, then add_bytes only on match).
  • After: the wrong bytes briefly land in the store unprotected. Dropping the TempTag without naming it makes them GC-eligible, but Blobs::has(actual_hash) can return true for a window bounded by iroh-blobs' GC cadence. A malicious origin returning bytes hashing to X when asked for Y could cache-poison X for 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_cached test still passes (it asserts !has(expected), which is the operator-visible behavior).

What this PR does NOT do

Test plan

  • cargo build --workspace — clean
  • cargo clippy --workspace --all-targets — no new warnings
  • cargo nextest run -p decdn-cache — 141/141 pass (2 new FS tests: multi-chunk streaming, oversize cap mid-stream)
  • 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
  • Verified the existing hash_mismatch_is_rejected_and_not_cached test still asserts the right operator-visible behavior

🤖 Generated with Claude Code

Copilot AI review requested due to automatic review settings May 10, 2026 12:09

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

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.

Comment on lines +1051 to +1064
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)))
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

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 requires the stream to be Sync, this will cause a compilation error when the stream is boxed and pinned at line 217.

Comment thread crates/cache/src/origin/fs.rs Outdated
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;

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

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 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::fetch via tokio_util::io::ReaderStream + a running cap adapter.
  • Update CacheEngine::pull_through to ingest via add_stream, verify via TempTag::hash(), then promote via tags().create().
  • Add a count_and_cap_stream adapter to track pull_through_bytes per chunk and enforce max_blob_bytes mid-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.

Comment on lines +252 to +258
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)))
Comment thread crates/cache/src/origin/fs.rs Outdated
Comment on lines +427 to +431
// 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
Comment thread crates/cache/src/origin/fs.rs Outdated
Comment on lines +443 to +449
// 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
Comment on lines +1046 to +1063
(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]>
@thiras
thiras force-pushed the cozy-conway-issue-271-pr2 branch from 9c7a057 to 2464211 Compare May 10, 2026 13:18
@thiras

thiras commented May 10, 2026

Copy link
Copy Markdown
Contributor Author

Force-pushed 2464211 (rebased on the updated PR 1 + review fixups).

Implemented:

  • pull_through_bytes not counted on cap-breach chunk (Gemini, HIGH): moved the metric increment to before the cap check. The chunk that lands the running total past max_bytes is now billed even though we then abort the import — matches the pre-streaming "every byte fetched is paid" intent at engine.rs:952-960.
  • fetch_stream_caps_when_file_exceeds_max_bytes test was misleading (Gemini MEDIUM, Copilot): split into two tests:
    • fetch_rejects_oversize_file_at_fstat_prologue — confirms the prologue rejects (fast path).
    • cap_at_max_bytes_rejects_one_byte_overrun — drives cap_at_max_bytes directly with a synthetic upstream that produces max_bytes + 1 bytes (same chunk shape ReaderStream::new(file.take(max_bytes + 1)) produces for a grew-during-read file). This actually exercises the running-cap path the original test claimed to cover.

Pushed back on:

  • Gemini HIGH "Sync bound on stream::unfold async block not satisfied" (twice): the code compiles clean against iroh_blobs::api::blobs::Blobs::add_stream(impl Stream<…> + Send + Sync + 'static). Async-block unfold is Sync when its captured state is Sync, which all three captures here are (Option<S>, u64, Option<Arc<CacheMetrics>>). The static analysis flagged a hypothetical that the type system already disproves.
  • Copilot "stream not fused after error" in cap_at_max_bytes and count_and_cap_stream: real contract violation in PR 2 standalone, but the actual consumers (add_stream's ? on Err, collect_to_bytes on first Err) never re-poll — so it's latent. PR 3 hardens with the Option<S> sentinel where a real hang motivated the change. Skipping in PR 2 to keep the diff focused on the FS streaming + engine add_stream cut-over.

@thiras
thiras deleted the branch cozy-conway-issue-271-pr1 May 10, 2026 14:00
@thiras thiras closed this May 10, 2026
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.

2 participants