Skip to content

fix(cache): restore mid-stream retry classification (#519) - #526

Merged
alpergundogdu merged 3 commits into
mainfrom
fix/519-mid-stream-retry-classification
May 14, 2026
Merged

alpergundogdu merged 3 commits into
mainfrom
fix/519-mid-stream-retry-classification

Conversation

@thiras

@thiras thiras commented May 11, 2026

Copy link
Copy Markdown
Contributor

Summary

Closes #519.

Test plan

  • cargo nextest run --workspace — 706/706 pass
  • cargo clippy --workspace --all-targets -- -D warnings — clean
  • cargo fmt -- --check — clean
  • cargo doc --workspace --no-deps — clean
  • cargo deny check — clean
  • 8 new mid-stream retry tests in crates/cache/tests/pull_through.rs covering small-blob drain retry, large-blob abort+restart retry, exhaustion, unknown-size streaming, typed-Permanent decompression short-circuit, buffer opt-out, drain overrun → BlobTooLarge, and the deterministic HashMismatch non-retry boundary
  • 3 new config tests covering buffered_max_bytes ceiling boundary, at-ceiling, and zero-disable
  • Multi-agent PR review (5 specialised agents) — high-confidence findings applied in follow-up commit 46f3ac7 (typed BlobTooLargeMarker on FS cap breach, helper dedup, doc accuracy fixes, comment cleanup)
  • Manual smoke: local HTTP origin behind socat-driven mid-body reset proxy with a 1 MiB and 50 MiB sample blob, cache.origin_retry.max_retries = 3, cache.gc_interval_sec = 30 — verify both succeed despite intermittent resets and origin_retry_exhausted_total does not tick

Disk amplification

Worst-case orphaned bytes per fetch on the streaming abort+restart path: (1 + max_retries) * max_blob_bytes. Reclaimed by iroh-blobs GC at cache.gc_interval_sec cadence (default 5 min, wired in #518/#521). Memory cost on the drain path is bounded by buffered_max_bytes per concurrent fetch (default 4 MiB).

🤖 Generated with Claude Code

thiras and others added 2 commits May 11, 2026 15:01
Pre-#271 HttpOrigin::fetch collected the response body inline, so
transport-layer body errors flowed through classify_reqwest_error and
were retried via retry_fetch. Post-#271 (streaming pipeline) those
errors emerge from the side-channel after fetch returned Ok and so
bypass retry classification entirely — a flaky load balancer that
pre-#271 self-healed via retries now surfaces every mid-body reset
as a one-shot failure to the caller.

Restore retry via a hybrid strategy gated on the new
cache.origin_retry.buffered_max_bytes knob (default 4 MiB):

- Small blobs (size_hint <= buffered_max_bytes): drain the stream
  into a bounded BytesMut inside the retry loop. Drain errors are
  classified via classify_io_error (recognising typed
  BlobTooLargeMarker / OriginError::DecompressionFailed as Permanent;
  reqwest-shaped io::ErrorKind::Other as Transient) and re-feed the
  loop. Zero on-disk amplification.
- Large blobs (size_hint > threshold, or unknown): stream into
  iroh-blobs::add_stream as today, then classify the side-channel
  io::Error after temp_tag().await. On Transient, drop the partial
  TempTag (iroh-blobs GC reclaims at cache.gc_interval_sec cadence,
  wired via #518) and re-enter the retry loop. Bounded memory;
  worst-case disk amp = (1 + max_retries) * max_blob_bytes.

Implementation pulls the loop out of retry_fetch into a
run_with_retry combinator and rewrites pull_through over a new
pull_through_attempt method so the same max_retries budget covers
headers, drain, and streaming-restart failures. Deterministic
non-retryable outcomes (Store / HashMismatch / BlobTooLarge) ride
out via PullThroughOutcome.

Config: buffered_max_bytes carries a 64 MiB hard ceiling
(MAX_BUFFERED_MAX_BYTES) — the abort+restart path covers any blob
size, so raising the buffer beyond that is almost always an
operator typo.

Tests: spawn_mid_body_reset_server connection-counting TCP fixture
plus eight new cases pinning small-blob drain retry, large-blob
abort+restart retry, exhaustion, unknown size_hint streaming,
typed-Permanent decompression short-circuit, buffer disable, drain
overrun -> BlobTooLarge, and the boundary between transient
io::Error retry and deterministic HashMismatch.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Apply the high-confidence findings from the multi-agent PR review:

- FS origin cap breach now packs `BlobTooLargeMarker` instead of
  emitting `io::Error::other(string)`. Pre-fix the string-shaped
  io::Error fell through `classify_io_error` to
  `ErrorKind::Other → Transient`, burning the retry budget on a
  deterministic cap breach. Matches the HTTP origin's symmetry at
  `response_chunk_stream`. The pre-existing unit test
  `cap_at_max_bytes_rejects_one_byte_overrun` now asserts on the
  typed marker shape and the cap value in Display rather than a
  string substring.

- Deduplicate body-phase helpers. The engine's local
  `should_buffer_attempt` and `drain_origin_stream` were byte-
  identical with `retry::should_buffer` / `retry::drain_to_bytes`.
  Promote the retry-module helpers to `pub(crate)` and have the
  engine call them directly. Removes a documented "we might evolve
  these differently someday" hedge that wasn't pulling its weight.

- `default_buffered_max_bytes` is now `const fn` (the `#[allow]` +
  "serde requires fn" comment was inaccurate — serde accepts
  `const fn`).

- Fix stale doc references to the deleted `build_origin_anyhow_from_io`
  in `http.rs` and to the no-longer-used `retry_fetch` in `s3.rs` /
  test docs. Now point at `crate::retry::classify_io_error` and
  `run_with_retry`.

- Sharpen the `classify_io_error` doc to list the exact Transient
  `ErrorKind` set and call out `UnexpectedEof` as the load-bearing
  kind for mid-body resets behind a flaky LB.

- Trim the per-branch `(#519)` markers and narration comments from
  `pull_through_attempt`. The module doc + commit history carry the
  archaeology; inline branch labels rot.

- Replace the misused `// SAFETY:` prefix on the no-origin
  invariant comment with `// Invariant:` (SAFETY is reserved for
  unsafe blocks).

All 706 workspace tests pass; clippy/fmt/doc/deny clean.

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

github-actions Bot commented May 11, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 88.08% (was 88.27%, ▼ 0.19%) — 12467/14154 lines

File Coverage Lines Δ
crates/cache/src/engine.rs 91.11% 1189/1305 ▼ 1.03%
crates/cache/src/origin/fs.rs 82.37% 271/329 ▲ +0.11%
crates/cache/src/origin/http.rs 95.39% 331/347 ▲ +0.86%
crates/cache/src/origin/mod.rs 86.96% 60/69 ▲ +5.80%
crates/cache/src/origin/s3.rs 91.46% 332/363 ● 0.00%
crates/cache/src/retry.rs 83.17% 173/208 ▼ 13.29%
crates/common/src/config/mod.rs 96.49% 3405/3529 ▼ 0.06%
History
Commit Total Δ vs base
46f3ac7 88.07% ▼ 0.20%
dc725e8 (HEAD) 88.08% ▼ 0.19%

@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 implements a robust retry mechanism for origin pulls, specifically targeting mid-stream body-phase failures. It introduces a "buffer-then-commit" strategy for small blobs to avoid disk amplification and an "abort + restart" strategy for larger blobs, managed through a centralized retry loop. The changes include refactoring the CacheEngine, updating RetryPolicy with a configurable memory budget, and adding extensive test coverage for various failure modes. Review feedback recommends refactoring the classify_kind_only function in retry.rs to reduce code duplication by hoisting the error wrapping logic out of the match arms.

Comment thread crates/cache/src/retry.rs Resolved

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

Restores pre-#271 mid-stream retry semantics in the cache pull-through path by extending retry classification into the body phase (via small-blob buffering or streaming abort+restart), and adds a new cache.origin_retry.buffered_max_bytes configuration knob (with validation + tests) to bound memory usage.

Changes:

  • Introduces a shared run_with_retry primitive and updates the cache engine to run a single retry budget across headers, drain, and streaming restart failures.
  • Adds RetryPolicy::buffered_max_bytes (default 4 MiB) plus config validation (64 MiB hard ceiling) and documentation updates.
  • Adds mid-stream retry classification tests (small buffered drain retries, large abort+restart retries, exhaustion, chunked/unknown size, and non-retryable boundaries).

Reviewed changes

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

Show a summary per file
File Description
crates/common/src/config/types.rs Expands operator-facing documentation for origin retry semantics and the new body-phase buffering knob.
crates/common/src/config/mod.rs Adds buffered_max_bytes ceiling validation and new config resolver tests.
crates/cache/src/retry.rs Adds buffered_max_bytes, introduces run_with_retry, and implements drain + body-phase io::Error classification.
crates/cache/src/engine.rs Refactors pull-through into a per-attempt closure wrapped by the unified retry loop; adds drain vs streaming retry behavior.
crates/cache/src/origin/mod.rs Updates OriginByteStream docs to reflect restored body-phase retry classification behavior.
crates/cache/src/origin/http.rs Updates decoder error commentary to align with new body-phase classification path.
crates/cache/src/origin/fs.rs Switches FS cap breach signaling to a typed BlobTooLargeMarker and updates tests accordingly.
crates/cache/src/origin/s3.rs Updates comments to reference the new unified retry loop primitive.
crates/cache/tests/s3_origin.rs Pins headers-phase-only retry behavior by disabling the buffered drain path in this test.
crates/cache/tests/pull_through.rs Adds an extensive suite of mid-stream retry regression tests for both buffered and streaming paths.

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

Comment thread crates/cache/src/retry.rs Resolved
Comment thread crates/cache/tests/pull_through.rs Resolved
Comment thread crates/cache/tests/pull_through.rs Resolved
Comment thread crates/cache/tests/pull_through.rs Resolved
…fixtures

Address PR #526 review findings:

- Refactor classify_io_error to peek typed markers via get_ref()
  before consuming the io::Error. Pre-fix, the no-typed-marker path
  consumed `e` via into_inner() then rebuilt with
  `io::Error::from(kind)` — silently dropping `raw_os_error` for
  errors created via `from_raw_os_error()`/`last_os_error()` (their
  into_inner returns None and the OS code lives in a private Repr
  field that the rebuild can't access). Today's tests don't catch
  this because all three origin adapters wrap via
  io::Error::other(...) (Custom variant, has inner), but a future
  origin emitting a raw OS error would lose actionable diagnostics.
  The peek-first refactor preserves `e` verbatim into anyhow on
  the common kind-only path. (Copilot)

- Also hoist `anyhow::Error::new(...)` out of classify_by_kind's
  match arms — falls out of the refactor naturally. (Gemini)

- Extract drain_http_request_headers helper for the test TCP
  servers in pull_through.rs. The previous inline pattern (1) used
  `Ok(0) | Err(_) => return` inside the per-connection read loop,
  which killed the entire spawned listener task on any single bad
  read — a transient client-side disconnect on attempt N would
  break attempts N+1..N+max_retries with connection-refused errors
  unrelated to the behavior under test, and (2) scanned only the
  latest read buffer for `\r\n\r\n`, missing delimiters split
  across reads (unlikely on loopback for a sub-100-byte reqwest
  GET but real). The helper carries a 3-byte overlap across reads
  and returns per-connection errors so the listener stays alive
  for the full retry sequence. Applied to both
  spawn_mid_body_reset_server and the inline server in
  unknown_size_hint_uses_streaming_path_and_retries. (Copilot)

All 706 workspace tests pass; clippy/fmt/doc/deny clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@thiras
thiras requested a review from alpergundogdu May 11, 2026 13:27
@alpergundogdu
alpergundogdu merged commit a065482 into main May 14, 2026
10 checks passed
@alpergundogdu
alpergundogdu deleted the fix/519-mid-stream-retry-classification branch May 14, 2026 12:03
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: mid-stream origin errors no longer feed retry classification (regression vs pre-streaming HttpOrigin)

3 participants