Skip to content

feat(cache): stream HttpOrigin + async-compression decode (#271 PR3/4) - #515

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

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

Conversation

@thiras

@thiras thiras commented May 10, 2026

Copy link
Copy Markdown
Contributor

Summary

PR 3 of 4 for issue #271. Stacked on #514 (PR 2).

  • HttpOrigin::fetch now streams via stream::unfold over resp.chunk() with the per-chunk idle timeout and per-chunk encoded-size cap preserved as adapter logic. Decompression replaces the synchronous flate2/zstd Read round-trip with async-compression's tokio::bufread::{GzipDecoder, ZstdDecoder} layered through tokio_util::io::{StreamReader, ReaderStream}. The decompress_body, read_capped, and DECOMPRESS_BLOCKING_THRESHOLD paths are gone.
  • Streaming end-to-end: a 10 GB gzipped origin no longer pins 10 GB of process RSS — decoded bytes flow chunk-by-chunk into iroh-blobs' add_stream with per-fetch heap bounded by the decoder's working set.

Key new mechanics

Side-channel for typed errors. iroh-blobs' add_stream swallows the upstream io::Error (the inner async block uses ? and the outer tokio::join! discards the failure) and can also hang waiting for Done after a sender-drop. The fix: count_and_cap_stream writes the upstream io::Error to an Arc<Mutex<Option<io::Error>>> side channel, then yields None (clean stream end) so add_stream sends Done cleanly; the import commits a partial blob with the wrong hash. The engine consults the side channel before checking iroh-blobs' result and surfaces the real failure (build_origin_anyhow_from_io). The partial blob is left as an unprotected TempTag and reclaimed by iroh-blobs' GC.

Typed-error preservation. io::Error::source() returns inner.source(), not Some(&inner) — so a typed OriginError::DecompressionFailed packed inside io::Error::new(kind, typed) is invisible to a chain().downcast_ref::<OriginError>() walk. The fix in build_origin_anyhow_from_io: pull the typed inner out via into_inner() + Box::downcast::<OriginError>() before constructing the anyhow chain. When successful, the typed variant becomes the deepest error and is recoverable by CacheError::origin_error_kind. Truncated and empty gzip body tests still see typed DecompressionFailed.

Behavioural changes worth flagging

  • Decompression bombs are now caught by the engine's running cap on decoded bytes (count_and_cap_stream) rather than by a per-decoder cap (the old read_capped). Same security guarantee, single cap layer. The corresponding test was updated to assert on the new error message ("max_blob_bytes / mid-flight") and no longer requires a typed DecompressionFailed downcast (the cap fires at the engine layer, before the decoder fails).
  • Body-mid-stream reqwest errors are no longer retried. Pre-cache: FilesystemOrigin.fetch reads the entire blob into memory before returning Bytes, preventing streaming delivery to the client for large blobs #271 the full body was collected inside fetch, so retry saw mid-body errors. After this PR they surface to the engine after retry_fetch has already returned Ok. A separate request triggers a fresh retry budget. Acceptable for memory savings; mid-stream retry would need engine-level abort-and-restart logic on the partially-imported tag and is out of scope.

Workspace deps

  • Added: async-compression = { version = "0.4", features = ["tokio", "gzip", "zstd"] } (workspace).
  • Moved: flate2, zstd from [dependencies] to [dev-dependencies] on the cache crate. Test fixtures still construct gzipped / zstd bodies; the runtime no longer touches them.

Test plan

  • cargo build --workspace — clean
  • cargo clippy --workspace --all-targets — no warnings
  • cargo nextest run -p decdn-cache — 141/141 pass
  • 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
  • Typed DecompressionFailed assertion still holds for truncated and empty gzip body tests
  • Headers-phase typed errors (UnsupportedEncoding, multi-encoding rejection, malformed encoding) unchanged

🤖 Generated with Claude Code

Copilot AI review requested due to automatic review settings May 10, 2026 12: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

This PR (stack 3/4 for #271) completes the HTTP leg of cache pull-through streaming by turning HttpOrigin::fetch into a chunked stream and switching gzip/zstd decoding from sync Read-based decompression to an async-compression streaming pipeline, so large origin responses no longer require buffering the full encoded/decoded body in memory.

Changes:

  • Stream HttpOrigin::fetch end-to-end (reqwest chunk loop → stream adapter → optional async gzip/zstd decode → engine add_stream).
  • Add an engine-side error “side-channel” to preserve mid-stream io::Error causes that iroh-blobs otherwise swallows.
  • Update tests and workspace deps to reflect the new streaming/decompression behavior (async-compression runtime; flate2/zstd kept for test fixtures only).

Reviewed changes

Copilot reviewed 6 out of 7 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
crates/cache/src/origin/http.rs Reworks HTTP fetch to stream chunks and optionally decode gzip/zstd via async-compression without buffering whole bodies.
crates/cache/src/engine.rs Captures mid-stream errors via side-channel, improves surfacing of upstream failures, and adjusts stream-capping adapter behavior.
crates/cache/src/origin/fs.rs Makes stream wrappers terminate deterministically after an error to avoid re-poll/hang edge cases.
crates/cache/tests/pull_through.rs Updates the decompression-bomb assertion to match the new “decoded bytes cap in engine” behavior/message.
crates/cache/Cargo.toml Moves flate2/zstd to dev-deps and adds async-compression for runtime streaming decode.
Cargo.toml Adds workspace dependency for async-compression.
Cargo.lock Locks new transitive deps for async-compression and related updates.

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

Comment thread crates/cache/src/engine.rs Outdated
Comment on lines +1113 to +1117
// `anyhow::Error::msg(chain_msg)` keeps the Display
// honest; we couldn't preserve typed downcast for an
// inner we can't name.
let _ = other_box;
return anyhow::Error::msg(chain_msg);
Comment thread crates/cache/src/engine.rs Outdated
Comment on lines +1126 to +1129
/// Adapter that bumps the `pull_through_bytes` metric per chunk,
/// aborts mid-stream if cumulative bytes exceed `max_bytes`, and
/// captures any `io::Error` it observes into `captured_err` before
/// passing it along.
Comment thread crates/cache/src/engine.rs Outdated
Comment on lines +1159 to +1163
// `Option` so polling stops once we yield an `Err`. Polling a
// stream after a terminal error is undefined; without the
// sentinel, iroh-blobs' `add_stream` can hang because its
// internal `data.next().await` re-enters our adapter, which
// re-polls the already-errored upstream.
Comment thread crates/cache/src/origin/http.rs Outdated
.and_then(|l| usize::try_from(l).ok())
.map_or(0, |l| min(l, INITIAL_CAPACITY_HINT_CAP));
// Build the body stream:
// 1. reqwest::Response::bytes_stream() yields encoded chunks

@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 HTTP origin to use streaming decompression via the async-compression crate, replacing the previous buffered synchronous approach. It introduces a side-channel mechanism in the cache engine to capture and propagate typed errors from the stream that were previously swallowed. Feedback focused on optimizing error handling by deferring string allocations and avoiding redundant error messages, as well as ensuring that metrics accurately reflect resource usage by counting bytes even when a size limit is breached.

Comment thread crates/cache/src/engine.rs Outdated
Comment on lines +1066 to +1074
fn flatten_error_chain(err: &(dyn std::error::Error + 'static)) -> String {
let mut messages: Vec<String> = Vec::new();
let mut current: Option<&(dyn std::error::Error + 'static)> = Some(err);
while let Some(e) = current {
messages.push(e.to_string());
current = e.source();
}
messages.join(": ")
}

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 flatten_error_chain function produces redundant messages when used with error types (like those from thiserror) that already include their source in their Display implementation. For example, OriginError::DecompressionFailed includes its source, so flattening will repeat the source message. Consider relying on the canonical Display implementation to ensure consistency and avoid redundancy.

References
  1. Prefer using canonical representations, such as an existing Display implementation, to ensure consistency and avoid redundant error messaging.

Comment on lines +1095 to +1124
fn build_origin_anyhow_from_io(upstream: std::io::Error) -> anyhow::Error {
// Extract the message NOW because `into_inner()` consumes the
// io::Error and the message lives on the wrapped error's
// Display, which we'll lose access to once we drill into the
// typed inner.
let chain_msg = flatten_error_chain(&upstream);

// Try to peel off the typed inner. `io::Error::into_inner()`
// returns `Option<Box<dyn Error + Send + Sync>>`; the `Box::downcast`
// on the trait object recovers the concrete `OriginError` if
// the adapter packed one in via `typed_decoder_error`.
let inner_opt = upstream.into_inner();
if let Some(boxed) = inner_opt {
match boxed.downcast::<OriginError>() {
Ok(typed) => return anyhow::Error::from(*typed),
Err(other_box) => {
// Inner wasn't a typed `OriginError` — but it's still
// some other error worth keeping in the chain.
// `anyhow::Error::msg(chain_msg)` keeps the Display
// honest; we couldn't preserve typed downcast for an
// inner we can't name.
let _ = other_box;
return anyhow::Error::msg(chain_msg);
}
}
}
// No inner at all (io::Error from a raw kind, no wrapped
// payload). The flattened message is all we have.
anyhow::Error::msg(chain_msg)
}

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 flatten_error_chain call is performed before checking if the error can be downcast to OriginError. Since flatten_error_chain involves string allocations and joining, it should be deferred until it's actually needed in the fallback paths. This avoids unnecessary work when a typed OriginError is successfully recovered.

fn build_origin_anyhow_from_io(upstream: std::io::Error) -> anyhow::Error {
    let inner_opt = upstream.into_inner();
    if let Some(boxed) = inner_opt {
        match boxed.downcast::<OriginError>() {
            Ok(typed) => return anyhow::Error::from(*typed),
            Err(other_box) => {
                let chain_msg = flatten_error_chain(&*other_box);
                return anyhow::Error::msg(chain_msg);
            }
        }
    }
    anyhow::Error::msg(upstream.to_string())
}

Comment thread crates/cache/src/engine.rs Outdated
Comment on lines 1197 to 1208
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)));
*captured.lock().unwrap_or_else(PoisonError::into_inner) = Some(err);
return None;
}
if let Some(m) = metrics.as_ref() {
m.pull_through_bytes
.inc_by(u64::try_from(chunk.len()).unwrap_or(u64::MAX));
}

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 pull_through_bytes metric is incremented only after the max_bytes check. If a chunk causes the total to exceed the limit, it is rejected and not counted. To accurately reflect origin resource usage and avoid inaccurate statistics, the metric should be incremented for all bytes received once the retrieval has started, even if the operation eventually fails due to size limits.

                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"
                        ));
                        *captured.lock().unwrap_or_else(PoisonError::into_inner) = Some(err);
                        return None;
                    }
