Skip to content

fix(cli): harden DECDNMAN reconstruction after review of #1293 - #1301

Merged
thiras merged 3 commits into
mainfrom
feat/1183-manifest-review-fixes
Jul 19, 2026
Merged

thiras merged 3 commits into
mainfrom
feat/1183-manifest-review-fixes

Conversation

@yigitdot

@yigitdot yigitdot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

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.md anchor and the same-size-corrupt-part test) were already fixed before merge. This addresses the rest.

Corruption residue on a failed reconstruction

concat_parts renamed the output into place before reconstruct compared its length to total_bytes. When that guard fired the user was told 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 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 and decode already proves sum(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 filename that 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. filename is 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) and concat_parts ran synchronously inside async fn reconstruct, while bundle pull polls every entry from a single task (buffer_unordered, no tokio::spawn because probe_once is not Send). 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_verified returned false on any IO error, so an EIO on a bad sector silently re-fetched — and re-paid for — a chunk on every run, against the promise retention is sold on. Only NotFound is silent now; everything else warns, including right-size/wrong-hash, which is corruption rather than an interrupted write. The --no-keep-blobs cleanup also did let _ = remove_dir, hiding the ENOTEMPTY caused by the orphan .tmp that write_blob_atomic stages 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/downloads while --data-dir/identity.data_dir resolves 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 on ResolvedChain. ADR 012 § Download flow amended accordingly.

Comment corrections

  • The update_reader rationale I added in 6619dcb claimed EINTR retry as the advantage over io::copy. std::io::copy retries ErrorKind::Interrupted too, so that was never the distinction — the real ones are the 64 KiB buffer sized for the hasher's block processing and skipping the Write-impl round-trip. The change was right; my justification for it was not.
  • "separate magic" → the bundle manifest has no magic at all (JSON with a version field).
  • "the last one is partial" → not an invariant; an exact multiple of the chunk size ends on a full chunk.
  • ADR 012 step 3 said "delete part files", contradicting its own § Blob retention section directly below it.

Deliberately not done

  • config-types::Hash for ChunkEntry.hash — its serde repr is a 64-char hex string, which would silently break the fixed postcard wire format (32 bare bytes).
  • A WireFileManifest/domain split or a ChunkHash newtype — correct in the abstract, ~40 lines of conversion boilerplate for a pub(crate) module with two call sites.
  • ChunkEntry.size is 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 test covers the per-chunk ChannelContext rebuild — I filed that as #1302 and have since closed it as wrong. crates/e2e/tests/cli_fetch_manifest.rs already asserts last_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

cargo nextest run -p decdn-cli -p decdn-common --no-fail-fast
  Summary [2.381s] 735 tests run: 735 passed, 0 skipped
cargo clippy --workspace --all-targets -- -D warnings   # clean
cargo fmt -- --check                                    # clean
RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --document-private-items  # clean

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

    • Downloads now resume more efficiently by reusing verified chunk parts.
    • Downloaded files are assembled and validated before being published.
    • Download storage is located relative to the configured data directory.
    • Concurrent requests for the same manifest are coordinated to avoid duplicate work.
  • Bug Fixes

    • Added stricter manifest validation, including chunk limits, filename safety, and trailing-data rejection.
    • Prevented incomplete or incorrectly sized files from appearing as completed downloads.
    • Improved handling and reporting of invalid cached download parts.

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]>
@coderabbitai

coderabbitai Bot commented Jul 18, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@thiras, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 11 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: be5ebed7-ec26-413d-b0f6-0cd08183db12

📥 Commits

Reviewing files that changed from the base of the PR and between 8efb5e6 and 2565966.

📒 Files selected for processing (5)
  • adr/012-client.md
  • crates/cli/src/commands/bundle_pull.rs
  • crates/cli/src/commands/file_manifest.rs
  • crates/common/src/cli/fetch.rs
  • crates/e2e/tests/cli_fetch_manifest.rs

Walkthrough

Manifest 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.

Changes

Manifest reconstruction

Layer / File(s) Summary
Manifest validation contract
adr/012-client.md, crates/cli/src/commands/file_manifest.rs
Manifest decoding rejects trailing bytes, excessive or zero-sized chunks, and non-basename filenames; the ADR documents these constraints and resumable part handling.
Resumable reconstruction and atomic output
crates/cli/src/commands/file_manifest.rs, crates/cli/src/commands/fetch.rs
Reconstruction uses data-directory-relative storage, blocking filesystem operations, verified cached parts, and parent-directory temporary files; output length is checked before rename. Tests cover the new validation and output behavior.
Per-manifest reconstruction serialization
crates/cli/src/commands/bundle_pull.rs, crates/cli/src/commands/fetch.rs
Bundle pulls serialize reconstruction by manifest hash and pass the chain data directory to the downloads-root calculation.

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
Loading

Note

🎁 Summarized by CodeRabbit Free

Your 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 @coderabbitai help to get the list of available commands.

@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 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.

@github-actions

github-actions Bot commented Jul 18, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 81.51% (was 81.48%, ▲ +0.02%) — 49897/61219 lines

File Coverage Lines Δ
crates/cli/src/commands/bundle_pull.rs 25.51% 101/396 ▼ 0.66%
crates/cli/src/commands/fetch.rs 38.08% 286/751 ▲ +0.17%
crates/cli/src/commands/file_manifest.rs 93.37% 493/528 ▼ 0.85%
crates/common/src/cli/fetch.rs 100.00% 69/69 ● 0.00%
History
Commit Total Δ vs base
8efb5e6 81.74% ▲ +0.01%
739ea09 81.74% ▲ +0.01%
2565966 (HEAD) 81.51% ▲ +0.02%

yigitdot and others added 2 commits July 19, 2026 03:26
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]>
@thiras
thiras merged commit 62b206d into main Jul 19, 2026
23 checks passed
@thiras
thiras deleted the feat/1183-manifest-review-fixes branch July 19, 2026 16:48
thiras added a commit that referenced this pull request Jul 21, 2026
…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]>
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.

2 participants