Repository navigation
fix(cache): restore mid-stream retry classification (#519) - #526
Conversation
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]>
Coverage reportTotal: 88.08% (was 88.27%, ▼ 0.19%) — 12467/14154 lines
History
|
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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_retryprimitive 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.
…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]>
Summary
size_hint <= cache.origin_retry.buffered_max_bytes, default 4 MiB) drain into a boundedBytesMutand classify drain errors; large blobs stream as today but drop the partialTempTagon transient body errors and re-enter the retry loop (iroh-blobs GC reclaims orphaned bytes per cache: wire iroh-blobs GC into runtime — partial-import bytes (hash-mismatch, mid-stream cap breach) currently leak disk indefinitely #518).run_with_retry) wraps a per-attempt closure so the samemax_retriesbudget covers headers, drain, and streaming-restart failures. Deterministic non-retryable outcomes (Store / HashMismatch / BlobTooLarge) ride out viaPullThroughOutcome.cache.origin_retry.buffered_max_byteswith a 64 MiB hard ceiling.0opts out and forces all body-phase failures through the streaming abort+restart path.Closes #519.
Test plan
cargo nextest run --workspace— 706/706 passcargo clippy --workspace --all-targets -- -D warnings— cleancargo fmt -- --check— cleancargo doc --workspace --no-deps— cleancargo deny check— cleancrates/cache/tests/pull_through.rscovering 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 boundarybuffered_max_bytesceiling boundary, at-ceiling, and zero-disable46f3ac7(typedBlobTooLargeMarkeron FS cap breach, helper dedup, doc accuracy fixes, comment cleanup)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 andorigin_retry_exhausted_totaldoes not tickDisk amplification
Worst-case orphaned bytes per fetch on the streaming abort+restart path:
(1 + max_retries) * max_blob_bytes. Reclaimed by iroh-blobs GC atcache.gc_interval_seccadence (default 5 min, wired in #518/#521). Memory cost on the drain path is bounded bybuffered_max_bytesper concurrent fetch (default 4 MiB).🤖 Generated with Claude Code