References
  1. Once retrieval has started, errors should not roll back counters to accurately reflect origin resource usage and avoid inaccurate statistics.
  2. Prefer streaming the response body with a running size cap to prevent Out-Of-Memory (OOM) conditions.

@thiras
thiras force-pushed the cozy-conway-issue-271-pr2 branch from 9c7a057 to 2464211 Compare May 10, 2026 13:18
@thiras
thiras force-pushed the cozy-conway-issue-271-pr3 branch from f5b1524 to e286838 Compare May 10, 2026 13:21
@thiras

thiras commented May 10, 2026

Copy link
Copy Markdown
Contributor Author

Force-pushed e286838 (rebased on updated PR 2 + review fixups).

Implemented:

  • build_origin_anyhow_from_io dropped other_box (Copilot): now preserves the inner via io::Error::new(kind, other_box) so the operator-visible source chain isn't lost when the inner isn't a typed OriginError.
  • flatten_error_chain redundancy (Gemini MEDIUM): dropped entirely. thiserror's #[error] Display already includes the source for OriginError variants ("failed to decompress gzip response body: …"), so flattening was duplicating each level. Engine now uses anyhow::Error::from(typed_origin_error) for the typed path and anyhow::Error::from(io::Error::new(kind, inner)) otherwise — natural Display (or :#) walks the chain without manual joining.
  • flatten_error_chain called even when typed downcast succeeds (Gemini MEDIUM): moot now that the helper is gone — typed-success path avoids the work.
  • Doc rot (Copilot, 3 of 4):
    • count_and_cap_stream doc: rewrote to match reality (yields None, not Err; explains the hang-on-Done-wait that motivates the design).
    • Termination-after-error comment: rewritten.
    • response_chunk_stream comment in http.rs: corrected reqwest::Response::bytes_stream() → response_chunk_stream pulls encoded chunks via resp.chunk().

