Skip to content

feat(client-pull,cli): multi-source parallel fetch scheduler (ADR 039, #1164) - #1773

Merged
thiras merged 19 commits into
mainfrom
claude/issue-1164-status-20c77a
Aug 24, 2026
Merged

thiras merged 19 commits into
mainfrom
claude/issue-1164-status-20c77a

Conversation

@alpergundogdu

Copy link
Copy Markdown
Contributor

Implements the ADR 039 multi-source parallel fetch scheduler (closes #1164). A client fetching a large blob now fans out across several full-holder nodes at once over the existing paid cdn/client/v1 protocol, instead of streaming from one peer. Client-only: the node's cache-miss pull leg is untouched.

Design (ADR 039, rewritten in this branch)

  • Eager fan-out + aria2-style dynamic segmentation with tail-stealing. Each admitted source gets a large bao-aligned contiguous segment as a bounded byte_len request; a source that finishes steals the tail of the largest remaining range (min_split_size floor, 16 MiB). "Keep the fastest source hot" is emergent from stealing, not a separate controller.
  • One outstanding unit per source — a correctness invariant, not a throughput cap: two concurrent units to one node collide on its (signer, provider) payment lane. Parallelism comes from source count.
  • Reassign-only tail (deadline/stall watchdog + fault), never duplicate requests — every byte is paid, so BitTorrent-style endgame duplication is a straight loss.
  • Per-provider payment lanes on one shared pool. Each source signs vouchers on its own (signer, provider) lane seeded from that lane's cumulative; a shared aggregate-committed gate (deposit − Σ committed across all lanes) keeps concurrent lanes from overspending the one deposit.
  • No new wire surface — bounded byte_len requests already exist and the node already bills the exact aligned span.

What's included

  • client-pull/src/segment.rs — pure group-canonical segmentation + tail-steal helpers.
  • client-pull/src/scheduler.rs — concurrent fan-out, tail-stealing, cancellation + deadline reassignment, present-bytes backstop (no double-pay), aggregate-solvency gate, interval .ranges flush.
  • client-pull/src/ranged_store.rs — single-writer present-record flush (per-checkpoint fsync moved off the hot path; interval flush bounds crash-loss).
  • discovery::admit_sources — set-valued admission with operator/region spread.
  • CLI: --multi-source/--no-multi-source, --max-sources (4), --multi-source-min-bytes (64 MiB), --unit-deadline-ms (10s); engagement gate wired into decdn fetch.
  • ADR 039 rewritten to present-tense canon; stale bounded-range language checked in 005/038.

Testing

  • Full workspace suite green (2790 tests), plus a real anvil e2e across two holders proving byte-identical assembly and that both nodes are independently paid on their own lanes under one pool.
  • Load-bearing invariants have dedicated tests: no-double-pay under a multi-threaded runtime, aggregate gate refuses a second leg into a drained pool, stall→reassignment, per-provider lane addressing, interval flush persists mid-fetch.

Deferred (accepted, not blocking)

  • bundle pull stays single-source (its open_lock serialization + rarely-fired 64 MiB gate make multi-sourcing low-value for now).
  • Aggregate solvency gates at leg-boundary granularity; strict per-byte no-overspend (a reservation subsystem) is deferred and backstopped by on-chain first-come redemption.

🤖 Generated with Claude Code

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.

Pull request overview

This PR implements ADR 039’s client-only multi-source parallel fetch path for large blobs: the CLI can now fan out a single paid cdn/client/v1 fetch across multiple full-holder nodes concurrently, with bao-aligned segmentation, tail-stealing, and per-provider payment lanes on one shared pool deposit.

Changes:

  • Added a multi-source scheduler (multi_source_fetch) and pure segmentation/tail-steal helpers, including cancellation + stall reassignment and an aggregate solvency gate across lanes.
  • Reworked ClientRangedStore present-range persistence to support concurrent ingest writers via single-writer interval flushing (.ranges sidecar) and explicit flush points.
  • Wired CLI flags/engagement gate and added an anvil-backed e2e test validating two-holder parallelism and per-lane payment settlement; updated ADR 039 to “Accepted”.

Reviewed changes

Copilot reviewed 13 out of 14 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
crates/node/src/node_origin/admit_store.rs Implements flush_present_record as a no-op for the node origin ingest store.
crates/e2e/tests/cli_fetch_multi_source.rs Adds an anvil-backed CLI e2e proving two-holder multi-source fetch and per-lane payment.
crates/common/src/cli/fetch.rs Adds CLI flags and resolved helper for multi-source enablement and tuning knobs.
crates/client-pull/src/source.rs Extends IngestStore with flush_present_record; enhances scripted source doubles for deterministic multi-source tests.
crates/client-pull/src/segment.rs New pure segmentation + tail-steal utilities (bao-aligned, canonicalized).
crates/client-pull/src/scheduler.rs New multi-source fan-out scheduler with tail-stealing, cancellation, watchdog, and aggregate solvency gating.
crates/client-pull/src/ranged_store.rs Moves .ranges persistence to explicit flush points; adds flush_present_record API and concurrent-ingest test.
crates/client-pull/src/lib.rs Exposes the scheduler API (MultiSourceConfig, SourceLane, multi_source_fetch) and re-exports RangedStore.
crates/client-pull/src/driver.rs Adds interval .ranges flushing wrapper; threads aggregate spend gate into fill_gap; refactors counters.
crates/client-pull/src/discovery.rs Adds admit_sources for set-valued, operator-spread source admission with tests.
crates/client-pull/Cargo.toml Adds futures-util for driving worker futures concurrently without spawning.
crates/cli/src/commands/fetch.rs Wires multi-source engagement into decdn fetch, builds per-provider lanes, persists per-lane watermarks.
Cargo.lock Records the new futures-util dependency in the lockfile.
adr/039-multi-source-parallel-fetch.md Rewrites ADR 039 in present tense and marks it Accepted, matching implemented behavior.

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

Comment thread crates/client-pull/src/scheduler.rs Resolved
@github-actions

github-actions Bot commented Aug 20, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 81.57% (was 81.57%, ● 0.00%) — 64676/79287 lines

File Coverage Lines Δ
crates/cli/src/commands/bundle_pull.rs 49.15% 432/879 ▼ 0.06%
crates/cli/src/commands/fetch.rs 34.62% 522/1508 ▼ 4.78%
crates/client-pull/src/discovery.rs 96.39% 828/859 ▲ +0.21%
crates/client-pull/src/driver.rs 91.36% 856/937 ▼ 4.92%
crates/client-pull/src/lib.rs 89.09% 1649/1851 ▲ +0.05%
crates/client-pull/src/ranged_store.rs 90.57% 1037/1145 ▲ +0.47%
crates/client-pull/src/retry.rs 100.00% 56/56 new
crates/client-pull/src/scheduler.rs 92.74% 1277/1377 new
crates/client-pull/src/segment.rs 95.48% 190/199 new
crates/client-pull/src/source.rs 92.71% 305/329 ▲ +2.36%
crates/common/src/cli/fetch.rs 97.80% 178/182 ▲ +0.13%
crates/node/src/node_origin/admit_store.rs 89.69% 200/223 ▲ +0.14%
History
Commit Total Δ vs base
e2b2599 81.29% ▼ 0.03%
c423f10 81.33% ▲ +0.01%
71fecd6 81.57% ● 0.00%
ad177e0 (HEAD) 81.57% ● 0.00%

@yigitdot

Copy link
Copy Markdown
Contributor

PR #1773 Review — multi-source parallel fetch scheduler (ADR 039, #1164)

Context

Branch claude/issue-1164-status-20c77a, 17 commits, +3761/−208 across 16 files.
CI is fully green (clippy, test, doctest, both anvil-e2e jobs, public API snapshot),
so nothing here is a build or lint failure — these are design and correctness
findings.

The PR makes decdn fetch fan a large blob out across several full-holder nodes
over the existing paid cdn/client/v1 protocol. New: client-pull/src/scheduler.rs
(worker-per-source fan-out, tail-stealing, cancel/deadline reassignment),
segment.rs (pure bao-aligned segmentation), retry.rs (shared terminal/retry
classifier, hoisted verbatim out of the CLI). Modified: driver.rs (typed
PoolExhausted, interval present-record flush), ranged_store.rs (single-writer
flush), discovery.rs (admit_sources), CLI wiring + five new flags.

Reviewed by five specialist agents plus a direct read of the diff. Every finding
below was verified against the code; provenance (new vs. pre-existing) is stated
where it matters.


Critical

C1. admit_sources can put two nodes of the SAME operator on one voucher lane

discovery.rs:761-772 (pass 2) + cli/src/commands/fetch.rs:1221,1240-1243,1434-1439

Pass 1 admits one candidate per distinct eth_address. Pass 2 then fills the
remaining slots "operators now free to repeat". So whenever there are fewer
distinct operators than max_sources — one operator running two nodes, the exact
topology pass 1 exists for, and entirely normal in a tens-of-nodes launch network
— the admitted set contains two candidates with the same eth_address.

build_multi_lane derives provider directly from candidate.eth_address, so
the CLI then builds two MultiLanes with the same provider and same pool_id,
seeds two independent PoolLedgers from the same persisted cumulative, and
runs both concurrently as separate SourceLanes.

That is two concurrent monotonic voucher streams on one (signer, provider) lane
— precisely the hazard scheduler.rs:16-20 says the one-unit-per-source rule
exists to avoid ("two concurrent units to the same node would share one
(signer, provider) payment lane and reintroduce the concurrent-same-lane voucher
hazard bundle pull serializes against"). The design's core payment-safety premise
is delegated to admit_sources, which does not uphold it.

It also breaks the watermark write: the persist_watermark loop at :1434-1439
runs twice with an identical LaneKey { pool_id, signer, provider }, last
write wins, and can persist the lower of the two watermarks.

The guard at fetch.rs:1300 (admissible.len() < 2) counts nodes, not
operators, so it does not catch this.

Fix (minimal): dedupe admissible by eth_address before the < 2 check.
Fix (better): have admit_sources return an AdmittedSources newtype whose
constructor guarantees distinct eth_address, and have multi_source_fetch take
it — the scheduler's premise then gets checked at the boundary instead of asserted
in prose.

C2. Every retryable worker error is discarded; the fetch dies as a contentless string

scheduler.rs:497-504 and :676-683

Err(e) => {
    let terminal = retry_disposition(&e) == RetryDisposition::Terminal
        || e.downcast_ref::<PoolExhausted>().is_some();
    if terminal { return Err(e); }
    UnitOutcome::Faulted        // `e` is dropped here — never stored, never logged
}

There is no last_err slot and no per-source attribution. UpstreamRefused(NotFound),
Overloaded, EvictedSinceProbe, HashBlacklisted, transport resets, and
HashMismatch (a node served bytes that failed bao verification) are all destroyed.
The watchdog arm at :507 carries no error by construction. Logging is not an
option: decdn installs no tracing subscriber, which is exactly why
discovery.rs:472-476 returns its provenance in the return value.

The user of a failed 512 MiB fetch sees only:
Error: all sources failed; 536870912 bytes unfetched — no node id, no reason,
no remedy. Worse, because that bail is a bare anyhow! string rather than a typed
UpstreamRefused, the annotate_unbound_cache_miss call at fetch.rs:1442-1445
downcasts, misses, and passes it through verbatim — so the entire two-cause
cache-miss diagnosis is unreachable on the multi-source path.

Compare the single-source loop at fetch.rs:815-907, which keeps last_err,
prints a per-candidate failover line, and returns the last real error. Mirror it.
Keep a Some/None split: a watchdog stall genuinely has no error, and
"all sources stalled with no verified progress within 10s" is a different and more
actionable message than "the nodes refused".

C3. A failed multi-source fetch never falls back to the single-source loop

cli/src/commands/fetch.rs:769-802

Err(err) if grant.is_some() => return Err(annotate_delegated_exhaustion(err)),
Err(err) => return Err(err),

Once multi-source engages, any failure ends the fetch — including plainly
retryable ones. The scheduler's own "all sources failed" is not a typed terminal
error; it is exactly the class the failover loop directly below was built to
survive.

Before this PR, a >64 MiB fetch with several holders tried every candidate in
sequence. After it, the same fetch fans out and hard-fails if the fan-out does,
without the failover loop ever running. --multi-source defaults on with a 64 MiB
floor, so this is the default path for exactly the large blobs the feature targets.
The .partial survives, so a re-run resumes — but the user sees a failure where
they previously saw a success.

ADR 039 is silent on failure fallback (it only specifies the size/holder gate for
choosing single-source), so this is an unspecified design gap rather than an ADR
violation — worth an explicit answer in the ADR either way.

Fix: branch on retry_disposition(&err). Return only on Terminal (plus
PoolExhausted, already typed); on RetryElsewhere, warn to stderr and fall
through — the loop resumes the same .partial and re-pays nothing.

C4. A reactive top-up on one lane is invisible to every other lane's deposit gate

driver.rs:580-587 + cli/src/commands/fetch.rs:1112, :1369

fill_gap credits a landed top-up by writing through this lane's handle:
ctx.lock()?.deposit = new_deposit. But build_multi_lane constructs a fresh
Arc<Mutex<PoolContext>> per lane
, so lanes B..N never see it.

Meanwhile remaining_deposit = locked_deposit(ctx) - spent(...) (driver.rs:494)
subtracts the aggregate committed across all lanes. So after lane A tops up,
every other lane computes stale_deposit − aggregate_spend_including_A's_new_spend
and walks toward zero → Refuse → PoolExhausted → which this PR's own rule
(scheduler.rs:498-502) makes terminal for the whole fetch.

The comment at fetch.rs:1369 — "a reactive top-up heals the shared pool for all
of them" — is false as written. In the common CLI config the other lanes first try
their own top-up, which masks this behind C5's extra escrow; with
working_deposit == 0, a delegated grant, or the budget spent, it aborts a fetch
whose pool was just funded.

Fix: share one deposit view across lanes, or have a successful top-up credit
every lane's ctx.

C5. The per-fetch top-up budget is multiplied by the lane count

scheduler.rs:411-413 + driver.rs:242

DriveCounters::new() is called once per worker, and topups_used lives in
it. PaceState.max_topups is funder.max_topups() = MAX_TOPUP_ATTEMPTS (CLI: 3).
With the default --max-sources 4, one decdn fetch can execute 12 reactive
top-ups
— 12 ensure_allowance + topUp pairs escrowing real USDC — where the
documented and previously-enforced bound was 3.

The comment at :411-413 acknowledges the budget is per-worker but frames it as a
design note rather than the overspend it is. All lanes draw one pool; the top-up
budget is a property of that pool, not of a lane.

Fix: share it as an AtomicU32/Mutex<u32> threaded into every worker's
counters — exactly what pool_spent already does for the solvency gate.


Important

I1. The present record is not flushed on the error path

scheduler.rs:662-671 and driver.rs:361-394

Both do drive_with_interval_flush(...).await?; and only then
store.flush_present_record()?. The ? skips the final flush on every failure.

This PR removed the per-checkpoint record write (ranged_store.rs checkpoint
now only unions into in-memory present), so durability rests entirely on the 5 s
PRESENT_RECORD_FLUSH_INTERVAL plus that final flush. Skipping it leaves the
durable frontier up to five seconds of throughput stale — a bound that now scales
with bandwidth, where the old 4 MiB bound did not.

It does not take a crash. drive_fetch constructs a fresh
ClientRangedStore::open_or_create per candidate (fetch.rs:1094-1096), so on an
ordinary proxy-warming failover the next attempt reads a stale .ranges and
re-pulls — and re-pays for — bytes already delivered, bao-verified, and
fsynced. At 200 Mbps that is ~125 MB. Meanwhile select_watermark has already
settled the failed lane HIGH, so the first payment is booked.

Fix: bind the result, flush, then propagate — the failure exit is precisely the
case whose record gets read next. Also consider keeping a byte-based trigger
alongside the timer, or documenting that the loss window scales with link speed.

I2. Success is reported for a fetch that was never promoted

cli/src/commands/fetch.rs:1417-1422

if fetch_result.is_ok() && ranged_store.is_complete().await.unwrap_or(false) {
    ranged_store.finalize().await.map_err(...)?;
}
...
Ok(Some(total_bytes))

is_complete() can fail (RangedStoreError::Backend("present lock poisoned"),
Alignment). .unwrap_or(false) turns any such failure into "not complete", which
skips finalize() — the verify sweep and the .partial → output promote — and the
function still returns Ok(Some(total_bytes)), so the CLI prints
fetched N bytes -> movie.mkv and exits 0 with no movie.mkv on disk. The user
paid in full. Scripted pipelines proceed on the success exit code.

Fix: propagate the is_complete error, and ensure! completeness before
reporting success.

I3. A retired worker can strand later-requeued work and fail a recoverable fetch

scheduler.rs:271-332, :414-423, :350-372

Work::pick returning Ok(None) retires a worker permanently — there is no
idle/park state. steal_split returns None whenever the largest in-flight range
is under the 16 MiB MIN_SPLIT_SIZE, which is the normal end-of-fetch condition,
so every freed worker retires for good once ranges get small. Separately,
requeue_missing pushes a faulted worker's remainder back to pending after
removing it from in_flight.

Sequence: workers B, C, D finish, find nothing above the floor to steal, retire.
Worker A then faults, requeues its remainder, and breaks. pending is non-empty
with no live worker; try_join_all returns Ok; multi_source_fetch bails
"all sources failed; N bytes unfetched" — despite three healthy, already-paid-for
lanes having been available moments earlier, and (per C2) with the actual cause
already discarded.

Fix: park workers on a Notify until pending is empty and all peers are
idle, or re-queue before clearing in_flight. Whether a retired worker should be
revivable deserves an explicit answer in ADR 039.

I4. A steal-cancelled lane can persist a watermark below what the node can redeem

cli/src/commands/fetch.rs:1425-1440 + client-pull/src/ledger.rs:171-208

Each lane's watermark is persisted with
select_watermark(&fetch_result, l.ledger.committed(), l.ledger.settlement(), ...)
— one global outcome applied to every per-lane state. select_watermark
settles at committed on Ok(()) and at the HIGH settlement on an ambiguous
Err. Sound single-source, where Ok means the one leg finished cleanly.

PoolLedger::issue arms a voucher before exchange, precisely so "a future
dropped inside the send still has settlement report what we owe". Steal-cancel
drops a victim's fill_gap future at whatever await it is parked on — including
that exchange — and that is a designed, routine event on a successful fetch.
So a steal landing mid-send leaves armed > committed, the fetch completes Ok,
and the Ok arm persists the low value. The client's lane cumulative then sits
below the provider's, and the next fetch signs a cumulative the upstream already
holds — rejected as a regression.

Scope: this partly self-heals. After a cancel the victim re-queues and usually
picks again against the same source, and issue builds the next voucher on the
settlement frontier, so the next successful send closes the gap. The window that
does not heal is a cancel landing on the victim's final in-flight voucher, where
requeue_missing finds nothing remaining and the worker exits. Real, but a race on
the last voucher of a stolen leg — not every steal.

Fix: for multi-source lanes persist settlement() unconditionally rather than
branching on the shared fetch_result. It already equals committed() when
nothing is armed, so it is safe on the clean path and correct on the cancelled one.

I5. The steal_split argmax is duplicated across a module boundary

scheduler.rs:289, :303-309 vs segment.rs:172

pick collects remaining discarding the index, steal_split picks its argmax,
then pick re-derives the same argmax to recover the index. The comment at
:297-302 reconciles them: "both iterate in_flight in order and take the last
maximum". That is true today (both use Iterator::max_by_key), but it is a
cross-module coupling with no compiler support. Change steal_split to sort, or to
first-max semantics, and pick trims and cancels the wrong victim while the
real victim keeps streaming and paying for the stolen tail — silent double-pay,
with no test guaranteed to catch it (the double-pay tests use two lanes, not the
≥3-lane tie case).

Fix: have steal_split return Option<(usize, AlignedRange)> over an indexed
remaining, deleting the re-derivation and the comment that reconciles it. This is
the single highest-value structural change in the diff.

I6. Silent overlap if the steal trim guard fails

scheduler.rs:310-331

The victim is trimmed and cancelled only under half.fetch_start() > *start. If
that guard is false the code still assigns half to worker i — two workers
then own overlapping ranges and both pay for the overlap. Unreachable today
(in-flight starts come from AlignedRange::fetch_start(), so
canon_start == start), but carried by convention through a (u64, u64) tuple
rather than by a type. The safe branch is to decline the steal, not to proceed
untrimmed.

Related: pick/clear silently no-op on an out-of-range worker id
(:279, :292, :328, :338) while still returning Ok(Some(half)) — the
worker then pays for a range in_flight never recorded, so a peer sees it as
unowned and steals it. run_worker:408 already handles the same class correctly
with anyhow::bail!; pick/clear should match (bail! satisfies the anti-panic
policy just as well as a no-op).

I7. The engagement gate opens a pool before it knows the blob size

cli/src/commands/fetch.rs:1299-1353

try_multi_source_fetch calls build_multi_lane — which runs
build_ctx_for_fetch, i.e. chain work, open/reuse pool — and then
open_progressive_pull purely to learn total_bytes, and only then applies the
multi_source_min_bytes floor. For any blob below the floor with ≥2 admissible
holders — with a 64 MiB default, that is most fetches — that is a wasted chain
round-trip plus a wasted QUIC open before falling through to the single-source
loop, which redoes the same work. The comment at :1310-1313 claims "the probe is
not wasted work" because the lane is reused; that holds only on the engaged path.

Fix: hand the built first lane + header to the single-source loop on
fall-through, or gate on a cheaper size source.

I8. Three silent return Ok(None) declines after the user explicitly asked

cli/src/commands/fetch.rs:1300-1305, :1346-1353

A user who passes --multi-source --max-sources 8 and watches a 500 MiB blob
arrive over one connection cannot tell whether it was the size floor, the
operator-spread filter collapsing eight candidates onto one operator, or the kill
switch. Every other degradation on this path already prints to stderr
(Bootstrap::warning, the proxy-warming lead, the failover line). One line per
decline naming the specific unmet condition.


Suggestions

S1. missing_bytes maps Err(_) to u64::MAX, blaming the peer for a local fault

scheduler.rs:168-179. store.missing_ranges fails on a poisoned present lock
or an alignment error — both client-side. u64::MAX makes now >= prev trip
immediately, faulting a healthy, actively-delivering paid source. If the error is
transient (erroring at the watchdog sample, succeeding at the requeue sample) it is
swallowed entirely: the healthy source is dropped, its remainder reassigned, and
the new lane re-pays the credit-window tail. Return the error and give watchdog a
Stalled | StoreError(e) outcome; a local store fault is not something another
node can fix and must never read as a peer stall.

S2. A transient .ranges write failure kills a multi-GB paid download

driver.rs:231-232. The periodic flush is a durability optimization; promoting
its failure to fatal inverts that. An ENOSPC or a transient tempfile-creation
failure aborts the whole in-flight fetch, cancelling every worker mid-delivery —
and, per I1, without a final flush, so the progress the flush was protecting is
discarded too. The error also reaches the user as a bare io::Error with nothing
saying it came from a background flush. Make the tick best-effort but not silent:
record the failure and report it from the final flush.

S3. PoolExhausted's doc contradicts retry_disposition

driver.rs:86-97 says the type exists "so the failover classifier
(retry_disposition) can downcast_ref and rule it terminal for BOTH fetch
paths". Commit c423f101 deliberately reversed that: retry.rs:55-62 and the test
pool_exhausted_falls_over_in_the_shared_classifier (retry.rs:132-139) assert it
is RetryElsewhere in the shared classifier, with only the scheduler applying the
pool-scope rule. The doc is falsified by a test in the same crate.

S4. MultiSourceConfig::unit_deadline's doc is stale on arrival

scheduler.rs:240-242 says "Consumed by the reassignment path (a later task); the
core scheduler does not read it." It is read — :650 → run_worker → watchdog
at :507.

S5. ingest_stream's doc block now documents flush_present_record

node/src/node_origin/admit_store.rs:92-124. The new flush_present_record was
inserted between the existing ~30-line doc comment and the ingest_stream it
describes. The block covering on_progress, the R: BaoRangeReader bound, and the
admit-error parked-fault recovery now renders as documentation for a one-line
Ok(()) no-op, with the new "No-op: …" text glued to its end; ingest_stream at
:124 has no docs at all.

S6. Region spread is claimed in three places and implemented in none

discovery.rs:701-724 opens with "greedily spreading across eth_address
(operator) first and region_hint second", then explains region is deliberately
not a tiebreaking pass. ADR 039:37 says the client "spreads the set across
distinct operators and regions". The PR body says "operator/region spread". No test
asserts region behavior. Either implement it or amend all three.

S7. Magic values that should be types, and unbounded flags

MultiSourceConfig: max_sources == 0 is silently repaired to 1
(scheduler.rs:610), unit_deadline == ZERO silently disables the watchdog
(:194-196). NonZeroUsize and Option<Duration> say both in the type.
The documented safety floor (unit_deadline must exceed 4 MiB / min-throughput,
:189-192) is enforced nowhere.

CLI: max_sources, multi_source_min_bytes, unit_deadline_ms
(common/src/cli/fetch.rs:184,191,199) accept 0 and arbitrarily large values,
while stall_timeout_ms and timeout_ms in the same struct already use
value_parser = clap::value_parser!(u64).range(1..). validate() (:398) skips
every new flag.

multi_source + no_multi_source (:165-177) is a representable illegal state —
and --proxy-warming one screen up (:137-138) already solves the identical
problem with a single default_value_t = true, action = ArgAction::Set field.
Given the pre-launch no-compat rule, adopting that shape deletes the second field,
multi_source_enabled(), and the illegal state.

S8. CLI test fixture disables the feature it should be exercising

cli/src/commands/fetch.rs:1945-1946 sets multi_source: false while the clap
default is true, and also constructs the (false, false) state clap cannot
produce. Every CLI test on that fixture exercises the single-source path only, and
none would notice if the production default flipped.

S9. The only real-wire test runs 100× below the production floor

e2e/tests/cli_fetch_multi_source.rs:85-99: a ~640 KiB blob with
--multi-source-min-bytes 200000. Fan-out and per-lane payment are genuinely
proven (both nodes settle non-zero claims on one shared pool — a good test). But
with MIN_SPLIT_SIZE = 16 MiB no segment can ever be stolen, so tail-stealing,
cancellation, and reassignment never execute on the real wire. Also
run_fetch_until_ready (:288-312) retries the whole decdn fetch for 90 s on any
failure, which can mask a genuinely failing first attempt.

S10. canonicalize_ranges silently drops len == 0, which means "to end" elsewhere

segment.rs:51-53. Not currently reachable, but 0 is overloaded in this crate:
align_range(0, 0, total) means the whole blob (ranged_store.rs:890) and
read(offset, 0) means "to the end" (:793-797). The one place that receives a
zero span reads it as "skip" while everything adjacent reads it as "everything".
Same shape at :138-142 (if seg_end <= off { break; }). Make the unreachable
case loud rather than absorbed — the symptom otherwise is silently-missing bytes.

S11. Unresolvable references: spec §N, ADR 039 §5.2, ADR 039 § Payment model

There is no spec document in this repo (find -iname '*spec*' returns only
OpenZeppelin's Certora files). The 18 spec §5.3 / §5.5 / §8 citations across
scheduler.rs, segment.rs, driver.rs, ranged_store.rs, source.rs,
lib.rs, and Cargo.toml are permanently unverifiable — they read like references
to an out-of-band task brief. Point them at ADR 039's real headings or drop the §.

ADR 039 has no numbered sections, so cli/src/commands/fetch.rs:1296's
"ADR 039 §5.2" resolves to nothing (intended target: ### Source diversity and reputation). And its heading is ### Payment, not § Payment model — the latter
is a real heading in ADR 003, a different document the same comments also cite,
so a reader following it lands on the wrong ADR. Five sites:
scheduler.rs:96,550, cli/src/commands/fetch.rs:952,1278,
e2e/tests/cli_fetch_multi_source.rs:198.

S12. multi_source_enabled's doc is contradicted by its own test

common/src/cli/fetch.rs:422-426 says off "regardless of --multi-source's own
value — the negation always wins". overrides_with is mutual, so clap clears
the earlier occurrence and the real semantics are last-flag-wins. The test at
:750-753 asserts exactly that: ["--no-multi-source", "--multi-source"] is
enabled, with the message "a later --multi-source overrides an earlier
--no-multi-source". Doc and test contradict each other in one file.

S13. Other doc claims that do not match the code

  • scheduler.rs:236-238 — max_sources is documented as a "Cap on
    concurrently-used holders", but multi_source_fetch spawns a worker for every
    entry in lanes (:636), regardless. It only sizes the initial segment count
    (:610); the cap is enforced by the CLI's admit_sources call. Harmless as
    called today, but the public API contract is wrong. ADR 039 § Parameters repeats
    the claim.
  • segment.rs:9-11 — MIN_SPLIT_SIZE is described as a floor "for a tail smaller
    than this", but steal_split gates on the parent range (:175) and returns
    roughly half, so tails below the floor are routine.
  • scheduler.rs:562-564 — "Finalization is the caller's job — like
    crate::drive
    ". drive does the opposite (driver.rs:399-402 finalizes on
    completion). drive is the contrast, not the parallel; the CLI's own comment at
    fetch.rs:1420-1422 gets this right.
  • segment.rs:89 — "Split the gap-set into up to n segments" is contradicted
    by its own body at :101-104; a multi-span gap-set legitimately exceeds n.
  • scheduler.rs:164-165 — "this worker's range is disjoint from every peer's" is
    contradicted by the backstop comment at :428-431, which documents the window
    where it is not.
  • scheduler.rs:562 — "Returns once every gap is filled (or a worker faults)." A
    retryable fault does not return; only a terminal one does.
  • segment.rs:165-167 — steal_split's # Errors attributes OOB rejections to
    align_range, but they come from canonicalize_ranges (:60-61), which runs
    first — as its own tests assert.
  • driver.rs:200-201 — "5 seconds mirrors the voucher-flush cadence." No such
    cadence exists in the codebase.
  • cli/src/commands/fetch.rs:1330-1332 — "This also opens/reuses that holder's
    pool" credits the throwaway probe, but build_multi_lane did it on the line
    above.
  • discovery.rs:704-712 — "without disturbing rank order" understates pass 2: once
    it fires the result is not in rank order (ranked [op1,op1,op2], max=3 yields
    [op1(0), op2(2), op1(1)]). The only test asserting rank preservation uses a case
    where pass 2 never runs.

S14. ADR 039 acceptance criteria that this PR does not meet

ADR 039 is marked Accepted and this PR is its implementation, so these are
tracked gaps rather than nits:

  • Reputation feedback is entirely unimplemented — five sites in the ADR
    (§ Failure handling, § Source diversity and reputation, Consequences → Positive
    bullet 4, Cross-ADR Impact → ADR 008, and Acceptance Criterion 2). Confirmed:
    neither decdn-client-pull nor decdn-cli depends on decdn-reputation.
  • AC 5 / § Concurrency invariants state "no byte range is outstanding at more
    than one source at a time" as an absolute. The PR's own backstop comment
    (scheduler.rs:428-431) documents the window where a completed-but-uncleared
    range is steal-eligible; the backstop makes it harmless, not impossible.
  • § Parameters labels all four knobs "config", and names one
    multi_source.enabled — implying a TOML section. All four ship as CLI flags
    only; there are no matching keys in crates/common/src/config/.
  • § Dynamic segmentation says the victim is "the source with the largest
    remaining un-fetched range". The code takes the argmax over assigned lengths,
    which never shrink as bytes are delivered — so a source 90% through a 32 MiB
    assignment outranks one that has fetched nothing of a 24 MiB one.
  • § Dynamic segmentation says a below-floor range makes the scheduler "skip the
    split, and let the range drain on its current stream". The freed worker does not
    skip — it exits permanently (see I3).
  • § Failure handling says "a source that accumulates failures is dropped"; the
    code drops on the first retryable fault (:535-538).

Pre-existing, amplified by this PR (not introduced here)

retry_disposition rules every UpstreamVoucherRejected terminal
(retry.rs:67-71). This is a verbatim move of the classifier already on main
(main:crates/cli/src/commands/fetch.rs:938-942), so it is not a new defect. But
two of the nine VoucherRejectReason variants are per-lane facts, not global ones:
AmountRegression/BytesRegression describe one (signer, provider) watermark —
which is exactly what this PR gives each SourceLane its own of — and
WrongProvider is definitionally per-node (currently unreachable, since
CapabilityGrant carries no node scope; a latent trap if it ever does).

Multi-source amplifies the cost: one lane's stale watermark now cancels every other
healthy paying lane via try_join_all, instead of merely ending one sequential
attempt. Worth classifying by reason with an exhaustive match (no _ arm, so a
new variant forces a decision), either here or as a follow-up issue.


Strengths

  • The terminal-vs-retryable split (scheduler.rs:52-73, :474-508) is the right
    architecture, and keeping PoolExhausted retryable in the shared classifier
    while the scheduler applies the pool-scope rule itself is a genuinely subtle
    distinction, correctly reasoned and correctly tested.
  • Replacing the anyhow::bail! string with a typed PoolExhausted
    (driver.rs:83-115) is what makes downcast classification possible at all, and
    terminal_fault_propagates_and_is_not_reassigned asserts the downcast rather
    than the message.
  • CancelHandle's flag-plus-Notify design correctly handles both the
    stale-permit and lost-wakeup cases; the loop in cancelled (:155-162) is right
    and well-argued.
  • The e2e asserts the thing that actually matters — both nodes settle non-zero
    claims against one shared pool id — rather than just byte-identity.
  • SourceLane bundling fixes a real prior bug (one ledger shared across sources).

S15. Smaller operational notes

  • Stealing a completed-but-uncleared range cancels the victim mid-finish.
    pick (:322-325) signals unconditionally, including when the victim has fully
    delivered and is inside BlobSource::finish — the select then drops fill_gap
    there, aborting the voucher drain for a leg that delivered everything. The
    slow_finish test exercises this and passes, so it is tolerable, but skipping the
    cancel when the split point is already present would avoid the churn. (This is
    also the mechanism behind I4.)
  • Progress bar is non-monotonic under fan-out. driver.rs:637-643 snapshots
    base_present once per leg and reports base_present + received; with N workers
    writing the same set_position the bar jumps backward. Cosmetic, but visible on
    every multi-source fetch.
  • Blocking file I/O now blocks every lane. ingest_stream's write_all_at and
    checkpoint's two sync_all() calls run directly on the async task, and the
    workers are try_join_all'd onto one task (no spawn), so one worker's 4 MiB
    fsync stalls all peers and the interval flush. Pre-existing single-source, but
    this PR's concurrency claim makes it newly load-bearing — worth a spawn_blocking
    follow-up.

Test coverage

All 215 decdn-client-pull tests pass (6.8 s). The structural invariants
(per-lane ledgers, aggregate-solvency arithmetic, terminal-error propagation,
segmentation alignment) have genuinely discriminating tests. The temporal
invariants do not.

Against the PR body's six claims: no-double-pay-under-multi-thread, aggregate gate,
per-provider lane addressing, and byte-identical two-holder assembly are all
genuine. Interval flush is partial (helper tested in isolation, never through
multi_source_fetch). "stall → reassignment" is not tested.

T1. The stall watchdog has zero coverage, and the test named for it doesn't cover it

scheduler.rs:193-216, selected at :507. Every scheduler test sets
unit_deadline to 10 s or 30 s, so the watchdog never fires once in the suite.

stalled_source_tail_is_reassigned_and_fetch_completes (:880-954) uses
with_fault_after(8 MiB, || anyhow!("scripted stall")), which makes fill_gap
return Err — that is the UnitOutcome::Faulted path at :503; the watchdog arm
at :507 is never reached. The string "scripted stall" is what makes it read as
watchdog coverage. Rename it — the misleading name is what makes the gap
invisible.

Each uncovered branch maps to a concrete regression that would ship silently:

  • :204-208 (now == 0 → don't trip a delivered range): delete it and a source
    waiting inside finish gets tripped and its already-paid range reassigned —
    a direct double-pay. That is precisely the slow_finish shape the multi-thread
    test builds, but at unit_deadline: 30s it can never fire there.
  • :210-213 (now >= prev → trip): flip to now > prev and a wedged source is
    never reassigned; the fetch hangs to the outer cap.
  • :214 (shrink resets the window): remove it and a healthy-but-slow source is
    falsely reassigned mid-checkpoint — the exact failure :189-192 warns about.
  • :197-199 (zero deadline disables): --unit-deadline-ms 0 is reachable and
    unvalidated.

Neither the positive nor the negative test is expressible with today's
ScriptedSource: with_fault_after errors, slow_to_start stalls only before the
first byte. A stall_after(n_bytes, Duration) builder is the missing harness piece.

T2. The steal double-pay window that actually matters is never constructed

The module doc at :524-530 names the real hazard: a victim whose paid frontier
is past the split while its checkpoint frontier is behind it. Neither steal test
builds that state — :962's victim has delivered ~nothing past the split, and
:1045's has delivered everything (so the backstop trivially skips it). The middle
case, where the paid/checkpointed gap is nonzero, is untested.

Separately, forced_steal_does_not_double_fetch_the_stolen_tail (:962) may not
discriminate. Its bound is total_delivered <= total + 8 MiB and its docstring
claims the pre-fix code produced ~80 MiB — which needs the fast source to finish
32 MiB inside the victim's 200 ms head start. Measured on this machine
(one_source_below_two_holders_still_completes: 20 MiB in 1.225 s ≈ 20 MiB/s in
debug), 200 ms buys about 4 MiB, not 32 MiB, and both the fixed and unfixed
variants land near 68 MiB — inside the 72 MiB bound. Fix either way: lengthen
slow_to_start so the victim provably delivers zero, or tighten the bound to
total + 4 MiB as the multi-thread test already does at :1104.

T3. try_multi_source_fetch has no unit coverage at all

cli/src/commands/fetch.rs:1281-1439 — ~160 lines of lane construction, header
probe, store resume, per-lane select_watermark/persist_watermark, promotion,
and error annotation. The only CLI test added covers a four-term const fn
(engagement_gate_requires_enabled_size_and_two_holders). The per-lane watermark
loop is the money-critical part: if it settled the wrong lane's prior_amount, or
persisted lane A's cumulative under lane B's LaneKey, nothing in this PR would
fail
. The e2e checks billed_a > 0 && billed_b > 0 but not that each lane's
persisted watermark matches its own delivery. This is where C1 and I4 live.

T4. The aggregate-solvency tests run single-threaded

concurrent_lanes_gate_on_the_shared_pool_balance (:1481) and
shared_gate_refuses_a_second_leg_into_a_drained_pool (:1600) are plain
#[tokio::test]. The gate is a read-then-act TOCTOU by construction (:628-634
sums, then fill_gap proceeds), and its honest bound is
deposit + Σ one in-flight leg per lane — asserted only where one lane is dead on
arrival. Two live lanes racing the gate under flavor = "multi_thread", the case
where the bound is load-bearing, is never run. Also min_remaining == deposit - aggregate (:1555) is a current-thread scheduling artifact, not an invariant; the
companion min_remaining < deposit - max_lane (:1562) is the discriminating one.

T5. Other gaps

  • initial_segments with a fragmented gap-set exceeding n (segment.rs:110-153)
    is untested. The cap is per-canonical-span (:128), so five disjoint 1 MiB gaps
    with n=2 returns five segments — deliberate, unverified. The existing
    multi-gap test uses gaps that merge, so the multi-span path never runs. This is
    the resume-after-partial-fetch shape in production.
  • admit_sources pass 2 is effectively untested (discovery.rs:761-772). The
    test named ..._spreads_across_operators_then_fills supplies 3 distinct
    operators with max=3, so pass 2 never executes. The one test that reaches it
    asserts only .len() == 2 — reverse the fill order and it still passes. Neither
    asserts which candidates return, which is exactly what C1 turns on.
  • CLI flag edges: the reverse order ["--multi-source", "--no-multi-source"]
    (negation last) is the untested direction, and it is where overrides_with
    interacts non-obviously with default_value_t = true. --max-sources 0, 1, and
    --unit-deadline-ms 0 are all unvalidated and untested.
  • The interval flush is never tested through multi_source_fetch. The helper
    test at driver.rs:1686 races a sleep(130ms); nothing asserts the wiring at
    scheduler.rs:662, nor the real §5.5 invariant that no worker flushes
    concurrently with the interval owner. FlushCountingStore already exists and
    drops straight into a two-lane fetch.
  • Weak liveness proxy: two_sources_fetch_large_blob_byte_identical
    (:812-817) proves "both contributed" with opened_bytes() > 0, recorded at
    open before a byte streams — a source that opens and immediately faults
    satisfies it. delivered_bytes(), added by this PR for exactly this purpose, is
    the honest metric.
  • Under-specified: all_sources_failing_errors_without_hang (:1162) asserts
    only is_err(), so it cannot guard the inverse of the de08382c fix — a change
    that re-masks a typed terminal error as the generic string still passes.
  • Flake risk: forced_steal_no_double_pay_on_multi_thread_runtime needs the
    stealer (100 ms handicap) to finish 32 MiB inside the victim's 500 ms finish
    stall — ~400 ms of margin on a 2-worker runtime. On a 2-core CI runner an
    inverted finish order makes the stealer legitimately steal a not-present range
    and re-fetch it, failing spuriously. Widening slow_finish to 2 s costs nothing.
  • Scheduler-side classification covers 2 of 4 terminal shapes
    (UpstreamVoucherRejected, PoolExhausted). Untested through the scheduler:
    BlobTooLargeClaim, UpstreamRefused(OriginBlacklisted), and — more useful —
    the negative case that a typed RetryElsewhere refusal is reassigned rather
    than aborting.
  • Stale CI comment (pre-existing, not caused by this PR):
    .github/workflows/ci.yml:77 says "all 15 crates/e2e/tests/*" — there are
    already 21 files there, so the count was stale before this branch. Worth a
    drive-by fix since the PR adds another one.

Verified correct (so it doesn't get re-litigated)

  • The Work::pick victim vs. steal_split argmax do agree today: both use
    Iterator::max_by_key (last-max-wins) over the same order, and remaining
    preserves in_flight order while skipping Nones exactly as the victim scan
    does. I5 is about the coupling being unenforced, not about it being wrong now.
  • The CancelHandle flag/Notify protocol is sound — flag-set-then-notify_one
    both under the Work lock, victim clears under the same lock in pick,
    cancelled() re-checks after each wakeup. Neither stale permits nor lost wakeups
    can misfire.
  • The one-outstanding-unit-per-source invariant is structural, and in_flight[i]
    is provably None at every pick (cleared by clear, or Option::taken by
    requeue_missing), so a worker can never steal from itself.
  • Concurrent ingest_stream on one store is safe: each call opens its own fd and
    uses write_all_at; shared ancestor outboard nodes are written byte-identically.
    flush_present_record clones under the sync mutex and releases before writing —
    no await across a sync lock.
  • Anti-panic policy is clean: no unwrap/expect/panic/indexing in any new
    non-test code, and every test module carries the correct #[allow] block.
  • No back-compat shims: retry_disposition was moved wholesale, old copy and its
    tests deleted rather than dual-maintained.

Recommended order

  1. C1 (duplicate-operator lanes), C4 (cross-lane top-up invisibility),
    C5 (top-up budget × lanes) — all three are payment correctness, all three
    are small fixes, and all three cost real USDC when they fire.
  2. C2 + C3 (error attribution + fallback) — together these decide what a user
    sees and whether a recoverable fetch fails at all.
  3. I1, I2 (durability on the error path, false success reporting).
  4. I3, I4, I5 (worker retirement, watermark on cancel, argmax coupling).
  5. Docs — S3, S4, S5, S6, S11, S12, S13 are all mechanical and all currently false.
    S14 (ADR gaps) needs a scoping decision, not a code fix.
  6. Tests: T1 (watchdog — an entire feature with no coverage and a misleadingly
    named test hiding it) and T3 (try_multi_source_fetch, where C1 and I4
    live). T2's bound and the multi-thread flake margin are cheap fixes worth
    doing at the same time.
  7. The rest as follow-ups. File the ByteSpan/AlignedRange threading separately —
    it is the largest structural win but a wider diff than this PR should carry.

Overall

The core design is sound and the hard parts are done well — the cancellation
protocol, the present-bytes backstop, and the terminal/retryable split are all
correct and correctly argued. The problems cluster in two places: payment
accounting across lanes
(C1, C4, C5, I4 — four independent ways one shared pool
gets treated as N independent ones) and what happens when things go wrong
(C2, C3, I1, I2, I3 — the retryable path discards its evidence, does not fall back,
and does not persist). The prose is also ahead of the code in ~15 places, mostly
from three late fix commits that changed behavior without revising the docs written
for the earlier ones.

I'd fix the payment-accounting cluster and C2/C3 before merge; the rest can land as
follow-ups.

@alpergundogdu alpergundogdu left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doc-convention cleanup not covered by the earlier review: seven comments in scheduler.rs reference internal task numbers or before/after states ("the Task-4 double-pay", "Task 4's bookkeeping-only steal", "the pre-fix scheduler/code/bug"). CLAUDE.md's present-tense canon rules these out — a cold reader has no way to resolve "Task 4", and history belongs in git. Each inline comment carries a suggested present-tense rewrite that keeps the technical content (the counterfactuals stay; only the task numbers and pre/post-fix framing go).


Generated by Claude Code

Comment thread crates/client-pull/src/scheduler.rs Resolved
Comment thread crates/client-pull/src/scheduler.rs Resolved
Comment thread crates/client-pull/src/scheduler.rs Resolved
Comment thread crates/client-pull/src/scheduler.rs Resolved
Comment thread crates/client-pull/src/scheduler.rs Resolved
Comment thread crates/client-pull/src/scheduler.rs Resolved
Comment thread crates/client-pull/src/scheduler.rs Resolved
alpergundogdu and others added 18 commits August 24, 2026 01:13
initial_segments and steal_split each rounded a raw, possibly unaligned
byte-range end up to the next bao chunk-group boundary via align_range,
but compared that ceiling against the raw unaligned end. Two gaps
separated by less than one group of held data (or a range whose true
end fell mid-group) could produce two AlignedRanges whose fetch spans
overlapped by up to one group -- a double-fetch and, once the
multi-source scheduler pays per source, a double-pay.

Canonicalize every input span to its enclosing group boundaries (and
merge touching/overlapping spans) before splitting, so every boundary
handed to align_range is already aligned and its ceiling-up can never
carry a segment past where the caller intended it to stop.
…ing them

canonicalize_ranges clamped a span's rounded-up end to total_bytes to
handle the blob's legitimate partial last group, but that same clamp
silently absorbed a genuinely out-of-bounds span too: a gap whose
start was at or past total_bytes was dropped, and one whose raw
(pre-rounding) end exceeded total_bytes was silently truncated. This
contradicted the still-documented RangeVerifyError propagation and the
repo's fail-loudly-on-malformed-input convention.

canonicalize_ranges now checks each span's start and raw end against
total_bytes before any rounding, and returns
RangeVerifyError::RangeOutOfBounds -- the same error align_range
itself raises -- for a span that is genuinely out of bounds. The
legitimate final-partial-group clamp (raw end == total_bytes, rounds
up then clamps back down) is unaffected and still succeeds.
Fan a request across several paid sources over one shared store (spec
§5.3): bao-aligned segmentation, one worker per source, and a freed
source steals the aligned second half of the largest in-flight range.
One outstanding unit per source (lane correctness). Node path untouched.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Adds the CLI-side pieces for ADR 039 multi-source fetch: --multi-source
(default on) / --no-multi-source, --max-sources, --multi-source-min-bytes,
--unit-deadline-ms on ClientFetchArgs, and the pure should_multi_source
engagement gate (enabled && total_bytes > min_bytes && admissible >= 2) in
crates/cli/src/commands/fetch.rs, covered by a TDD unit test.

Wiring the gate into drive_fetch/bundle_pull is deliberately deferred: see
task-7-report.md for why multi_source_fetch's single shared ctx/ledger/funder
cannot yet correctly pay several distinct-provider sources at once.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…or multi-source; wire scheduler into fetch/bundle

multi_source_fetch now takes a SourceLane set — each source paired with its
OWN PoolContext (provider) + PoolLedger — instead of one shared ctx/ledger, so
a voucher is signed against the source's real on-chain provider and each lane's
cumulative advances independently (ADR 039 § Payment model). fill_gap gains an
optional aggregate-committed reader: multi-source workers gate remaining_deposit
on pool_deposit - Σ committed across every lane, so concurrent lanes cannot each
treat the whole deposit as their own; the single-source drive path passes None
and is unchanged. Wired into `decdn fetch`: when should_multi_source engages,
build one per-provider lane per admitted candidate and call multi_source_fetch,
else the single-source failover loop runs unchanged.

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

Strengthen the multi-source solvency coverage (review finding #1): the existing
observation test only proved the pacer SEES deposit-minus-Σcommitted. Add
shared_gate_refuses_a_second_leg_into_a_drained_pool, which proves the gate
actually BLOCKS. A peer lane's ledger is pre-seeded near the deposit; the healthy
lane fetches its own segment, then is refused the reassigned second segment
because the aggregate remaining is below the next voucher cost. Asserts the fetch
ends incomplete, the healthy lane bills exactly one segment (never the refused
second), and combined committed stays within deposit + one in-flight leg — the
honest leg-boundary bound (on-chain redemption is the hard backstop). RED against
a naive own-committed gate: the fetch completes and the lane bills two segments.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…to one interval (spec §5.5)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ce scheduler instead of masking as "all sources failed"

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ti-source scheduler; keep single-source failover on budget refusal

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…rom PR review

Address the review on #1773. Payment accounting first, then what happens when
things go wrong, then the coverage that would have caught either.

Payment accounting across lanes:

- `admit_sources` admits at most ONE node per operator. A voucher lane is keyed
  on `(signer, provider)` and `provider` IS the operator address, so filling
  spare slots with a repeat operator built two concurrent voucher streams on one
  watermark and collided two watermark writes under one `LaneKey`. The admitted
  set now shrinks instead. `multi_source_fetch` re-checks the same precondition
  on the lane set it is handed, so the premise is verified at the boundary
  rather than asserted in prose.
- The deposit, the spend that gates it, and the reactive-top-up budget are facts
  of the POOL, not of a lane. They move behind one shared view: the gate
  subtracts the aggregate committed, the top-up budget is counted once per fetch
  rather than once per lane (4 lanes x 3 = 12 real escrows against a documented
  bound of 3), and a landed top-up credits EVERY lane rather than only the one
  that funded it.
- A multi-source lane persists its ARMED cumulative. A tail steal drops the
  victim's `fill_gap` future inside the voucher exchange on a SUCCESSFUL fetch,
  so settling that lane at `committed` persisted below what the node redeems.

Failure paths:

- Retryable worker errors are kept and reported. A failed fetch names each lane
  by its payee and carries the last real error as its cause, so a caller's
  downcast still reaches it — which is what makes the CLI's two-cause cache-miss
  diagnosis reachable on this path at all.
- A failed fan-out falls back to the single-source failover loop unless the
  failure is terminal. It resumes the same `.partial`, so nothing already paid
  for is re-bought.
- The present record is flushed on the error path too, in both `drive` and the
  scheduler: the bytes a failed fetch delivered are paid for.
- `is_complete`'s error is propagated rather than read as "not complete", which
  reported success with no output file on disk.
- A freed worker with nothing to steal PARKS instead of retiring, so it is still
  there when a peer faults and re-queues moments later.
- `steal_split` returns WHICH range it split, deleting a cross-module argmax
  agreement that had no compiler support; a steal that cannot trim its victim is
  declined rather than handed out untrimmed; `pick`/`clear` refuse an
  out-of-range worker index.
- The engagement gate applies its size floor to the probe's reported size before
  opening a pool and a throwaway header stream, and each decline says which
  condition was unmet.

Coverage:

- The stall watchdog had none, and the test named for it exercised the fault
  path. Renamed it, added a `stall_after` source double (a source that wedges
  WITHOUT erroring — the only shape that reaches the watchdog), and covered all
  four branches deterministically under a paused clock.
- The per-lane watermark rule is a pure function with tests: cross the lanes and
  nothing else in the fetch path would notice.

ADR 039 and the CHANGELOG record the behavior.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JjiDQL7FuB8UHGBBpG1PjH
@thiras
thiras force-pushed the claude/issue-1164-status-20c77a branch from c423f10 to 71fecd6 Compare August 23, 2026 23:08
@thiras

thiras commented Aug 23, 2026

Copy link
Copy Markdown
Contributor

Rebased onto main (the branch was conflicting) and addressed the Critical + Important findings plus T1/T3. Commit: 71fecd61.

Payment accounting (C1, C4, C5, I4)

  • C1 — admit_sources now admits at most one node per operator and the set shrinks rather than repeating one. Pass 2 is gone: provider IS the operator address, so a repeat operator is not parallelism the payment model can express. multi_source_fetch re-checks the same precondition on the lane set it is handed, so the premise is verified at the boundary rather than asserted in prose. Tests assert which candidates come back, not just how many.
  • C4 + C5 — the deposit, the spend that gates it, and the top-up budget are facts of the pool, not of a lane. They moved behind one shared view (SharedPool) threaded into fill_gap: the gate subtracts the aggregate committed, the budget is counted once per fetch, and a landed top-up credits every lane's ctx. Single-source passes None and is unchanged.
  • I4 — multi-source lanes persist settlement() unconditionally. You were right that the steal-cancel window lands on a successful fetch, which is exactly where select_watermark's Ok arm settles low.

Failure paths (C2, C3, I1, I2, I3, I5, I6)

  • C2 — per-lane faults are collected with the payee address; the fetch names each lane and wraps the last real error with .context(...), so downcast_ref still reaches it. That is what makes annotate_unbound_cache_miss reachable on this path at all. Watchdog stalls stay a separate None case with their own wording, per your Some/None split.
  • C3 — retry_disposition-gated. Only Terminal + PoolExhausted end the fetch; anything else warns and falls through to the failover loop.
  • I1 — final flush now runs on the error path in both drive and the scheduler; the drive error wins when both fail.
  • I2 — is_complete's error is propagated and completeness is ensure!d before reporting success.
  • I3 — a freed worker parks on a Notify instead of retiring, and leaves only when nothing is pending and no peer holds work. Verified by mutation: revert the park to a break and the new test fails.
  • I5 — steal_split returns Option<(usize, AlignedRange)>; the re-derived argmax and the comment reconciling it are deleted.
  • I6 — a steal that cannot trim its victim is declined rather than handed out untrimmed, and pick/clear bail! on an out-of-range worker index instead of no-op'ing.

I7 / I8

ProbeResponse.total_bytes already exists for exactly this ("so requesters can estimate cost"), so the hint is carried through Probed -> ResolvedTargets and the size floor is applied before any lane construction. Every decline now prints which condition was unmet.

Coverage (T1, T3)

  • T1 — you were right that nothing exercised the watchdog. with_fault_after can't: it takes the error arm. Added ScriptedSource::stall_after(n, Duration) — a source that wedges without erroring — plus a scripted-store double that drives all four branches under a paused clock. stalled_source_tail_is_reassigned_and_fetch_completes is renamed to faulted_..., which is what it always tested. Each branch is mutation-verified: disabling the watchdog, flipping >= to >, and dropping the now == 0 guard each fail a test.
  • T3 — the per-lane watermark rule is now a pure multi_lane_watermarks with tests covering key/cumulative pairing and the settle-high rule.

Not done in this pass

All of S1–S15 and the remaining T2/T4/T5 items, by scope decision — happy to take them as a follow-up. Two notes from working through them:

  • S11 is broader than ADR 039: ADR 037 § Fallback is cited at ten pre-existing sites across cli, client-pull, and common, and ADR 037 has no such heading. The adr/ hygiene hook only checks adr/, which is why it never fires on those.
  • S14's reputation-feedback gap is real and unaddressed; neither client-pull nor cli depends on decdn-reputation.

ADR 039 is updated where this changes behavior (one-node-per-operator as a payment rule, the parking semantics, the fallback answer you flagged as an unspecified gap, and the shared-pool facts), and the PR now carries a CHANGELOG entry.

Verified: 2934 workspace tests pass, clippy --all-targets clean, cargo fmt --check, cargo doc -D warnings, and the cli_fetch_engages_multi_source_across_two_holders anvil e2e passes against the real wire.

…n exit status

The journey retried `decdn fetch` until it exited 0, because a holder whose
chain watcher has not yet observed the freshly-opened pool refuses the stream
pre-serve. Exit status stopped being a readiness signal once a retryable
refusal on one lane falls back to single-source failover: the fetch now exits 0
having been served by the OTHER holder alone, the retry loop stops, and the
both-holders-paid assertion fails against a fetch that never fanned out.

Wait for what the journey actually asserts — one invocation that bills BOTH
lanes. Requiring both within a SINGLE invocation is what keeps it honest: a loop
that accumulated payments across attempts would pass on two single-source
fetches that each paid a different holder, which is the non-parallelized case
this journey exists to rule out. Each attempt clears the output and `.partial`
set first, so a resumed fetch cannot bill one lane for the other's remainder.

Reproduced at ~1 run in 4 before, 10/10 green after.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JjiDQL7FuB8UHGBBpG1PjH
@github-actions

Copy link
Copy Markdown

Gas snapshot

No gas changes vs base.

@github-actions

Copy link
Copy Markdown

Contracts coverage

Line coverage: 89.69% (2575/2871 lines)
▲ +0.00pp vs base (89.69% → 89.69%)
Run: 32675059158

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.

ADR 039: rewrite leaner as the single multi-source home, then implement the scheduler

4 participants