Skip to content

refactor(cache): make Origin trait stream-shaped (#271 PR1/4) - #513

Merged
thiras merged 2 commits into
mainfrom
cozy-conway-issue-271-pr1
May 10, 2026
Merged

thiras merged 2 commits into
mainfrom
cozy-conway-issue-271-pr1

Conversation

@thiras

@thiras thiras commented May 10, 2026

Copy link
Copy Markdown
Contributor

Summary

PR 1 of 4 for issue #271 (cache: FilesystemOrigin.fetch reads the entire blob into memory before returning Bytes). Behavior-preserving trait shape change so PRs 2-4 can cut each backend over to true streaming without re-rolling the trait once per backend.

  • OriginFetch::Found(Bytes) → OriginFetch::Found { stream: OriginByteStream, size_hint: Option<u64> } where OriginByteStream = Pin<Box<dyn Stream<Item = io::Result<Bytes>> + Send + Sync + 'static>> — exactly the bound iroh_blobs::api::blobs::Blobs::add_stream requires.
  • All three backends and every test mock wrap their existing Bytes payload via the new OriginFetch::found_one_shot(bytes) constructor (single-chunk stream::once).
  • The engine's pull_through drains the stream via OriginFetch::collect_to_bytes before re-entering the existing size-cap → BLAKE3 → add_bytes path. PR 2 replaces that collect step with a tee'd add_stream and drops the explicit BLAKE3 verification.
  • New workspace deps: futures-util (already transitive via reqwest) and tokio-util (PR 2's ReaderStream source). Both MIT/Apache; cargo deny clean.

What this PR does NOT do

Test plan

  • cargo build — workspace builds clean
  • cargo clippy --workspace --all-targets — no new warnings
  • cargo nextest run -p decdn-cache — 139/139 pass
  • cargo nextest run — 678/678 pass
  • cargo fmt -- --check — clean
  • cargo deny check — advisories / bans / licenses / sources all OK
  • pre-commit run --all-files — all hooks pass

Closes part of #271. Follow-ups: PR 2 (FilesystemOrigin), PR 3 (HttpOrigin + async-compression), PR 4 (S3Origin).

🤖 Generated with Claude Code

Convert OriginFetch::Found(Bytes) to a streaming variant carrying a boxed
Stream<io::Result<Bytes>> + size_hint so the engine can pipe origin bytes
straight into iroh-blobs' add_stream in a follow-up. PR 1 is behavior-
preserving: every adapter still buffers the full payload and wraps it via
OriginFetch::found_one_shot, and the engine drains via collect_to_bytes
before re-entering the existing size-cap → BLAKE3 → add_bytes flow.

The new shape's bound (Send + Sync + 'static) is the one Blobs::add_stream
demands, so PR 2 (FilesystemOrigin streaming) can hand the stream straight
through without an adapter shim. PRs 2-4 cut each backend over to true
chunked streaming and replace the engine's collect step with a tee'd
add_stream + temp_tag-then-promote pattern.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 10, 2026 11:58

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

Refactors the decdn-cache origin fetch interface to be stream-shaped (in preparation for true streaming pull-through in follow-up PRs addressing #271), while keeping current backends behaviorally equivalent by wrapping existing buffered Bytes payloads into a single-chunk stream.

Changes:

  • Redefines OriginFetch::Found to carry { stream, size_hint } and introduces OriginByteStream, plus helpers found_one_shot and collect_to_bytes.
  • Updates cache engine + all origin backends and test mocks to use the new stream-shaped OriginFetch (via found_one_shot) and adapts tests to drain streams with collect_to_bytes.
  • Adds workspace dependencies futures-util and tokio-util to support streaming primitives and upcoming AsyncRead↔Stream<Bytes> bridges.

Reviewed changes

Copilot reviewed 11 out of 12 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
crates/node/src/metrics.rs Updates origin test mock to return the new stream-shaped OriginFetch via found_one_shot.
crates/node/src/admin.rs Updates admin test mocks to return stream-shaped OriginFetch via found_one_shot.
crates/cache/tests/s3_origin.rs Adapts S3 origin tests to consume OriginFetch via collect_to_bytes.
crates/cache/tests/pull_through.rs Updates pull-through test origins to return stream-shaped OriginFetch via found_one_shot.
crates/cache/src/origin/s3.rs Wraps buffered S3 payload in found_one_shot (PR-1 shim).
crates/cache/src/origin/mod.rs Introduces OriginByteStream, stream-shaped OriginFetch, and helper APIs (found_one_shot, collect_to_bytes).
crates/cache/src/origin/http.rs Wraps buffered HTTP payload in found_one_shot (PR-1 shim).
crates/cache/src/origin/fs.rs Wraps buffered filesystem payload in found_one_shot and updates tests to drain streams.
crates/cache/src/engine.rs Switches pull-through to drain OriginFetch via collect_to_bytes (transitional buffered path).
crates/cache/Cargo.toml Adds futures-util and tokio-util dependencies for streaming-related utilities.
Cargo.toml Adds workspace dependency entries for futures-util and tokio-util.
Cargo.lock Records dependency graph updates for the new crates.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +147 to +161
pub async fn collect_to_bytes(self) -> Result<Option<Bytes>, std::io::Error> {
use bytes::BytesMut;
use futures_util::StreamExt;
match self {
Self::NotFound => Ok(None),
Self::Found {
mut stream,
size_hint,
} => {
let cap = size_hint.and_then(|n| usize::try_from(n).ok()).unwrap_or(0);
let mut buf = BytesMut::with_capacity(cap);
while let Some(chunk) = stream.next().await {
buf.extend_from_slice(&chunk?);
}
Ok(Some(buf.freeze()))
Comment thread crates/cache/src/origin/mod.rs Outdated
Comment on lines +100 to +103
/// Best-effort upfront size estimate from the adapter. Used by
/// the engine for short-circuit cap checks before reading the
/// first byte; the engine still re-checks the running total as
/// chunks arrive.
Comment thread crates/cache/src/origin/mod.rs Outdated
Comment on lines +36 to +40
/// Errors flow as `io::Error` so the engine can collapse mid-stream
/// failures into [`OriginPullError::Permanent`] without re-classifying
/// every adapter's native error type. Headers-phase classification stays
/// in each adapter (transient vs permanent) and is emitted before the
/// stream is constructed.

@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 introduces streaming primitives for origin pull-through by transitioning the OriginFetch result from a fully buffered Bytes payload to a chunked OriginByteStream. It adds futures-util and tokio-util dependencies and implements transitional shims across the filesystem, HTTP, and S3 origin backends to maintain compatibility while the engine is updated. Feedback includes a recommendation to cap initial buffer allocations to prevent memory exhaustion from large size hints and corrections for direct indexing violations that conflict with the project's anti-panic policies.

Comment thread crates/cache/src/origin/mod.rs Outdated
Comment on lines +156 to +157
let cap = size_hint.and_then(|n| usize::try_from(n).ok()).unwrap_or(0);
let mut buf = BytesMut::with_capacity(cap);

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 size_hint is used directly for the initial allocation of BytesMut. If an origin provides an excessive hint (e.g., via a large Content-Length header), this could lead to memory exhaustion or a panic during allocation. It is safer to cap the initial capacity and let the buffer grow as needed, similar to the implementation in HttpOrigin.

Suggested change
let cap = size_hint.and_then(|n| usize::try_from(n).ok()).unwrap_or(0);
let mut buf = BytesMut::with_capacity(cap);
let cap = size_hint.and_then(|n| usize::try_from(n).ok()).unwrap_or(0);
let mut buf = BytesMut::with_capacity(cap.min(1024 * 1024));
References
  1. When implementing origin fetch logic, prefer streaming the response body with a running size cap instead of buffering the entire payload into memory to prevent Out-Of-Memory (OOM) conditions, especially for chunked responses that may omit a Content-Length header.
  2. When reading files with a maximum size limit, bound the read operation at the I/O layer using file.take(max_bytes.saturating_add(1)) to prevent Time-of-Check to Time-of-Use (TOCTOU) vulnerabilities if the file grows mid-read. Additionally, cap the initial Vec::with_capacity allocation hint to a reasonable constant (e.g., 1 MiB) to avoid large up-front memory commitments for potentially very large files, while still allowing the buffer to grow as needed.
  3. Avoid panics when converting file sizes (u64) to usize for Vec::with_capacity. Use usize::try_from to handle potential overflows gracefully as a typed error, especially on systems with smaller address spaces or when max_bytes is very large.

.collect_to_bytes()
.await?
.ok_or_else(|| anyhow::anyhow!("expected Found, got NotFound"))?;
anyhow::ensure!(&bytes[..] == payload, "got: {bytes:?}");

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

Direct indexing with [..] is denied by the workspace's clippy::indexing_slicing policy and violates the project's anti-panic rules. Since Bytes implements PartialEq<[u8]>, you can compare them directly without slicing.

Suggested change
anyhow::ensure!(&bytes[..] == payload, "got: {bytes:?}");
anyhow::ensure!(bytes == payload, "got: {bytes:?}");
References
  1. To comply with the anti-panic policy which denies clippy::indexing_slicing, use .get() with unwrap_or or other safe methods for slicing instead of direct indexing ([]).

.collect_to_bytes()
.await?
.ok_or_else(|| anyhow::anyhow!("expected Found"))?;
anyhow::ensure!(&bytes[..] == payload);

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

Direct indexing with [..] is denied by the workspace's clippy::indexing_slicing policy and violates the project's anti-panic rules. Since Bytes implements PartialEq<[u8]>, you can compare them directly without slicing.

Suggested change
anyhow::ensure!(&bytes[..] == payload);
anyhow::ensure!(bytes == payload);
References
  1. To comply with the anti-panic policy which denies clippy::indexing_slicing, use .get() with unwrap_or or other safe methods for slicing instead of direct indexing ([]).

.collect_to_bytes()
.await?
.ok_or_else(|| anyhow::anyhow!("expected Found"))?;
anyhow::ensure!(&bytes[..] == payload);

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

Direct indexing with [..] is denied by the workspace's clippy::indexing_slicing policy and violates the project's anti-panic rules. Since Bytes implements PartialEq<[u8]>, you can compare them directly without slicing.

Suggested change
anyhow::ensure!(&bytes[..] == payload);
anyhow::ensure!(bytes == payload);
References
  1. To comply with the anti-panic policy which denies clippy::indexing_slicing, use .get() with unwrap_or or other safe methods for slicing instead of direct indexing ([]).

@github-actions

github-actions Bot commented May 10, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 87.83% (was 87.90%, ▼ 0.07%) — 11963/13621 lines

File Coverage Lines Δ
crates/cache/src/engine.rs 91.02% 1004/1103 ▼ 0.50%
crates/cache/src/origin/fs.rs 73.21% 164/224 ▼ 0.47%
crates/cache/src/origin/http.rs 87.66% 334/381 ● 0.00%
crates/cache/src/origin/mod.rs 87.69% 57/65 ▼ 12.31%
crates/cache/src/origin/s3.rs 90.16% 339/376 ● 0.00%
crates/node/src/admin.rs 95.84% 622/649 ● 0.00%
crates/node/src/metrics.rs 60.79% 169/278 ● 0.00%
History
Commit Total Δ vs base
b26529e 87.82% ▼ 0.08%
6dd0ad9 (HEAD) 87.83% ▼ 0.07%

Addressing review feedback on #513:

- `OriginFetch::collect_to_bytes`: cap the upfront `BytesMut::with_capacity`
  hint at 1 MiB regardless of `size_hint`. A hostile origin advertising
  `Content-Length: 10 TiB` would otherwise trigger a huge alloc before
  any byte of the body arrives. The buffer still grows incrementally
  past the cap; engine's running cap on streamed bytes catches the
  actual overrun. Mirrors the pre-existing `INITIAL_READ_CAP_HINT` from
  `FilesystemOrigin`.

- `OriginByteStream` doc: clarify that `io::Error` stream items do NOT
  feed `retry_fetch`'s transient/permanent classification — retry runs
  around `fetch`, so post-fetch stream errors surface via
  `CacheError::OriginError` without retry. (Copilot caught a stale
  description that suggested otherwise.)

- `OriginFetch::Found` doc: spell out that PR 1 still drains the stream
  via `collect_to_bytes` before re-entering the buffered `add_bytes`
  path; memory savings only land in PR 2 onward. The `size_hint`
  short-circuit is also a PR 2 feature.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@thiras

thiras commented May 10, 2026

Copy link
Copy Markdown
Contributor Author

Triaged review feedback. Pushed 6dd0ad9 addressing the actionable items:

Implemented:

  • size_hint DoS in collect_to_bytes (Gemini, Copilot): cap BytesMut::with_capacity at 1 MiB regardless of size_hint so a hostile origin advertising Content-Length: 10 TiB can't trigger a huge alloc up front. Buffer still grows incrementally past the cap; engine's running cap (PR 2) catches the actual overrun.
  • OriginByteStream doc (Copilot): clarified that io::Error stream items don't feed retry_fetch's transient/permanent classification — retry runs around fetch, so post-fetch stream errors surface via CacheError::OriginError without retry.
  • OriginFetch::Found doc (Copilot): spelled out that PR 1 still drains via collect_to_bytes; memory savings only land in PR 2 onward. The size_hint short-circuit is also a PR 2 feature.

Pushed back on:

  • [..] indexing in s3 tests (Gemini, 3 instances): &bytes[..] goes through Bytes::Index<RangeFull> and isn't tripping clippy::indexing_slicing (cargo clippy --workspace --all-targets passes). Workspace lint is deny but this specific shape doesn't hit it.

Did not change:

  • collect_to_bytes extra-alloc/memcpy regression (Copilot): valid concern in absolute terms — the PR-1 transitional path does pay one extra BytesMut alloc + memcpy versus the pre-PR-1 zero-copy Bytes::Found. The cost is bounded by the new initial-allocation cap and is gone the moment PR 2 lands (the engine then pipes the stream straight into add_stream without collecting). Accepting it as the cost of a behavior-preserving trait migration.

@thiras
thiras merged commit c75ee78 into main May 10, 2026
12 checks passed
@thiras
thiras deleted the cozy-conway-issue-271-pr1 branch May 10, 2026 14:00
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