Repository navigation
feat(cli): consume DECDNMAN file manifests and reconstruct chunked files - #1293
Conversation
Implements the client-side consumer for the 256 MiB-chunk file manifest format pinned in ADR 012 § File Manifests and Reconstruction (#1183). Large single-file publishing had no download path: the manifest blob had no Rust type and no consumer, so fetching a manifest hash wrote the manifest bytes out as if they were the file. `commands::file_manifest` adds the postcard-encoded `FileManifest` / `ChunkEntry` types, a magic sniff, and the reconstruction driver: fetch each chunk in order, verify it against its own BLAKE3 hash and declared size, stage it at ~/.decdn/downloads/<manifest-hash>/chunk-<i>.part, then stream-concatenate the parts into the output file. Part files are retained by default so the client can re-serve them (and so an interrupted reconstruction resumes without re-paying for chunks it already holds); the new --no-keep-blobs deletes them immediately. Both client entry points sniff the 8-byte magic: `decdn fetch` and each `decdn bundle pull` entry, since the two manifest layers compose. Wrong or missing magic means the bytes are a raw blob and the pre-existing write-through path is untouched. Chunk pulls reuse the node and channel already resolved for the manifest blob but rebuild the ChannelContext per chunk — the context snapshots the voucher watermark, so a hoisted one would re-sign a spent nonce across a multi-chunk file. That is why `fetch`'s inline open-or-reuse plus ADR 005 binding is extracted into `build_channel_ctx`. Named FileManifest to keep it unambiguous against the unrelated JSON inter-file bundle Manifest in `bundle_pull` (appendix-bundles.md § Relationship to file manifests). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Warning Review limit reached
Next review available in: 13 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 ignored due to path filters (1)
📒 Files selected for processing (8)
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 |
There was a problem hiding this comment.
Code Review
This pull request implements ADR 012 for client-side reconstruction of chunked single-file manifests (DECDNMAN). It introduces a new file_manifest module to sniff, decode, and sequentially fetch and verify chunks, integrating this flow into both the fetch and bundle_pull commands. Feedback focuses on optimizing chunk retrieval: first, by avoiding redundant node discovery and probing for each chunk in bundle_pull by reusing the target node; and second, by checking file size before hashing and using blake3::Hasher::update_reader in part_is_verified to improve disk I/O efficiency.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| async fn reconstruct_entry( | ||
| &self, | ||
| manifest: anyhow::Result<file_manifest::FileManifest>, | ||
| manifest_hash: [u8; 32], | ||
| dest: &Path, | ||
| ) -> anyhow::Result<u64> { | ||
| let manifest = manifest?; | ||
| file_manifest::reconstruct( | ||
| &manifest, | ||
| manifest_hash, | ||
| &file_manifest::downloads_root(), | ||
| dest, | ||
| !self.common.no_keep_blobs, | ||
| |chunk_hash| self.fetch(chunk_hash), | ||
| ) | ||
| .await | ||
| } |
There was a problem hiding this comment.
In reconstruct_entry, passing |chunk_hash| self.fetch(chunk_hash) to file_manifest::reconstruct introduces a significant performance penalty when auto-discovery is active (i.e., when self.explicit is None). For every single chunk of the file, self.fetch will call self.pick(chunk_hash), which triggers a full network probing and ranking round (probe_and_rank) across all candidates.
Since all chunks of a file manifest are almost certainly hosted on the same node that served the manifest itself, performing redundant discovery for each chunk adds massive latency and network overhead.
To resolve this, consider refactoring PullCtx::fetch to split out a fetch_from(hash, node_id, provider) helper that bypasses self.pick. Then, in fetch_entry, resolve the (node_id, provider) once for the manifest hash, and pass them to reconstruct_entry so that all chunk fetches can directly reuse the same target node and provider without re-running discovery.
There was a problem hiding this comment.
Not taking this as proposed — it trades an availability guarantee for the latency win.
probe_and_rank does not just rank; it filters candidates on resp.body.has_blob for the specific hash being fetched (fetch.rs:290). So the per-chunk pick is what guarantees the selected node actually holds that chunk. Pinning (node_id, provider) from the manifest blob for all chunks rests on "all chunks are almost certainly hosted on the same node" — in a cache network where nodes hold blob subsets and evict independently, that is exactly the assumption the probe exists to avoid. A 40-chunk 10 GiB file whose tail was evicted from the manifest's node would go from "discover a holder per chunk" to "fail on chunk 17".
The latency observation is real, though — N probe rounds for N chunks is a lot of round trips. The right shape is try-the-manifest's-node-first with fallback to discovery on miss, which keeps the guarantee and removes the probe from the common path. That is a new selection policy rather than a fix to this PR's scope, so it is filed as #1294.
| fn part_is_verified(part: &Path, chunk: &ChunkEntry) -> bool { | ||
| let Ok(file) = std::fs::File::open(part) else { | ||
| return false; | ||
| }; | ||
| let mut hasher = blake3::Hasher::new(); | ||
| let Ok(read) = std::io::copy(&mut std::io::BufReader::new(file), &mut hasher) else { | ||
| return false; | ||
| }; | ||
| read == chunk.size && *hasher.finalize().as_bytes() == chunk.hash | ||
| } |
There was a problem hiding this comment.
In part_is_verified, the function reads and hashes the entire file to verify its integrity. Since chunks can be up to 256 MiB, performing full BLAKE3 hashing on mismatched or partially downloaded files is highly inefficient.
Consider checking the file's metadata size first. If the file size on disk does not match chunk.size, we can immediately return false and avoid any redundant disk I/O and hashing. Additionally, prefer using blake3::Hasher::update_reader for hashing file streams in Rust. This built-in method is more efficient and correctly handles internal buffering and retry logic for interrupted reads (EINTR) compared to std::io::copy with a BufReader.
fn part_is_verified(part: &Path, chunk: &ChunkEntry) -> bool {
let Ok(mut file) = std::fs::File::open(part) else {
return false;
};
if let Ok(metadata) = file.metadata() {
if metadata.len() != chunk.size {
return false;
}
} else {
return false;
}
let mut hasher = blake3::Hasher::new();
if hasher.update_reader(&mut file).is_err() {
return false;
}
*hasher.finalize().as_bytes() == chunk.hash
}References
- Prefer using
blake3::Hasher::update_readerfor hashing file streams in Rust. This built-in method is more efficient and correctly handles internal buffering and retry logic for interrupted reads (EINTR).
There was a problem hiding this comment.
Fixed in 6619dcb. part_is_verified now rejects on metadata().len() != chunk.size before hashing, and uses blake3::Hasher::update_reader — the EINTR-retry point is the one that matters here, since an interrupted read under io::copy would have been reported as a verification failure and cost a re-fetch. Added a_truncated_part_is_refetched to pin it.
There was a problem hiding this comment.
Correction to my reply above: I claimed the EINTR-retry behavior was what update_reader bought over io::copy. That is wrong — std::io::copy's generic loop has always had Err(ref e) if e.kind() == ErrorKind::Interrupted => continue, so an interrupted read would not have been reported as a verification failure under the old code. The real advantages are the 64 KiB buffer sized for the hasher's block processing and skipping the Write-impl round-trip; the size-check-before-hashing part of your original comment was the substantive win.
The code change stands, but the rationale I committed alongside it was misleading. Corrected in #1301, which also fixes a set of findings from a follow-up review of this PR.
Coverage reportTotal: 81.73% (was 81.84%, ▼ 0.11%) — 49685/60791 lines
History
|
part_is_verified hashed the whole part file before comparing its length, so a truncated part from an interrupted run cost a full 256 MiB read to reject. Check the length from the directory entry first, and hash via blake3::Hasher::update_reader, which retries interrupted reads instead of surfacing them as a verification failure. The module doc linked [`FileManifest`], which is pub(crate) — rustdoc's private-intra-doc-links lint is deny under CI's RUSTDOCFLAGS=-D warnings. Plain code span instead. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… ADR citation Addresses PR review findings for DECDNMAN file-manifest reconstruction (#1183): - Add `a_same_size_corrupt_part_is_refetched` unit test covering the hash branch of `part_is_verified` (a right-size, wrong-content part). The prior truncation test only exercised the size branch; if the hash check regressed, corrupt bytes would be silently concatenated and the size-only total_bytes guard would not catch it. - Add `crates/e2e/tests/cli_fetch_manifest.rs` (anvil-gated): drives the shipped `decdn` binary end-to-end against a real node serving a 3-chunk manifest over a real payment channel, asserting the reconstructed file and that the persisted voucher watermark advanced per chunk. This is the only test that reaches the per-chunk `ChannelContext` rebuild in `ChunkFetcher::fetch`; a `reconstruct()` fake-fetcher unit test cannot, so a future hoist that re-signs a spent nonce would slip past it. postcard/serde are gated behind `anvil-e2e` so default builds carry no unused dep. - Fix a broken ADR citation in file_manifest.rs and bundle_pull.rs: the section is "Non-relationship to ADR 012's DECDNMAN chunk manifest", not "Relationship to file manifests" (which does not exist; a differently-scoped "Relationship to ADR 002 / ADR 013" section would mislead a reader following the citation). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Gas snapshotNo gas changes vs base. |
Contracts coverageLine coverage: 88.95% (2495/2805 lines) |
* fix(cli): harden DECDNMAN reconstruction after review of #1293 A five-agent review of #1293 (merged) surfaced findings this addresses. Corruption residue: concat_parts renamed the reconstructed file into place before reconstruct compared its length to total_bytes, so a mismatch told the user the download failed while wrong bytes sat at the output path -- and bundle pull's skip-existing, whose comment asserts "a present final file is verified-good", then skipped it on every later run. The length check now happens inside concat_parts before the rename, matching the invariant the module already pins for the BLAKE3 path ("no output on a failed verification"). Low reachability by design; that is why a guard whose failure mode persists corrupt bytes was worth closing. Manifest bounds: decode now rejects >1M chunks, zero-size chunks, a filename that is not a bare basename, and trailing bytes after the record. Each chunk is a separate *paid* pull, so the chunk count is a spending bound, not just a memory one -- --max-blob-mb caps the manifest blob but still leaves room for tens of millions of entries. The filename check closes a traversal class before the field is ever wired to a path. Blocking IO: part verification (hashing up to a whole chunk) and concatenation ran on the executor, and bundle pull polls every entry from ONE task, so one large reconstruction stalled every sibling entry -- whose stall deadlines are wall-clock timers that elapse unpolled and fire on return. Both now run on the blocking pool. Shared part directories: the part dir is keyed only on the manifest hash, and two bundle entries may name the same manifest (one file at two paths; entries are not deduped by hash). Concurrent reconstructions shared it -- with --no-keep-blobs one entry's cleanup deleted parts while the other was mid-concatenate, and without it both paid for every chunk twice. Now serialized per manifest hash. Cross-process remains unguarded. Silent paid re-fetches: part_is_verified returned false on any IO error, so a bad sector silently re-fetched (and re-paid for) a chunk on every run, against the retention promise. Only NotFound is silent now. The --no-keep-blobs cleanup also swallowed remove_dir failures, which hid the orphan .tmp that write_blob_atomic stages inside the part dir. Part location: downloads_root took no argument and hardcoded ~/.decdn/downloads while --data-dir resolves to ~/.decdn/client, so the largest thing the client writes ignored an explicit --data-dir. Both call sites already hold the resolved dir on ResolvedChain. Comments: an update_reader rationale I added in 6619dcb claimed EINTR retry as the advantage over io::copy. std::io::copy retries Interrupted too, so that was not the distinction; the real ones are the 64 KiB buffer and skipping the Write round-trip. Also corrected "separate magic" (the bundle manifest has none) and "the last one is partial" (not an invariant). ADR 012 step 3 said "delete part files", contradicting its own Blob retention section; amended along with the parts path. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(cli): correct manifest-lock claim, unblock cleanup, tighten guards Second review pass over #1301 found the highest-severity issues were in that PR's own additions. The manifest-lock comment claimed serializing per manifest hash makes the second entry "find the first's verified parts and pay nothing". That holds only under the default retention. With --no-keep-blobs -- named two sentences earlier as the motivating hazard -- the first entry deletes every part before releasing the guard, so the second re-fetches and re-pays for every chunk. The lock does fix the mid-concatenate deletion race in both modes; only the payment claim was wrong. Corrected, and the behavior question filed as #1306 rather than fixed here: ADR 012 pins --no-keep-blobs as deleting "immediately after reconstruction", so deferring the sweep is an ADR amendment, not a review cleanup. The --no-keep-blobs cleanup loop was still running inline in the async fn -- up to MAX_CHUNKS unlink syscalls on the executor, the exact hazard this PR moved every other filesystem call off it to avoid, contradicting the rule stated in the same function. Now on the blocking pool, and its per-part warnings collapse to one summary line: thousands of identical lines is how a warning gets trained out of a user's attention. A wrong-size part now warns like a hash mismatch. Parts are written O_EXCL-temp then renamed, so this program only ever leaves one absent or complete -- a short part means a foreign writer or filesystem damage, not the "interrupted write" the old comment claimed. The rustdoc also said "only a missing part is silent" while the code silently accepted short ones twelve lines below. MAX_CHUNKS docs: said "three orders of magnitude" of headroom over 10,000-chunk files; 10,000 to 1,000,000 is 100x, i.e. two. Three of four reviewers also read the --max-blob-mb sentence as an allocation argument, so it now says explicitly that this bounds spending and file count, not allocation -- serde grows the vector as bytes are consumed, so an over-large list implies an over-large (capped, already paid for) blob. Same framing fixed in the ADR. Also ~34 -> ~33-37 bytes per entry, and the 64 KiB figure dropped since blake3 documents it as unstable. Error context: the part-verification spawn_blocking hardcoded a string with no path or index, and concat_parts' io::copy had none, so a bad sector reported neither which part failed nor that deleting it recovers. Tests: the filename guard's "." arm was uncovered, the MAX_CHUNKS boundary was unpinned (> vs >= survived), and empty-filename acceptance was pinned only in an anvil-gated e2e. The unit test for downloads_root only restated its own body; the wiring is now pinned in cli_fetch_manifest.rs, which already isolates HOME and passes --data-dir, so only honoring the flag puts parts where it asserts. Note iroh_blobs::Hash displays as base32 while the part dir is hex -- to_hex(), not Display. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(cli): move whole-chunk verify off the executor, test the cleanup leak Review follow-ups on the #1301 hardening: - `reconstruct` verified freshly-fetched chunk bytes with a whole-chunk BLAKE3 hash INLINE on the async executor, between the two calls this PR already offloaded (`part_is_verified` and `write_blob_atomic`). The cache-miss path is the one place that hash always runs, so it reintroduced the exact sibling-entry stall the offloads exist to prevent. Fold the verify into the same blocking closure as the write; verifying first still keeps a bad chunk off disk. (The transport already verifies chunk bytes against `chunk.hash` via client-pull's bao decoder, so this is defense-in-depth — but a whole-chunk hash regardless.) - Add `no_keep_blobs_leaves_a_dir_holding_an_orphan_tmp`, pinning the one branch the prior commit deliberately hardened: an orphan `.tmp` makes `remove_dir` fail `ENOTEMPTY`, the dir must survive (leak visible), and the run must still succeed. A regression back to `let _ =` was invisible. - Fix a stale doc: `--no-keep-blobs` help still named `~/.decdn/downloads`, which this branch moved to `<data-dir>/downloads` (default `~/.decdn/client/downloads`). - Reconcile a "256 MiB-scale" test comment with the size-agnostic runtime. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: Ant Somers <[email protected]>
Implements the client-side consumer for the 256 MiB-chunk file manifest format pinned in ADR 012 § File Manifests and Reconstruction. Large single-file publishing had no download path — the manifest blob had no Rust type and no consumer, so passing a manifest hash to
decdn fetchwrote the manifest bytes out as if they were the file.Consumer side only, as scoped: no manifest producer/chunker. The ADR pins the format completely, so nothing here is invented.
What's added
crates/cli/src/commands/file_manifest.rs:FileManifest/ChunkEntry, postcard-encoded exactly as the ADR specifies. Postcard writes a[u8; 8]as eight bare bytes, so theDECDNMANmagic really is the blob's prefix and can be sniffed before any deserialization.sniff()—Noneon wrong/missing magic (those bytes are a raw blob, per the ADR's backward-compatibility rule),Some(Err(_))when the magic matches but the body is unusable. A corrupt manifest fails loudly rather than being written out as file content.reconstruct()— fetch each chunk in order, verify against its own BLAKE3 hash and declared size, stage at~/.decdn/downloads/<manifest-hash>/chunk-<index>.part, then stream-concatenate the parts into the output file (atomic temp-then-rename). Streamed, not buffered: chunks are 256 MiB and the file need not fit in memory.--no-keep-blobsdeletes them immediately.Both entry points
The magic sniff is applied at both places a blob's bytes land:
decdn fetch— a manifest hash passed directly now reconstructs.decdn bundle pull— a bundle entry's blob may itself be a file manifest; the two layers compose (appendix-bundles.md§ Relationship to file manifests).Chunk pulls reuse the node and channel already resolved for the manifest blob, but rebuild the
ChannelContextper chunk. The context snapshots the channel's voucher watermark (prior_nonce), whichfetch_blobadvances in the store as it pays, so a hoisted context would re-sign a spent nonce across a multi-chunk file — and it gives each chunk a fresh low-deposit refill check (#1103). That is whyfetch's inline open-or-reuse + ADR 005 binding is extracted intobuild_channel_ctx. On thebundle pullside chunk fetches go through the existingPullCtx::fetch, so the per-provider mutex already serializes them; sequential is what the ADR requires anyway.Naming
Deliberately
FileManifest, notManifest. The unrelatedManifestinbundle_pullis JSON, publisher-side, and inter-file; this one is postcard, ingest-side, and intra-file. Different layer, different magic. The module doc spells out the non-relationship.Tests
9 new tests in
file_manifest. They exercise code that did not exist before, so they cannot compile against the parent commit — but each pins behavior that was absent:reconstruct_concatenates_chunks_in_order— output equals the concatenation, one fetch per chunk, in manifest order. The test chunk source yields at a real suspension point so the ordering assertion holds across genuine awaits.a_blob_without_the_magic_is_not_a_manifest— the raw-blob fallback, including a short blob and a near-miss 8th byte.magic_with_an_undecodable_body_errors_rather_than_falling_back— the fallback is not a blanket catch.parts_are_retained_by_default_and_reused/no_keep_blobs_deletes_parts— retention behavior both ways, including that a second run costs zero fetches.a_chunk_that_fails_blake3_aborts_reconstruction— and leaves no output file.sniffround-trip, version gate, andtotal_bytes-vs-chunk-sizes consistency.No ADR edit needed: ADR 012 already specifies this surface, including the
--no-keep-blobsflag name.Verification
🤖 Generated with Claude Code
Closes #1183