Repository navigation
fix(cli): harden DECDNMAN reconstruction after review of #1293 - #1301
Conversation
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]>
|
Warning Review limit reached
Next review available in: 11 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 (5)
WalkthroughManifest decoding and reconstruction now enforce stricter validation, use data-directory-relative download storage, reuse verified parts, validate output length before rename, and serialize reconstructions sharing a manifest hash. ChangesManifest reconstruction
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant PullCtx
participant FileManifestReconstruct
participant TokioBlockingPool
participant OutputPath
PullCtx->>FileManifestReconstruct: acquire manifest-hash lock and reconstruct
FileManifestReconstruct->>TokioBlockingPool: verify or write chunk parts
TokioBlockingPool-->>FileManifestReconstruct: return verified parts
FileManifestReconstruct->>OutputPath: validate total_bytes and rename output
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 introduces several robustness, security, and performance improvements to the file manifest decoding and reconstruction process. Key updates include resolving the downloads directory relative to the client's configured data directory, serializing concurrent reconstructions of the same manifest using a new locking mechanism, and implementing strict validation checks (such as limits on chunk counts, rejecting zero-size chunks, preventing path traversal in filenames, and catching trailing bytes). Additionally, blocking filesystem operations are now offloaded to Tokio's blocking thread pool to avoid executor stalls, and file length verification is performed prior to atomic renames. No review comments were provided, so there is no additional feedback to address.
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.
Coverage reportTotal: 81.51% (was 81.48%, ▲ +0.02%) — 49897/61219 lines
History
|
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]>
…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]>
…rocess (#1306, #1303) (#1336) * fix(cli): dedupe bundle-pull entries by hash + guard part dir cross-process (#1306, #1303) Two bundle-pull correctness bugs from the #1301 review, batched. - **#1306** — a bundle may hold one file's content at two paths (`ManifestEntry` carries `path` + `hash`, nothing dedupes by hash). Under `--no-keep-blobs` the first entry deleted its parts before the second ran, so the second re-fetched — and **re-paid for** — every chunk (a 100 GB file at two paths cost 200 GB), with nothing in the output saying so. `bundle pull` now fans out over *distinct blob hashes* (`group_by_hash` → `HashGroup`): `fetch_group` fetches/pays once, the first writable destination gets the materialized bytes, and every other is a hard link (or copy, on `EXDEV`) via `link_or_copy_atomic`. Covers raw and `DECDNMAN` entries alike, in both retention modes. Skip-existing/`--overwrite` stay per-destination (`plan_slots`). Deduped duplicates report a new `Linked` outcome so `fetched`/`total_bytes` count only paid pulls. - **#1303** — the per-manifest lock #1301 added was process-local, so two `decdn` invocations sharing a data dir still raced the shared part directory. `file_manifest::reconstruct` now holds a `rustix` exclusive `flock` on a persistent `<downloads_root>/<hex>.lock` (a sibling of the part dir, never inside it, so `--no-keep-blobs` cleanup can't take the lock target and reopen the race). The part dir is (re)created *inside* the locked region so a concurrent holder's cleanup can't strand a waiter on `ENOENT` mid-fetch. Dedup (in-process) + flock (cross-process) jointly retire the process-local `manifest_locks`. New workspace dep: `rustix` (features `fs`), already transitive. Docs: `appendix-bundles.md` § Pull dedup note; ADR 012 retention unchanged. Verified: 351 tests pass (10 new/updated), clippy `-D warnings`, fmt, rustdoc `-D warnings`, and `cargo deny` all clean. Closes #1306 Closes #1303 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(cli): use std cross-platform file lock, not Unix-only rustix flock Review (Gemini, Copilot): the #1303 lock used `std::os::fd::OwnedFd` + `rustix::fs` flock, which is Unix-only and would break the `x86_64-pc-windows-msvc` release build (release.yml builds decdn-cli → decdn.exe on windows-latest). PR CI is Linux-only, so it passed. Switch `acquire_part_lock` to `std::fs::File::lock` — stable since Rust 1.89 (MSRV here is 1.95), a cross-platform OS advisory lock (flock on Unix, LockFileEx on Windows). This gives a *real* lock on every release target rather than a Windows stub, and needs **no** third-party crate: the `rustix` direct dep is dropped entirely (workspace + cli), leaving the Cargo.lock change a net no-op vs main. The returned File is the lock guard; the OS frees it on drop/exit, so no staleness bookkeeping. Verified: 351 tests pass, clippy -D warnings, fmt, rustdoc -D warnings, cargo deny all clean; cli no longer depends on rustix/fs4. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Follow-up to #1293 (merged). A five-agent review — code quality, tests, error handling, type design, comments — ran against that PR; two findings (the dangling
appendix-bundles.mdanchor and the same-size-corrupt-part test) were already fixed before merge. This addresses the rest.Corruption residue on a failed reconstruction
concat_partsrenamed the output into place beforereconstructcompared its length tototal_bytes. When that guard fired the user was told the download failed while wrong bytes sat at the output path — andbundle pull's skip-existing (whose comment asserts "a present final file is verified-good") then skipped it forever on re-run.The check moved inside
concat_parts, before the rename. Note the guard is unreachable in normal operation: every part is size-checked anddecodealready provessum(chunk.size) == total_bytes, so only a part mutating between verification and concatenation trips it. That is precisely why it was worth fixing — a last-resort check whose failure mode publishes corrupt bytes defeats its own purpose, and the module already pins the opposite invariant for the BLAKE3 path (assert!(!out.exists(), "no output on a failed verification")).Manifest bounds at decode
Rejects >1M chunks, zero-size chunks, a
filenamethat is not a bare basename, and trailing bytes after the record.The chunk cap is a spending bound: every chunk is a separate paid sequential pull.
--max-blob-mb(default 1024 MiB) caps the manifest blob, but at ~34 bytes per encoded entry that still permits tens of millions of declared chunks. Zero-size chunks are worth rejecting specifically because the empty blob is trivially present in iroh-blobs, so those pulls always "succeed" — nothing throttles the resulting file-creation storm.filenameis unused today, which is exactly why the traversal class is cheaper to close now than to remember later.Blocking IO stalled concurrent bundle entries
part_is_verified(hashes up to a whole chunk) andconcat_partsran synchronously insideasync fn reconstruct, whilebundle pullpolls every entry from a single task (buffer_unordered, notokio::spawnbecauseprobe_onceis notSend). One large reconstruction blocked every sibling entry, and their stall deadlines are wall-clock timers that elapse while unpolled and fire the instant we yield — so healthy entries failed as "stalled". Both calls moved to the blocking pool.Shared part directories across entries
The part dir is keyed only on the manifest hash, and two bundle entries can name the same manifest (one file at two paths — entries are not deduped by hash). Concurrent reconstructions shared the directory: with
--no-keep-blobs, one entry's cleanup deleted parts while the other was mid-concatenate; without it, both fetched and paid for every chunk twice. Now serialized per manifest hash, which also makes the second entry reuse the first's verified parts and pay nothing. Cross-process reconstruction remains unguarded — noted rather than solved.Silent paid re-fetches
part_is_verifiedreturnedfalseon any IO error, so anEIOon a bad sector silently re-fetched — and re-paid for — a chunk on every run, against the promise retention is sold on. OnlyNotFoundis silent now; everything else warns, including right-size/wrong-hash, which is corruption rather than an interrupted write. The--no-keep-blobscleanup also didlet _ = remove_dir, hiding theENOTEMPTYcaused by the orphan.tmpthatwrite_blob_atomicstages inside the part dir; nothing GCs the downloads root, so that leak was permanent and silent.Part location honors --data-dir
downloads_root()hardcoded~/.decdn/downloadswhile--data-dir/identity.data_dirresolves to a client-scoped~/.decdn/client— so the largest thing the client writes ignored the user's explicit config. Both call sites already hold the resolved dir onResolvedChain. ADR 012 § Download flow amended accordingly.Comment corrections
update_readerrationale I added in 6619dcb claimed EINTR retry as the advantage overio::copy.std::io::copyretriesErrorKind::Interruptedtoo, so that was never the distinction — the real ones are the 64 KiB buffer sized for the hasher's block processing and skipping theWrite-impl round-trip. The change was right; my justification for it was not.versionfield).Deliberately not done
config-types::HashforChunkEntry.hash— its serde repr is a 64-char hex string, which would silently break the fixed postcard wire format (32 bare bytes).WireFileManifest/domain split or aChunkHashnewtype — correct in the abstract, ~40 lines of conversion boilerplate for apub(crate)module with two call sites.ChunkEntry.sizeis not redundant with BLAKE3: it is the only a-priori bound on bytes agreed to pay for, and it powers the cheap pre-hash rejection.Follow-ups filed separately
--no-keep-blobs, two bundle entries naming the same manifest each pay for every chunk (the first deletes the parts before the second runs). Not fixed here: ADR 012 pins that flag as deleting "immediately after reconstruction", so deferring the sweep is a deliberate ADR amendment rather than a review cleanup.decdninvocations sharing a data dir still race the same part directory.No test covers the per-chunk— I filed that as #1302 and have since closed it as wrong.ChannelContextrebuildcrates/e2e/tests/cli_fetch_manifest.rsalready assertslast_nonce >= chunks.len()after a real 3-chunk paid reconstruction, and a hoisted context would fail the fetch outright before reaching it. That test landed in the squash-merge of #1293, after the branch state the review ran against.Verification
Six new tests: chunk-cap, zero-size, trailing-bytes, filename-traversal, length-mismatch-leaves-no-output, and data-dir-relative parts root.
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes