Skip to content

feat(cli): bundle pull via chunk-hint range dedup (whole-file blobs) - #1982

Merged
alpergundogdu merged 30 commits into
mainfrom
claude/bundle-pull-parallel-chunks-54c2bc
Sep 14, 2026
Merged

alpergundogdu merged 30 commits into
mainfrom
claude/bundle-pull-parallel-chunks-54c2bc

Conversation

@alpergundogdu

@alpergundogdu alpergundogdu commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Reworks decdn bundles so that chunks are client-side range-dedup hints, not stored/served blobs — fixing why chunk-dedupped (--optimize) pulls were slow and node-storming.

The original slowness was per-chunk round-trips: each chunk was a separate cdn/client/v1 blob (probe + QUIC open + signed StreamRequest/StreamResponse + voucher per chunk), so a ~13.7 GB model was ~3,400 round-trips. This branch replaces that with whole-file range pulls plus client-side dedup.

What changed

  • origin import --optimize now stores each file as ONE whole-file blob (+ .obao4 outboard) — range-servable, exactly like a plain import — and emits the manifest's chunks list as advisory {hash, size} hints. No chunk blobs are stored; a chunk hash is not independently addressable; nodes serve whole files only.
  • bundle pull fetches a chunked entry by pulling only the complement of the ranges it already holds this run (sub-range drive, bao-verified against the whole-file hash), splicing the held ranges in locally (each verified by re-hashing the whole donor chunk against its hint hash), and promoting on a whole-file BLAKE3 == manifest hash check. A wrong/lying hint self-heals by re-fetching; it can never corrupt output.
  • The per-chunk fetch path is deleted; the shared-LaneLedgers payment concurrency (this branch's earlier work) is kept and now governs concurrent whole-file fetches. --jobs default lowered to 4.
  • adr/appendix-bundles.md rewritten to the hint model. No wire/contract/node-serve change.

Trust / money-safety

Complement ranges are bao-verified against the whole-file hash at their true positions; donor splices are chunk-hash verified; the whole-file BLAKE3 is the sole promotion gate. drive_ranges persists the lane voucher watermark, so a resumed/failed pull never re-pays, and shared bytes are never paid for twice.

Testing

  • Unit: complement_runs, plan_dedup/hints_of, and the splice byte-path (splice_donors/chunk_verified/copy_exact/hash_partial) including a corrupted-donor→refetch case.
  • anvil e2e cli_bundle_pull_range_dedup: an optimized bundle with a shared aligned run pays wire(A) + wire(B_complement) — the shared range is spliced locally, not re-downloaded — plus a lying-hint self-heal test (verified to fail without the fix).
  • Full workspace cargo nextest 3426 passed / 0; clippy --all-targets --all-features -D warnings, doc gate, cargo deny clean.

Known follow-ups (v1 scope)

  • Cross-pull / same-output-dir dedup is out of scope (v1 dedups within one run).
  • Optimized pulls hold ~2× the bundle on disk until the run-end staging sweep (parity with the old path); hard-linking the first materialize is a follow-up.

🤖 Generated with Claude Code

alpergundogdu and others added 10 commits September 10, 2026 18:14
…ource_fetch

multi_source_fetch takes an optional run-wide LaneLedgers registry. When
present, the deposit gate's spent/credit span every lane the bundle-pull
run has registered, not just this fetch's own lanes, so concurrent fetches
sharing a deposit gate correctly. When absent, behavior is unchanged: the
gate folds over only this fetch's lanes, as a solo `decdn fetch` always did.
…lane deposit on reuse

Code-review fixes for bundle-pull-parallel-shared-ledger:

- bundle_pull.rs: pull_plain/pull_chunked's outer streams were widened to
  buffer_unordered(len), instantiating one live progress bar per manifest
  entry/group before it ever acquires PullCtx.gate — a terminal-flooding
  regression on large bundles. Re-bound both outer streams at --jobs (new
  PullCtx.jobs field) while leaving the inner per-chunk stream and the
  global gate untouched, so a many-chunk file still saturates --jobs.

- fetch.rs: lane_ledger discarded a freshly-built PoolContext on a
  registry-reuse touch, even when open_or_reuse_pool had just performed a
  low-water top-up raising the on-chain deposit above the registry's
  stored value. The pool-wide spent/credit gate reads that stale value and
  could refuse (PoolExhausted) prematurely. Reconcile the shared handle's
  ctx.deposit upward to the fresher reading on every touch (a no-op when
  the touch's own build won the registry race).

- bundle_pull.rs: drop stray changelog-voice "now" from two comments.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Copilot AI lite review requested due to automatic review settings September 10, 2026 20:11

Copilot AI 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.

🟡 Changes recommended

Chunked-file fan-out currently buffers one future per chunk (buffer_unordered(chunks.len())), which can cause avoidable memory/scheduling blowups on very large chunked files despite the semaphore already bounding real I/O concurrency.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

This PR makes decdn bundle pull truly parallel by introducing a run-scoped per-lane voucher-ledger registry so concurrent pulls on the same (pool_id, signer, provider) lane share one monotonic issuer, while also enforcing a pool-wide “spent” view to prevent concurrent disjoint-lane fetches from over-issuing against a single deposit.

Changes:

  • Add LaneLedgers registry ((pool_id, signer, provider) -> LaneHandle) and thread it through both multi-source and single-source fetch paths so lanes share one Arc<PoolLedger> + shared context.
  • Replace bundle-pull serialization with a global --jobs semaphore gating all blob fetches (whole blobs and chunks), and fan out chunks within a file concurrently.
  • Update CLI docs/defaults (--jobs default 4 → 16) and add unit + anvil e2e coverage for the new concurrency/payment invariants.
File summaries
File Description
crates/e2e/tests/cli_bundle_pull_concurrent_chunks.rs New anvil-backed e2e validating concurrent chunk assembly and exactly-once payment watermarking.
crates/common/src/cli/bundle.rs Redefines --jobs as global concurrent blob-fetch cap and raises default to 16.
crates/client-pull/src/scheduler.rs Adds optional LaneLedgers to enable pool-wide spent/credit across a run; adds unit test for pool-wide gating.
crates/client-pull/src/lib.rs Exposes new ledgers module and re-exports registry types.
crates/client-pull/src/ledgers.rs Implements the run-scoped (lane -> ledger+ctx) registry plus helpers (total_committed, credit_all) with unit tests.
crates/cli/src/commands/fetch.rs Threads optional registry into fetch/drive paths and uses registry-backed pool-wide gating when present.
crates/cli/src/commands/bundle_pull.rs Removes per-lane locks + pool-serial mutex; adds global semaphore gate; enables per-file chunk fan-out under --jobs.
Review details
  • Files reviewed: 7/7 changed files
  • Comments generated: 1
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread crates/cli/src/commands/bundle_pull.rs Resolved
alpergundogdu and others added 2 commits September 10, 2026 22:51
…at --jobs

Merging main brought in a new multi_source_fetch test caller (PR #1978) that
predates the ledgers parameter; pass None there. Also bound the per-file chunk
stream at --jobs (buffer_unordered) so a file with very many chunks no longer
buffers one future per chunk — the global gate is the real in-flight-fetch cap
(addresses the Copilot review note).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alpergundogdu

Copy link
Copy Markdown
Contributor Author

Addressed the review + a merge-integration fix in bb907f8:

  • Copilot note (chunk fan-out buffering one future per chunk): the per-file chunk stream is now buffer_unordered(self.jobs.min(chunks.len())) instead of chunks.len(). The global --jobs semaphore (PullCtx.gate) remains the real in-flight-fetch cap, so a file with very many chunks no longer buffers a future per chunk while still saturating --jobs.
  • CI red (clippy/test): these were building the PR-merge-with-main. main had advanced 11 commits, including a new multi_source_fetch test caller (fix(client-pull): surface resume base on the progress bar before the first chunk #1978) that predates this PR's ledgers parameter. Merged main in and passed None at that call site.

Green locally after the merge: full workspace cargo nextest 3404 passed / 0 failed, clippy --all-targets --all-features -D warnings, doc gate, and cargo deny all clean.

@github-actions

github-actions Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 82.65% (was 82.78%, ▼ 0.13%) — 77690/93997 lines

File Coverage Lines Δ
crates/cli/src/commands/bundle_pull.rs 58.81% 1325/2253 ▲ +3.97%
crates/cli/src/commands/chunker.rs 93.42% 213/228 ● 0.00%
crates/cli/src/commands/fetch.rs 42.63% 1030/2416 ▼ 0.65%
crates/cli/src/commands/manifest.rs 96.19% 379/394 ● 0.00%
crates/cli/src/commands/origin.rs 85.14% 573/673 ▼ 0.22%
crates/cli/src/commands/pull_progress.rs 71.48% 198/277 ▼ 8.78%
crates/cli/src/main.rs 78.85% 41/52 ● 0.00%
crates/client-pull/src/ledgers.rs 98.37% 121/123 new
crates/client-pull/src/lib.rs 89.07% 1720/1931 ● 0.00%
crates/client-pull/src/scheduler.rs 94.04% 1924/2046 ▲ +0.20%
crates/common/src/cli/origin.rs 100.00% 32/32 ● 0.00%
History
Commit Total Δ vs base
bb907f8 82.67% ● 0.00%
2379f57 82.60% ▼ 0.11%
9985f4c 82.60% ▼ 0.11%
757b087 82.63% ▼ 0.08%
1551959 82.60% ▼ 0.14%
0689d9e 82.60% ▼ 0.13%
18542be 82.64% ▼ 0.14%
c98f2a7 (HEAD) 82.65% ▼ 0.13%

alpergundogdu and others added 9 commits September 11, 2026 13:56
…ints

Flip --optimize to store each file as one whole-file blob + its .obao4
outboard, exactly like a plain import, and emit the chunk list only as
manifest dedup hints. Previously --optimize stored per-chunk blobs and
left the whole-file blob unstored; nodes serving whole files (already
supported) is what makes client-side range dedup possible later.

import_optimized_file streams the file twice: import_one_file writes
the whole-file blob once, then a no-op-sink chunk_file pass computes
the hint list, with its whole_hash/total_size cross-checked against
the written blob to catch a concurrent-modification read race.

Drops the chunks_written status counter (there is no longer a
dedup-storage count to report); chunks_total is now the chunk-hint
count. Updates the existing optimize integration tests to assert
whole-file storage instead of per-chunk storage.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…zed partial

Adds the two client-side primitives the range-dedup hints work needs:
complement_runs (pure range math, unit-tested) turns a donor's covered
byte ranges into the gaps still worth a paid pull, and drive_ranges
opens a blob's pool + ranged store once and drives a set of ranges
into its .partial without finalizing, so a later assembly step can
promote it once donor bytes fill the rest.

Factors drive_fetch's handshake/store-open/source-build prelude into
open_fetch_prelude so both functions share it instead of duplicating
it; drive_fetch's own tests continue to pass unchanged, confirming the
refactor is behavior-preserving.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Treat a bundle entry's chunk list as a range-dedup hint rather than a
per-chunk fetch plan. Every entry is fetched and verified by its
authoritative whole-file BLAKE3; when a chunk it names is already
materialized on disk by a sibling entry this run, the fetch pays only for
the complement (the group-aligned bytes no donor covers) and splices the
rest from the sibling's finalized blob.

- `pull_entry` replaces the per-chunk `pull_chunked`/`pull_chunked_file`
  path: plan the dedup against a run-wide `ChunkIndex`, drive only the
  complement into the entry's `.partial`, splice each donor range after
  re-hashing the whole donor chunk against its hint hash (a lying donor
  hint or short read falls back to a paid re-fetch), then verify the
  reassembled `.partial` against the whole-file hash. A lying recipient
  hint (wrong placement) is caught by that check and recovered by
  re-driving the full blob.
- `drive_ranges` now persists the lane's voucher watermark once its
  ranges are driven, exactly as `drive_fetch` does (committed on success,
  settlement HIGH on ambiguous failure), so a failed or resumed chunked
  pull never re-pays a byte already bought.
- Delete the per-chunk path (`ChunkCell`, `ChunkedPlan`, `plan_chunked`,
  `assemble_plan`, `parse_chunk_hashes`, `assemble_chunks`, the chunked
  progress-bar API) and unify `pull_all` on one by-hash grouping through
  `pull_entry`. A donor's finalized staging blob is kept until the run
  ends, then swept.
- Remove the per-chunk-blob shared-chunk e2e; its premise (chunk as
  standalone blob) is gone. A range-dedup e2e lands in a later task.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add pure unit tests for splice_donors/chunk_verified/copy_exact/
hash_partial: a happy-path subset copy that lands the correct bytes
at the recipient offset with an empty refetch list, a corrupted-donor
case that is pushed to refetch with no bytes written, plus direct
chunk_verified/copy_exact/hash_partial coverage. Verified the
corrupted-donor test genuinely bites by temporarily short-circuiting
chunk_verified to always return true (test failed as expected), then
reverted.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
An optimized bundle stores each file as one whole-file blob; its
manifest chunks list is an advisory range-dedup hint, never a
separately stored or fetched blob. Rewrite appendix-bundles.md's
Chunked files/Generation/Pull sections in present-tense ASD-STE100 to
match, and sweep stale comments in manifest.rs, chunker.rs, and
bundle_pull.rs that still described chunks as stored/served/
concatenated blobs.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…of re-downloading

Two files sharing a 4 MiB chunk-group-aligned run are pulled from one node
in a single `decdn bundle pull` invocation. Asserts byte/BLAKE3-exact
output, that the shared lane bills exactly the first file's whole-file
wire size plus the second file's complement wire size (strictly less than
re-downloading both whole files), and that a lone non-overlapping file
bills exactly its whole-file wire size (dedup parity).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
On the range-dedup self-heal paths, re-driving ranges that complete the
blob lets `drive` finalize and rename `<hex>.partial` -> `<hex>`, after
which `hash_partial`/`promote_partial` operate on a `.partial` that no
longer exists and the entry fails spuriously even though `drive` already
bao-verified the whole blob against the manifest hash.

Guard both self-heal re-drives (the all-donors-corrupt refetch and the
whole-file-mismatch `[(0,total)]` re-drive): if the finalized `staging`
now exists, the blob is verified and promoted, so register the donor
chunks and return `Ok` instead of hashing an absent `.partial`. The
happy dedup path (complement-only drive) never completes the blob, so
`staging` does not exist there and the splice+hash+promote flow is
unchanged.

Add an anvil e2e that arms the self-heal with a lying recipient hint (a
real donor chunk placed where the recipient's bytes differ, so the
donor splice verifies but the whole-file BLAKE3 mismatches). It runs the
measured pull single-shot so the serve-race retry loop cannot mask the
bug; without the guard it fails with `open <hex>.partial: No such file`.

Also soften the `downloaded` metric docs (range-dedup does not lower it
below `reconstructed` on a single-path blob) and note the ~2x staging
disk retention until the run-end sweep.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…rallel-chunks-54c2bc

# Conflicts:
#	crates/cli/src/commands/pull_progress.rs
@alpergundogdu alpergundogdu changed the title feat(cli): parallel bundle pull via shared per-lane voucher ledger feat(cli): bundle pull via chunk-hint range dedup (whole-file blobs) Sep 11, 2026
Add cli_bundle_pull_from_optimize_import_dedups: runs the real `decdn
origin import --optimize` over an on-disk source tree (pinning
--chunk-avg/--chunk-min/--chunk-max to fastcdc's MINIMUM_MAX so the
chunker degenerates to fixed-size cuts landing on the shared/tail
seam), asserts the import wrote whole-file blobs + outboards (and no
separately-stored chunk-hash objects), serves the import store's
actual bytes (manifest + both whole files) from a NodeFixture, and
`bundle pull --hash`es the import-emitted bundle hash. Closes the gap
where the existing range-dedup e2e seeds whole-file blobs directly and
hand-builds the manifest, never exercising the import -> hint -> pull
seam.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

Copy link
Copy Markdown
Contributor Author

Correctness review (head 9985f4c)

Three bugs in the bundle_pull.rs dedup path can fail or re-pay an entry that was already verified and paid for, plus one progress regression and three smaller items. Suggested fixes inline.

🔴 1. Resumed dedup run fails after the complement drive finalizes the blob

pull_entry → drive_ranges_failover(hash, staging, &plan.complement, …) promotes <hex>.partial → <hex> whenever the ranged store reports complete. On a resumed run whose .partial/.ranges already hold the bytes that overlap the donor chunks (run 1 with --jobs 2: recipient B started before donor A registered, took the plain path, and was interrupted; run 2: A registers, B now plans donors), the complement drive completes the store, finalizes, and splice_donors then OpenOptions::open(<hex>.partial) → ENOENT → every path in the group is marked Failed. The staging.try_exists() guard only sits after the refetch / whole-blob re-drives, not after this first drive.

Fix: guard the first drive the same way, before spawning the splice:

self.drive_ranges_failover(hash, staging, &plan.complement, progress).await?;
// The store may already have held the donor-overlap bytes (a resumed run); the
// drive then finalized and there is nothing left to splice.
if staging.try_exists()? {
    index.register(hints, staging);
    return Ok(());
}
let partial = partial_path(staging);

🔴 2. A mismatched hint length is a hard, deterministic failure instead of a re-fetch

plan_dedup never compares the recipient's h.len against the donor's registered m.len, and chunk_verified only checks the donor's own [m.offset, m.offset+m.len). A stale or lying recipient hint with a longer len yields src_offset + alen past the end of the donor file; copy_exact hits UnexpectedEof and splice_donors returns Err via ?, so pull_entry fails the whole entry on every rerun while A stays registered. The appendix promises a bad hint only costs a re-download.

Fix (both halves): skip mismatched donors at plan time, and treat a copy error as "untrusted, re-fetch" rather than fatal:

// plan_dedup
let Some(m) = index.get(&h.hash) else { continue };
if m.len != h.len {
    // Same chunk hash, different claimed length: one side is lying. Pay for it.
    continue;
}
// splice_donors — replace the three `?`s in the copy with a refetch push
let copied = src
    .seek(SeekFrom::Start(d.src_offset))
    .and_then(|_| out.seek(SeekFrom::Start(dst_offset)))
    .and_then(|_| copy_exact(&mut src, &mut out, len));
if copied.is_err() {
    refetch.push(d.aligned);
}

(If the partial write left a torn range behind, the refetch drive overwrites exactly d.aligned, bao-verified, so nothing stale survives.)

🔴 3. Run-end sweep deletes a paid blob whose group failed to materialize

fetch_group skips remove_staging for a donor group regardless of any_failed, and pull_all then unconditionally remove_staging()s every index.sources(). A donor group whose materialize failed (ENOSPC, unwritable dir) loses its finalized <hex>, so the rerun re-drives and re-pays the entire blob. That is exactly the case the comment above should_remove_staging says must never happen.

Fix: have fetch_group report whether its staging must survive, and skip those sources in the sweep. Simplest shape: a Mutex<HashSet<PathBuf>> on ChunkIndex (say retain) that fetch_group inserts into when is_donor && any_failed, then:

for source in index.sources() {
    if index.retained(&source) { continue; }
    remove_staging(&source);
}

🟡 4. Progress bars stop short of 100% on a dedup pull

drive reports base_present + received where base_present counts only bao-verified present ranges; spliced donor bytes never enter the present record. A file with 60 % spliced ends its file bar at 40 %, and content_contributor credits the total bar with only that fraction. The deleted ChunkedFile::finish true-up (total.inc(size - last)) has no counterpart in FileBar::finish.

Fix: on success, pull_entry (or fetch_group after Ok) calls the callback once with (total, total); alternatively give FileBar::finish a finish_complete(size) variant that pushes the remaining delta into the total bar, mirroring credit_skipped.

🟡 5. Three probe rounds per dedup entry

Each drive_ranges_failover call re-runs probe_and_order over every candidate plus a throwaway header handshake. A dedup entry can call it three times (complement, refetch, whole-blob re-drive). Resolve the candidate order once in pull_entry and pass it into a helper that only re-dials.

🟢 6. --jobs help text is stale (crates/common/src/cli/bundle.rs)

It still says "whole-file entries and chunks of a chunked file alike … a chunk shared between files is fetched once and does not consume an extra slot". After this PR a chunk is never a fetch unit and one entry holds exactly one permit. Suggested:

/// Maximum concurrent entry fetches across the whole run. A range-dedup entry
/// holds one slot for its complement drive, donor splice, and any re-fetch.

🟢 7. should_remove_staging is now !any_failed

With the keep set gone the const fn only obscures the call site; inline it and drop its unit test.


Generated by Claude Code

A chunk is no longer a fetch unit; each distinct blob is one unit of work
holding one --jobs slot across its complement drive, donor splice, and any
re-fetch. Rewrite the stale help text (present tense) to match (PR #1982 review
item 6).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ress

Address PR #1982 review (money-band correctness on the bundle chunk-hint
range-dedup path). All in crates/cli/src/commands/bundle_pull.rs.

- #1 (resume): after the FIRST complement drive, check staging.try_exists() and
  return success when the drive finalized the blob (a resumed run whose .partial
  already held the donor-overlap ranges) instead of opening a now-renamed
  .partial and failing the entry. Same guard shape already used after the refetch
  and whole-blob re-drives; now covers all three. The dedup reassembly is
  extracted into reassemble_dedup over a RangeDriver trait so this seam is
  unit-testable without a live endpoint or pool.
- #2 (bad hint = re-download, never fail): plan_dedup skips a donor whose
  registered length disagrees with the recipient's claimed length (leaves the
  range in the paid, bao-verified complement); splice_donors treats a per-donor
  seek/copy error (a mismatched span or truncated donor that would EOF) as
  untrusted -> refetch rather than a fatal error.
- #3 (never re-pay a paid blob): a donor group whose blob is fetched and
  registered but whose materialize failed is mark_retained on the ChunkIndex, and
  the run-end sweep skips retained sources, so a rerun resumes from the finalized
  <hex> instead of re-driving and re-paying the whole blob.
- #4 (progress): on any dedup-path success, true the file + total bars up to 100%
  (spliced donor bytes never flow through drive's progress callback). Monotonic,
  so paths already at 100% are unaffected; the plain-entry path is untouched.
- #5 (one probe per entry): resolve the range-drive provider order once per dedup
  entry and thread it into every sub-drive, so a self-heal entry no longer
  re-probes up to 3x. Happy path still probes once.
- #7: inline should_remove_staging (now just !any_failed), reconciled with #3.

Regression tests (each shown to bite pre-fix): reassemble_dedup succeeds when the
first drive finalizes (#1); plan_dedup skips a length-mismatched donor and
splice_donors refetches an EOF-ing copy (#2); the run-end sweep keeps a retained
donor and removes a normal one (#3). cli unit suite green; the anvil e2e
(cli_bundle_pull_range_dedup, incl. self-heal) passes, confirming the extraction
is behavior-preserving.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alpergundogdu

Copy link
Copy Markdown
Contributor Author

All seven addressed in 6871b4b8 (help text) + 757b0874 (the rest). Each 🔴 came with a regression test verified to bite (revert→fail, restore→pass) — these were invisible to the suite before.

  • 🔴 1 — resumed run fails after the first complement drive finalizes. Added the same staging.try_exists()? { register; return Ok } guard after the first complement drive, matching the two existing guards. The dedup reassembly is extracted into reassemble_dedup over a RangeDriver trait so the "first drive finalizes the blob" path is unit-testable at the store seam without a live pool (test reassemble_dedup_succeeds_when_the_first_drive_finalizes_the_blob). A deterministic first-complement-finalize is not stageable against a whole-blob-only NodeFixture, hence the unit test rather than e2e; the sibling whole-blob guard stays e2e-covered.
  • 🔴 2 — mismatched hint length was fatal. plan_dedup now skips a donor whose m.len != h.len (the range stays in the complement and is paid for); splice_donors turns a seek/copy error into refetch.push(d.aligned) instead of ?, so the range is re-fetched bao-verified. A bad hint costs a re-download, never a failure. Tests: plan_dedup_skips_a_length_mismatched_donor, splice_donors_refetches_when_a_copy_would_run_past_the_donor_end.
  • 🔴 3 — sweep could delete a paid, unmaterialized donor blob. ChunkIndex gains a retain set; fetch_group marks is_donor && any_failed, and the run-end sweep skips retained sources. Test run_end_sweep_keeps_a_retained_donor….
  • 🟡 4 — bars stopped short on dedup. finish_progress trues the file + total bars to 100% on dedup success (monotonic; plain path and the fix(cli): stop bundle-pull total bar tearing and fix its denominator #1974 content denominator untouched).
  • 🟡 5 — three probe rounds. resolve_range_targets probes once per entry; drive_ranges_ordered re-dials the pre-resolved order for the refetch/whole-blob sub-drives. Happy path is still one probe.
  • 🟢 6 — --jobs help rewritten: one permit per entry, no chunk-as-fetch-unit language.
  • 🟢 7 — should_remove_staging inlined to !is_donor && !any_failed, its test dropped, reconciled with the docs: convert ASCII art schemas to Mermaid diagrams #3 retain set.

Green: cargo nextest -p decdn-cli 650, anvil e2e cli_bundle_pull_range_dedup 3/3, clippy --all-targets --all-features -D warnings, fmt, doc gate. The reassembly refactor is behavior-preserving — the whole-file BLAKE3 stays the sole promotion gate and no payment/watermark logic changed.

@yigitdot

Copy link
Copy Markdown
Contributor

Review (5-agent pass: code, tests, silent failures, docs, type design)

Design is sound: donor chunks are re-hashed before splice, complement ranges are bao-verified at their true positions, the whole-file BLAKE3 is the sole promotion gate, splices never enter .ranges, and retry depth is bounded. The problems are at the edges — two verified double-pay paths, a hole in the self-heal promise, and docs/help text that still describe the deleted per-chunk-blob model. Line numbers are PR-side (9985f4c).

Critical

  1. Missing finalize guard after the complement drive — crates/cli/src/commands/bundle_pull.rs:1298-1311. drive finalizes whenever the store becomes complete (driver.rs:477). The refetch drive (1320) and whole-blob re-drive (1347) guard with staging.try_exists(); the first complement drive does not. Scenario: an interrupted run leaves recipient B at ~95% (.partial + .ranges); the rerun plans a dedup, the complement drive completes the store → finalize renames .partial → staging and drops the sidecars → splice_donors open(partial) → NotFound → entry Failed. Third run: staging exists, .ranges is gone → open_or_create → create → the whole blob is downloaded and paid again. Fix: the same guard after the complement drive (if staging.try_exists()? { index.register(hints, staging); return Ok(()); }), plus a test that seeds a checkpointed .partial (seed_checkpointed_prefix) whose coverage ∪ complement completes the blob.

  2. Run-end sweep deletes a paid donor blob whose materialize failed — bundle_pull.rs:1199-1201 vs 1494-1499. fetch_group keeps a donor staging on any_failed precisely to avoid re-payment, then pull_all sweeps every index.sources() unconditionally. ENOSPC on a 5 GB hinted entry → finalized blob deleted → rerun pays again. Fix: record a per-source keep flag in ChunkIndex (set from any_failed) and sweep only fully-succeeded sources, or register donors after materialize succeeds.

  3. Recipient hint size ≠ donor chunk length → hard I/O failure, not self-heal — plan_dedup (bundle_pull.rs:1688-1711) spans the donor with the recipient h.len but verifies the donor m.len, never checking they agree; splice_donors:1755-1760 then ?s the copy_exact short read and the entry fails. Contradicts "a wrong/lying hint self-heals by re-fetching". Fix: if m.len != h.len { continue; } in plan_dedup, and treat a copy_exact failure as refetch.push(d.aligned). Unit test: A=[(H,1MiB),(T_a,200K)], B=[(H,2MiB),(T_b,200K)] (passes hints_of).

  4. Self-heal e2e does not observe the self-heal path — crates/e2e/tests/cli_bundle_pull_range_dedup.rs:446-455. billed_bytes is cumulative and the warm-up (389-405) already satisfies paid >= wire(A)+wire(B); if plan_dedup stopped producing donors, B would be fetched plain and the test would still pass. Fix: snapshot billed_bytes after the warm-up and assert the delta equals exactly wire_whole(A) + range_wire(SHARED,TAIL,total_b) + range_wire(0,SHARED,total_b) (the range_wire_bytes helper is already proven exact by the sibling test at 259-270). Also make run_bundle_pull_until_ready fail on any failed: stderr line that is not the known serve race, so a spurious first attempt (finding 1) cannot be absorbed and re-paid on retry.

Important

  1. False "no-ops" comment on an already-promoted staging blob — bundle_pull.rs:1264-1267 (new) and 1481-1489. ClientRangedStore::open_or_create is keyed on .ranges alone (ranged_store.rs:335-355); a finalized staging file with no sidecars is truncated and re-downloaded. This is what turns findings 1/2 (and any crash between promote_partial and materialize) into a silent double-pay. Either short-circuit pull_entry when staging exists (hash once, materialize) or delete the claim.

  2. Latent lock-order inversion — LaneLedgers::credit_all (ledgers.rs:69-82) takes map → ctx; driver.rs:852-856 holds a lane ctx guard and calls spent() → total_committed → map. Safe today only because every fetch future is polled on one task, but PullCtx (bundle_pull.rs:640-642) advertises "safe to share across tokio::spawn". Fix: clone handles out under the map lock, drop it, then lock ctxs. Also credit_all errors on poison while get_or_insert/total_committed recover — pick one.

  3. User-visible help text describes the deleted model — crates/common/src/cli/origin.rs:110-112 (--optimize: "write each chunk as its own blob"), :106 (--json shape still lists chunks_written, which ImportReport no longer has), crates/common/src/cli/bundle.rs:69-72 (--jobs: "chunks of a chunked file … a chunk shared between files is fetched once" — a chunk is never fetched; one permit per hash group).

  4. Orphaned doc fragment — crates/cli/src/commands/pull_progress.rs:166-167: the first two lines of the deleted chunked_file doc now head credit_skipped.

  5. ADR contradictions — adr/appendix-bundles.md:242-246 describes the per-provider lock this PR deletes; :285-291 says the downloaded → reconstructed line reflects shared chunks, but PullReport (bundle_pull.rs:342-350) says downloaded counts the whole size; :206-208 says hints are computed over the whole directory, but import_optimized_file chunks each file alone (cross-file recognition happens at pull time by hash equality). Also stale on main because of this PR: adr/022-content-discovery.md:161,134 (chunk-blobs "independently discoverable") and adr/039-multi-source-parallel-fetch.md:56 (provider_lock; also ADR 039 says two concurrent streams on one lane cause BadSignature, while bundle_pull.rs:20-24,843-849 says same-lane concurrency is fine under a shared ledger — one of them is wrong).

  6. Changelog voice (CLAUDE.md rule) — bundle_pull.rs:1197 "parity with the prior chunked path"; fetch.rs:2018 "exactly as before"; manifest.rs:45 "predates chunk hints"; scheduler.rs:965 "as a solo fetch always has", :2376 "the OLD way"; cli_bundle_pull_range_dedup.rs:2,9,13,289-297 reference a plan/task number, a review finding, "the deleted cli_bundle_pull_shared_chunk.rs", and "previously-uncovered … Before the finalize-aware guard". Working-spec and review-round references stay out of the repo.

  7. Stale "chunk fetch" wording and a broken drive_ranges contract — ledgers.rs:3-4, bundle_pull.rs:671-672,348,367,1166-1168, fetch.rs:1762,1920,2141 still talk about chunk fetches. fetch.rs:2131-2143 says drive_ranges leaves .partial unfinalized and expects "a proper subset" — false for two of its three callers (which then rely on it having finalized) — and "returns the store so the caller can read verified ranges" while every caller discards it. crates/cli/tests/origin_import.rs:688-692 rationale for rejecting --optimize --move contradicts origin.rs:159-166.

  8. Silent money outcomes — the CLI installs no tracing subscriber by default (crates/cli/src/logging.rs), so the warn!/debug! at bundle_pull.rs:1336-1340,1661-1666 are no-ops; parse_hash(..).ok()? (1652) and checked_add(..)? (1658) drop hints with no signal at all; donor refetch (1744-1752) is silent. A bundle whose hints all lie pays exactly what an unhinted bundle pays and prints an identical summary and --json. Add an eprintln! per ignored-hint / self-heal event and a hints_ignored / spliced_bytes tally in PullReport.

  9. Progress bar never credits spliced bytes — bundle_pull.rs:1363-1373; a dedup run ends short of 100%. advance_reused tests were deleted with no replacement.

Suggestions

  • Manifest size is never reconciled with header.total_bytes (bundle_pull.rs:1268-1278,1341,1355): an understated size makes the "full re-fetch" not full and the bail message misleading. Keep the store from drive_ranges_failover and bail early on mismatch.
  • ByteRun { offset, len } newtype: complement_runs:1898-1916 uses (u64,u64) as both (offset,len) and (start,end) in one function. bao_range::AlignedRange is the existing pattern; DonorRange::new(..) -> Option would close finding 3 structurally.
  • drive_ranges → return enum { Finalized, Partial } instead of three try_exists probes; also removes the dead store return.
  • LaneHandle constructor deriving the key from ctx (fetch.rs:1910,2136,2189 rebuild it by hand); topups_used lives per-FetchPrelude, so one bundle entry gets a fresh top-up budget per drive_ranges call (up to 3x).
  • Option<&LaneLedgers> as a mode selector forces the spent/credit Option pair in FetchPrelude (fetch.rs:1853-1854) whose both-or-neither invariant is unenforced; a solo fetch could just build a one-lane registry.
  • chunk_files sink parameter is dead API (every caller passes a no-op). ImportCtx { optimize: bool, sizes: Option<..> } → optimize: Option<ChunkSizes> makes the two internal: bails unrepresentable.
  • Test gaps: complement_runs_coalesces_unsorted_overlapping_donor uses abutting, not overlapping, ranges; no test for an all-donor empty complement, a missing/short donor file, multi-donor with one bad, --jobs >= 2 on the dedup path, or an interrupted-then-resumed dedup pull (the money claim in the PR body).
  • ADR STE: adr/appendix-bundles.md:263-279 are 60-word sentences with em-dashes; split.
  • PR body says --jobs was "lowered to 4" — main already has default_value_t = 4.

Strengths

  • The trust boundary is right, and spliced bytes never land in .ranges, so a crash mid-splice cannot make a later run trust unverified bytes.
  • The dedup e2e computes its expected watermark from the same align_range / bao_encoded_size primitives the node meters with — exact, not >=.
  • splice_donors tests assert what was not written.
  • pool_wide_spent_gates_on_other_run_lanes covers exactly the shape the old per-fetch fold would have missed.
  • The --optimize import e2e reads served bytes back from the store rather than the in-memory originals.

🤖 Generated with Claude Code

alpergundogdu and others added 5 commits September 14, 2026 11:07
…den self-heal test

Address the still-live code findings from the second review of the bundle
chunk-hint range-dedup path (money-band).

Critical-4: the self-heal e2e asserted a cumulative `paid >= wire_min` that
the warm-up already satisfied, so it could not tell the self-heal path from a
plain fetch. Snapshot the lane watermark after the warm-up and assert the
measured run's EXACT delta: a's whole file plus b's complement plus b's
re-driven head. Harden `run_bundle_pull_until_ready` to bail on a
non-transient reconstruction fault instead of absorbing (and re-paying for)
it via the serve-race retry.

Important-5: an already-finalized `<hex>` staging blob has no `.ranges`
sidecar (promotion deletes it), so re-driving it would `open_or_create` ->
`create` -> truncate and re-pay for the whole blob. `pull_entry` now hash-
verifies an existing staging once and materializes from it, never re-driving.
The misleading "no-op" comment is corrected to the real invariant.

Important-6: `LaneLedgers::credit_all` locked each lane `ctx` while holding
the map lock — the inverse of the driver's ctx-then-map order, a latent
deadlock. It now clones the ctx handles under the map lock, releases it, then
writes each deposit, and recovers a poisoned ctx with `into_inner` like the
other methods (making it infallible).

Important-12: the CLI installs no tracing subscriber, so ignored-hint and
self-heal `warn!`/`debug!` lines were no-ops and a bundle whose hints all lie
paid an unhinted price with an identical summary. `PullReport` now carries
`spliced_bytes` (bytes served from a local donor splice) and `hints_ignored`
(hints dropped by a fault), surfaced in both the human summary and `--json`.
Reporting only; payment is unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ures

CI runs `clippy --workspace --all-targets` (no --all-features); the range-dedup
+ --max-lane-streams locals pushed main's aggregated future 48 bytes over the
16 KiB large_futures threshold. Boxing run() keeps main's future off the stack.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…rallel-chunks-54c2bc

# Conflicts:
#	crates/cli/src/commands/pull_progress.rs
@alpergundogdu

Copy link
Copy Markdown
Contributor Author

Second review round addressed (head 18542be6). Mapping:

Critical

  • 1 (finalize guard after complement drive), 2 (sweep deletes paid donor), 3 (hint-length mismatch fatal) — already fixed in 757b0874 (each with a biting regression test); verified still present.
  • 4 (self-heal e2e non-falsifiable) — 15519594: the self-heal test now asserts an exact post-warm-up delta (a-whole + b-complement + b-head) and the runner bails on non-transient faults; forcing plan_dedup to drop donors makes it fail (64-byte bite).

Important

  • 5 (already-finalized staging re-drive) — 15519594: pull_entry hash-verifies + materializes from an existing staging, never re-drives; misleading comment corrected.
  • 6 (credit_all lock-order inversion) — 15519594: clones ctx handles under the map lock, releases it, then writes; poison handling unified; lock-order test added.
  • 7/8/9/11 (stale --optimize/--json help, orphaned credit_skipped doc, ADR 022/039/appendix, drive_ranges contract doc, --move rationale) — 816acc0c + 18542be6. ADR 039 now cites the shared-lane starvation reason (not the deleted provider_lock/BadSignature). The leftover drive_ranges_from doc you'd expect from the same fix is corrected in 18542be6.
  • 10 (changelog voice / plan refs) — 816acc0c, swept in the feature's files (logging.rs/discovery.rs left alone — pre-existing on main).
  • 12 (silent money outcomes) — 15519594: PullReport gains spliced_bytes + hints_ignored, in the human line and --json.
  • 13 (progress short of 100% on dedup) — already fixed (finish_progress true-up); verified.

Also: --max-lane-streams (default 1) added as a per-provider concurrency cap so concurrent same-lane pulls (the voucher-starvation path) ship dormant while a fairness fix is worked separately; main merged in (its #2004 total-bar speed/ETA kept alongside the range-dedup progress model); and the clippy::large_futures failure fixed by boxing run().

Suggestions (newtypes, drive_ranges→enum, Option<&LaneLedgers> mode selector, extra test cases) noted as follow-ups. Full suite green: cargo nextest workspace, clippy --workspace --all-targets (CI-exact) + --all-features, doc gate, cargo deny, and the range-dedup anvil e2e 3/3.

…rallel-chunks-54c2bc

# Conflicts:
#	crates/cli/src/commands/pull_progress.rs
@alpergundogdu
alpergundogdu merged commit 9adc747 into main Sep 14, 2026
25 checks passed
@alpergundogdu
alpergundogdu deleted the claude/bundle-pull-parallel-chunks-54c2bc branch September 14, 2026 11:26
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.

3 participants