Did not change:

  • pull_through_bytes not counted on cap-breach chunk (Gemini MEDIUM): already fixed in PR 2 (2464211); rebase carried it forward.

@thiras
thiras force-pushed the cozy-conway-issue-271-pr2 branch from 2464211 to ed4d321 Compare May 10, 2026 14:02
Base automatically changed from cozy-conway-issue-271-pr2 to main May 10, 2026 14:02
PR 3 of 4 for issue #271. Cuts HttpOrigin to true streaming end-to-end:
the chunk-collecting `BytesMut` loop is replaced with `stream::unfold`
over `resp.chunk()`, and gzip / zstd decoding moves from synchronous
`flate2` / `zstd` over `Read` to `async-compression`'s `bufread`
decoders layered through `tokio_util::io::{StreamReader, ReaderStream}`.

What this PR achieves end-to-end (HttpOrigin → engine → store):
- Per-fetch heap drops to chunk-size for both identity and compressed
  bodies. A 10 GB gzipped origin no longer pins 10 GB of process
  RSS through a `decompress_body` round-trip; decoded bytes flow
  straight into iroh-blobs' `add_stream`.
- The `DECOMPRESS_BLOCKING_THRESHOLD` `spawn_blocking` shim and the
  `read_capped` synchronous decode loop are removed. async-compression
  decodes in poll-driven async chunks, no executor pin.
