Repository navigation
perf(cache,cli,node): stop materializing whole blobs, and make decdn fetch resumable - #1496
Conversation
Serving a blob held the whole thing in RAM twice over. `export_bao_range` materialised the entire aligned bao range before the first frame went out, and `pull_through` read a freshly-committed blob back out of the store to hand it to `populate`, which drops it. A 708 MB blob therefore cost ~708 MB resident on the serve leg and again on the miss leg. Both are now bounded by a chunk group: - `export_bao_range_stream` yields the same header-less wire bytes per bao item. `export_bao_range` becomes a drain of it, so the existing ADR 038 round-trip tests still cover the buffered form; the serve path drives the stream through a new `ChunkFramer` that re-cuts items into CHUNK_SIZE frames. - `pull_through` takes `want_bytes`; `populate`/`populate_local` pass `false` and get the payload-free `PullThroughOutcome::Committed`. `get` is unchanged. One behaviour change worth knowing: the truncated-export refusal (the store's item channel closing without a terminal `Done`) can only be detected after the last item, so it now surfaces mid-stream rather than before the first byte. The billing invariant holds — the client sees a short delivery and never pays the closing voucher — but detection moved from pre-flight to mid-flight. The `populate` doc already promised the blob was "not re-assembled into a buffer the caller would just drop". That is now true. Progress on #1132. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`decdn fetch` buffered the whole blob twice — the bao wire form in a BytesMut, then the decoded form in a Vec — and wrote it in one shot at the end. Peak memory was ~2x the blob, and an interrupted fetch left nothing usable: re-running re-downloaded and re-paid from byte 0. It now writes each chunk group to `<output>.partial` the moment that group verifies, then renames it into place. Peak memory is one chunk group regardless of blob size, and a partial left by an earlier run is picked up automatically — the node is asked for the tail only, so only the tail is paid for. The new `client-pull::sink` drives bao-tree's incremental `ResponseDecoder` (io::fsm) over the existing `UpstreamPull`, so this reuses the streaming, voucher-paying chunk source the node's window path already uses rather than adding a second receive loop. `bao-tree`'s `tokio_fsm` feature is requested explicitly rather than inherited from workspace feature unification, since `decdn-cli` has no iroh-blobs crate in its graph to turn it on — the CLI's iroh-blobs-free invariant is unchanged (`cargo tree -p decdn-cli -e normal -i iroh-blobs` is still empty). Two things worth calling out: - A prefix inherited from disk CANNOT be verified in isolation: bao verifies a chunk group through the parent hashes covering the rest of the tree, and a client holding only a prefix never received them. So a resumed fetch re-hashes the assembled file against the content hash before promoting it, and discards the partial on mismatch. A fetch from byte 0 skips that — every byte was verified on the wire. - The streaming path drives its own #1481 reseed-and-retry loop rather than inheriting `fetch_inner`'s, because between attempts the output file has to be rewound to the resume offset; appending the re-fetched span twice would corrupt the download. `resumable_watermark` and `MAX_RESUME_ATTEMPTS` are exported so both loops share one bound. Closes #1120. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…work Five review agents over the previous two commits. Three findings were real bugs and one was a false claim I had written into the code, the CHANGELOG, and the commit message. Money bugs: - The interrupted-fetch path persisted `ledger.committed()`. `settlement()` is what a cancelled pull must write: vouchers are sent optimistically (#1484), so when a transfer dies there are usually vouchers in flight that the upstream has already persisted (it persists before it acks). Settling low there re-signs a spent nonce and wedges the channel permanently — the exact #1122 failure this work exists to prevent. The two readers are equal on success and diverge only on interruption, which is the one path that mattered. - A `.partial` the node cannot serve a resume for (left by a fetch of a different or larger blob, or complete-but-unpromoted) failed before the pull opened. That refusal is not a voucher rejection, so nothing reseeded and the partial was deliberately kept — wedging every subsequent run with an error blaming the node. It is now treated as proof the partial is not this blob's: discard and refetch once. Covered by a fourth e2e journey. - A flush failure was dropped whenever the pull also failed (`and_then` short-circuits). Disk-full surfaced as "the peer stalled", and if the pull error happened to be resumable the loop burned every retry re-paying vouchers against a local condition no retry could fix. The flush error now wins. Correctness and diagnosability: - `ChunkFramer` did not poison on an export fault, so a later call could cut a frame out of a partially-received, unverified export item and bill for it. - A mid-export fault had no node-side log; the client can only report it as a generic short delivery, so the operator had no signal at all. - `read_if_manifest` did an unbounded `read_to_end` on anything starting with the 8 unauthenticated `DECDNMAN` magic bytes — in the one function whose purpose is avoiding whole-blob buffering. - `metadata()` errors collapsed to "no partial", so a permissions fault would discard a large verified prefix and re-pay for the whole blob. - The progress bar did not move: `on_progress` fired once, at 100%, after the bar had been cleared. Now reported per verified chunk group, against the whole blob so a resumed fetch continues rather than restarting at 0. Corrected claim: I documented that a bao prefix "cannot" be verified in isolation. That is wrong. ADR 038: given the outboard, any range verifies against the root with an O(log n) proof and no earlier bytes — and `decdn-bao-range` does exactly that from an untrusted `{H}.obao4`. The client received those parent hashes and discarded them. The whole-file re-hash is still the right call, but because the CLI persists no outboard sidecar (#578) and one BLAKE3 pass is cheaper than a second on-disk format — a choice, not an impossibility. Fixed in the module docs and in the user-facing CHANGELOG entry. Tests: the stashed-fault precedence had zero coverage — every existing test drove the no-op `Bytes` impl, so swapping the two branches would have silently downgraded every peer stall and refusal to an anonymous decode error and stopped the peer being scored. Added a scripted faulting reader that pins both directions. Renamed one test that promised something it cannot observe, and noted the buffered/streaming export equality assertion is now a tautology. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…th directions `pull_through` and `pull_through_attempt` took `want_bytes: bool` directly beside `local_only: bool`. Two adjacent booleans the compiler will happily let you swap, in a chain where getting it wrong either reinstates the #1132 whole-blob read-back or stops `get` consulting peer origins — and neither failure has a test that would catch it. At the `populate` call site both happened to be `false`, so a swap was invisible in a diff too. `FillMode::{ReturnBytes, CommitOnly}` replaces it. Call sites now read `pull_through_fill(hash, local_only)` and `pull_through_bytes(hash)`: two total wrappers, so no caller names a mode or unwraps the `Option` at all. The correspondence is also now exact in BOTH directions, which it was not. `commit_buffered_bytes` returned its drain buffer regardless of the flag, so "CommitOnly implies no payload" was true while the converse was false — an exception that made the wrappers partial and the mode untrustworthy to read. It now drops the buffer and reports `Committed` like the streaming arm. That is a contract win rather than a memory win: the drain already holds those bytes, and the arm stays bounded by `buffered_max_bytes` (8 MiB) either way. The `populate` doc drops the caveat it had to carry for the exception. Tested where it can actually be observed: `PullThroughOutcome` is private, so the integration tests in `tests/pull_through.rs` can only see that a fill happened, not which arm produced it. The correspondence assertion lives in engine.rs's own test module and drives the buffered arm specifically (the streaming arm never had the defect). Verified it fails on a reverted fix with "CommitOnly must yield no payload, got Some(...)" rather than passing vacuously. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Warning Review limit reached
Next review available in: 9 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Free Run ID: 📒 Files selected for processing (7)
WalkthroughThe pull, cache, node delivery, and CLI paths now stream Bao data incrementally. Cache fills avoid unnecessary readbacks, node delivery frames streamed exports, and ChangesStreaming delivery and resumable downloads
Sequence Diagram(s)sequenceDiagram
participant CLI
participant ClientPull
participant Node
participant Cache
participant PartialOutput
CLI->>ClientPull: request verified download tail
ClientPull->>Node: pull Bao groups from resume offset
Node->>Cache: stream blob export
Cache-->>Node: return export items or terminal fault
Node-->>ClientPull: send bounded data frames
ClientPull->>PartialOutput: write verified bytes
CLI->>PartialOutput: validate and atomically rename on success
Note 🎁 Summarized by CodeRabbit FreeYour organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login. Comment |
Gas snapshotNo gas changes vs base. |
Contracts coverageLine coverage: 89.57% (2422/2704 lines) |
There was a problem hiding this comment.
Pull request overview
This PR addresses large-blob memory blowups and makes decdn fetch resumable by switching both the node delivery path and the CLI/client receive path from whole-blob buffering to incremental, bao-verified streaming. The changes fit into the codebase’s existing “bao verified-stream” model (ADR 038) and extend it end-to-end so peak memory is bounded by a chunk group rather than blob size.
Changes:
- Node serve: drive a streaming bao export and re-frame it into fixed
CHUNK_SIZEwire frames without materializing the full export buffer. - Cache miss / populate: introduce a fill-only mode so pull-through commits don’t read the blob back out just to drop it.
- CLI fetch: stream verified groups to
<output>.partial, resume from a group-aligned prefix, and only re-pay for the remaining tail; add an anvil-backed e2e merge gate.
Reviewed changes
Copilot reviewed 12 out of 13 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| crates/node/src/handlers/client/delivery.rs | Adds a ChunkFramer to re-cut streaming bao-export items into cdn/client/v1 chunk frames and serve without whole-blob buffering. |
| crates/e2e/tests/cli_fetch_resume.rs | Adds an anvil-backed e2e test covering clean fetch, resume, corrupt partial handling, and stale partial recovery. |
| crates/client-pull/src/sink.rs | Introduces a streaming decode/verify/trim/write pipeline that drives bao-tree incrementally from a live UpstreamPull. |
| crates/client-pull/src/lib.rs | Exposes MAX_RESUME_ATTEMPTS and resumable_watermark for reuse by the CLI’s streaming retry loop; wires in the new sink module. |
| crates/client-pull/Cargo.toml | Enables bao-tree’s tokio_fsm feature and adds iroh-io for the incremental decoder reader trait. |
| crates/cli/src/commands/fetch.rs | Switches decdn fetch to streaming-to-disk with .partial resume, adds manifest sniffing with a size cap, and promotes via rename. |
| crates/cache/tests/pull_through.rs | Adds tests asserting streaming vs buffered export equivalence and that populate works via both buffered/streaming commit-only paths. |
| crates/cache/src/engine.rs | Adds FillMode plumbing so commit-only pull-through avoids post-commit read-back; implements export_bao_range_stream plus buffered drain wrapper. |
| crates/bao-range/src/lib.rs | Makes CHUNK_GROUP_BYTES public for callers that must align offsets before knowing total blob size. |
| CHANGELOG.md | Documents the new bounded-memory delivery, streaming/resumable CLI fetch behavior, and the mid-stream truncation refusal behavior change. |
| Cargo.toml | Adds a workspace dependency pin for iroh-io compatible with bao-tree 0.16. |
| Cargo.lock | Updates lockfile to include iroh-io where required. |
| .github/workflows/ci.yml | Updates e2e journey inventory comments to include the new cli_fetch_resume test. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Coverage reportTotal: 80.79% (was 80.91%, ▼ 0.11%) — 54697/67701 lines
History
|
…icit rejection A second review round over the previous two commits. The fix commit (e082743) had introduced a worse bug than the one it fixed, plus two more. **The stale-partial restart destroyed paid-for data on any hiccup.** It was gated on `resumable_watermark(&err).is_none()` — "not a resumable voucher rejection" — while its comment claimed it detected a resume offset past the blob's end. Those sets are nothing alike: stalls, resets, HashMismatch, node refusals and the local flush error all took the branch. A resumed 690 MB fetch that dropped once would print "the partial cannot belong to this blob" (false), truncate to zero, and re-pay for the whole blob — inverting the feature, since resume then only survived a run with no hiccups. The floor check now returns a typed `ResumeOffsetPastEnd` and the restart keys on that and nothing else. **The restart also skipped the retry-budget guard.** `continue` sat above the `attempt == MAX_RESUME_ATTEMPTS` check, so firing on the final iteration fell out of the `for` into the "unreachable" bail: real error dropped, a message about a refetch that never happened, and the untruncated partial left to wedge the next run anyway. Rebuilt as a `loop` with an explicit counter — a restart is not a retry, so it no longer spends the budget, and there is no fall-through left. **`settlement()` over-settles after an explicit rejection.** `resolve_reject` pops only the front of the outstanding set, so vouchers pipelined behind a rejected one stay armed and `settlement()` reports them. `advance_progress` returns `Regressed` *without writing*, so that inflation is permanent and can pin `last_amount` above the deposit — wedging the channel from the opposite side to the bug settle-high was added to prevent. Now `committed()` on an explicit rejection (the node applies vouchers in nonce order, so followers were provably never taken) and `settlement()` when the failure is ambiguous. Also: the flush error now chains the pull error instead of dropping it; the manifest cap is derived from `MAX_CHUNKS` (at 32 MiB it was *below* what `MAX_CHUNKS` permits, so it would have rejected manifests `decode` accepts). `combine_pull_and_flush`, `watermark_after` and `existing_partial_len` are extracted as free functions specifically so they can be tested — the sharpest review finding was that these fixes had no test able to tell fixed from broken. Verified by reverting: `watermark_after` and `combine_pull_and_flush` both fail. `a_mid_export_fault_propagates` now uses a payload that leaves bytes buffered at the fault, so it actually exercises the poisoning it claimed to. Doc corrections, each verified against source: `buffered_max_bytes` defaults to 4 MiB not 8 (wrong in four places); a sidecar would not remove the O(blob) pass (verifying a prefix still hashes every group in it) and could not use `encode_verified_range`, which needs a complete outboard; `buf.clear()` drops whole verified items, not "partially-received unverified" ones; ADR 038 AC#3/#7, not AC#4; and the surviving "cannot be verified" claim the last sweep missed. The corrected e2e inventory (19 tests / 16 files / 256m) shows the balanced ceiling now sits just under the 130m job bound. Recorded in the comment rather than acted on — raising the CI budget is a separate call. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The previous commit's stale-partial restart was unreachable in practice, and the e2e caught it: journey 4 wedged for its full 90s retry window. `ResumeOffsetPastEnd` only fires when a server signs an `ok: true` response whose `total_bytes` is at or below the requested offset. An honest node never gets there — its range gate refuses `byte_offset >= total_bytes` BEFORE signing (`dispatch.rs`), and `ServeRejectReason::RangeNotSatisfiable` then **collapses to `NotFound` on the wire** by design, grouped with cache miss and unknown channel so that a client's bad range stays reputation-benign and leaks nothing (`ServeRejectReason::wire_error`). So the client cannot distinguish "your offset is past the end" from "I don't have this blob", and the narrow, positive predicate I reached for does not exist at this layer. Rather than pretend the signal is unambiguous, make acting on it safe: - **Open before touching the file.** The rewind is destructive and an open can fail for reasons that have nothing to do with the partial — an evicted blob, an unknown channel, a dead link. Truncating first destroyed a verified, paid-for prefix and then failed anyway, leaving the user worse off than before they ran the command. The rewind now happens only once an attempt is committed to writing. - **`resume_may_be_stale` accepts `NotFound` as well as `ResumeOffsetPastEnd`**, because that is what a real resume-past-the-end produces, while still excluding stalls, resets, hash mismatches and local flush failures — none of which say anything about the offset. Together those make the ambiguity cheap: a genuine cache miss fails the from-zero open too, nothing was truncated, and the prefix is still on disk for a later run against a node that has the blob. The cost of guessing wrong is one wasted open instead of the user's data. The e2e failure is the useful part of this. Five review agents and I all read the collapse-to-NotFound comment without following it to its consequence — one agent even noted "against an honest node the client-side floor never fires", which I filed as a wording issue rather than a reachability bug. The journey that caught it is the one added two commits ago for exactly this scenario. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Three open issues turned out to be three views of one observed incident (a 708 MB blob): whole blobs held in RAM on both ends of a paid delivery, and no resume when a transfer dies.
Closes #1132
Closes #1120
#1122 is addressed in part — see the breakdown below and #1495 for the remainder.
What changed
export_bao_rangematerialised the entire aligned bao range before the first frameexport_bao_range_stream+ aChunkFramerthat re-cuts bao items intoCHUNK_SIZEwire framespull_throughread a just-committed blob back out of the store to hand topopulate, which drops itFillMode::CommitOnly— no read-back, no payloaddecdn fetch<output>.partialas it verifies, renames into placePeak memory on all three is now one chunk group, independent of blob size. An interrupted fetch leaves a resumable prefix and re-pays only for the tail.
The streaming client work reuses
open_progressive_pull/UpstreamPull— the voucher-paying chunk source the node's window path already drives — rather than adding a second receive loop.bao-tree'stokio_fsmfeature is requested explicitly rather than inherited from workspace feature unification, sincedecdn-clihas no iroh-blobs crate in its graph to turn it on. The iroh-blobs-free invariant is unchanged (cargo tree -p decdn-cli -e normal -i iroh-blobsis still empty).Behaviour changes worth knowing at review time
tracing::error!because the client can only report it as a generic short delivery.<output>.partialbehind. That is what the next run resumes from. It is discarded on a failed integrity check, or when the node cannot serve a resume at its offset (which proves it belongs to a different blob).Review history
The first two commits went through a five-agent review; commit 3 is the fixes, commit 4 is a follow-up refactor. Findings that were real bugs in my own code:
ledger.committed()wheresettlement()is required. Vouchers are sent optimistically (Client blocks on VoucherAck for nothing: pure dead latency, and it serializes parallel streams to one provider #1484) and the node persists before acking, so settling low re-signs a spent nonce and strands the channel — the exact Payment channels aren't resilient to a fetch exiting early: it strands the channel + deposit (durable watermark, resumable fetch, resync, coop-close reconciliation) #1122 failure this work exists to prevent. The two readers are equal on the success path, which is why every test passed..partialwedged the command permanently — a partial from a different or larger blob makes the node refuse the offset; not a voucher rejection, so nothing reseeded and the file was kept, failing identically forever with an error blaming the node.I also had to correct a claim I had written into the code, the CHANGELOG and a commit message: that a bao prefix cannot be verified in isolation. ADR 038 says the opposite, and
decdn-bao-rangedoes exactly that from an untrusted outboard. The whole-file re-hash is still the right call, but as a choice (no sidecar format) rather than an impossibility — left uncorrected it would have stopped a future maintainer from removing it.#1122 status
CooperativeCloseAuth. Filed as #1495Verification
cargo fmt --check,clippy --all-targets -D warnings, 2658 tests,cargo doc,cargo deny— clean.cli_fetch_resume(anvil-e2e, a required merge gate) runs four journeys against a real chain, node and paid channel: clean fetch, resume, corrupt partial, and stale partial from another blob. Its load-bearing assertion is that a resumed fetch bills strictly fewer bytes than a full one — without that inequality the test would pass against an implementation that silently re-downloaded everything.No contract, ABI, config-knob or wire-protocol change, so no gas snapshot and no
sol!binding drift.🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
decdn fetchnow streams downloads and can resume interrupted transfers using.partialfiles.Bug Fixes