- Decompression bombs are now caught by the engine's running cap on
  decoded bytes (`count_and_cap_stream`), not by a per-decoder cap
  (the `read_capped` mid-stream check). Same security posture, single
  cap layer.
- Mid-stream stream errors (cap breach, idle timeout, decoder failure)
  flow through a side-channel (`Arc<Mutex<Option<io::Error>>>`) so the
  engine surfaces the actionable upstream message via
  `build_origin_anyhow_from_io`. Typed `OriginError::DecompressionFailed`
  is preserved on the chain via `io::Error::into_inner` +
  `Box::downcast`, so `origin_error_kind()` still recovers it for
  truncated / empty gzip bodies.

Stream-after-error termination: `count_and_cap_stream` and
`response_chunk_stream` both use the `Option<S>`-state-then-`None`-
yield pattern so iroh-blobs' `add_stream` doesn't hang waiting for
`Done` after a sender-drop. On upstream error we **yield None**
(clean stream end) rather than `Err`; the engine reads from the side
channel to surface the real failure instead of the partial-import's
`HashMismatch`. The partial blob lands in the store as an
unprotected `TempTag` and is reclaimed by iroh-blobs' GC.

Workspace deps:
- Add `async-compression` (gzip + zstd, tokio I/O bindings).
- `flate2` and `zstd` move from `[dependencies]` to `[dev-dependencies]`
  on the cache crate (test fixtures still construct gzipped/zstd
  bodies; the runtime no longer touches them).

Tests:
- 141/141 cache unit + integration tests pass; 680/680 workspace
  tests pass.
- `http_origin_rejects_decompression_bomb` updated: bomb is now
  rejected by the engine's `count_and_cap_stream` (single cap
  layer) rather than by the per-decoder `read_capped` cap. Same
  security guarantee, message check switched from "mid-stream"
  to "max_blob_bytes / mid-flight". Typed-downcast assertion
  removed because the cap fires at the engine layer.
- `http_origin_truncated_gzip_surfaces_decompression_failed` and
  `http_origin_empty_gzip_body_surfaces_decompression_failed` keep
  their typed `DecompressionFailed` assertion — the engine's
  `build_origin_anyhow_from_io` peels the typed inner out so the
  chain walk still finds it.
- All headers-phase typed-error tests (`UnsupportedEncoding`,
  multi-encoding rejection, malformed encoding) pass unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@thiras
thiras force-pushed the cozy-conway-issue-271-pr3 branch from e286838 to ab1fa06 Compare May 10, 2026 14:03
@thiras
thiras merged commit fe70c9b into main May 10, 2026
13 of 23 checks passed
@thiras
thiras deleted the cozy-conway-issue-271-pr3 branch May 10, 2026 14:04
@github-actions

Copy link
Copy Markdown

Coverage report

Total: 88.19% (was 87.90%, ▲ +0.29%) — 12115/13737 lines

File Coverage Lines Δ
crates/cache/src/engine.rs 92.26% 1061/1150 ▲ +0.74%
crates/cache/src/origin/fs.rs 82.26% 269/327 ▲ +8.58%
crates/cache/src/origin/http.rs 93.66% 325/347 ▲ +6.00%
History
Commit Total Δ vs base
ab1fa06 (HEAD) 88.19% ▲ +0.29%

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