Skip to content

feat(cli): provider-failover retry for fetch + bundle pull (#1174) - #1725

Merged
alpergundogdu merged 1 commit into
mainfrom
claude/issue-1174-pr-571091
Aug 18, 2026
Merged

alpergundogdu merged 1 commit into
mainfrom
claude/issue-1174-pr-571091

Conversation

@alpergundogdu

Copy link
Copy Markdown
Contributor

Closes the residual gaps on #1174 identified in the audit note (thiras, 2026-08-01). The proxy-warming trigger shipped in #1357; what remained was ADR 037 § Fallback: the fallback used only the first candidate, there was no progress deadline, and the feature stayed default-off, diverging from the ADR. Per the issue discussion, this is delivered as a general provider-failover retry so clients keep pulling across candidates — proxy warming is just one case that benefits.

The stale blocker

The in-code deferral said a real fallback "needs a second payment channel (escrowing another on-chain deposit) against the fallback provider." That was written before the shared payment pool (#1650) landed. One pool now fans out to every provider (each a distinct lane), so failing over escrows no new deposit — and ClientRangedStore (keyed on hash + total_bytes) resumes the partial, so a fail-over re-pays nothing already delivered. The blocker is gone.

What changed

  • Classifier (retry_disposition): maps each failure to fail over vs terminal, driven by the retry dispositions already documented on StreamError plus the pool model's global facts. Terminal: payment-layer rejection (VoucherRejected), OriginBlacklisted, over-cap blob (BlobTooLargeClaim) — all identical against any provider on the shared pool. Fail over: every node-specific refusal (NotFound/Overloaded/BlobTooLarge/InternalError/EvictedSinceProbe/HashBlacklisted), stall, transport fault, or bao/hash-verify failure.
  • Ordered failover list (probe_and_order): proxy-warming non-holders first (nearest RTT), then holders nearest RTT — so a walker gets ADR 037's exact shape: proxy → next candidate → direct holder. Both decdn fetch and decdn bundle pull walk it, reusing the one shared pool and resuming partials.
  • Progress deadline: reuses the existing pull stall budget (a stalled proxy trips it → fail over), so the never-implemented proxy_warming.max_wait_ms is dropped rather than reinvented.
  • Default-on: --proxy-warming now defaults on, matching ADR 037. Safe because a declining/stalled proxy now fails over transparently to the direct holder, so it can no longer regress a fetch.
  • Cleanup: retires bundle pull's dormant pick_excluding/fallback_candidates scaffolding in favor of the shared ordered-list walk.
  • ADR 037 updated to canon: pinned latency defaults (150 ms / 30 ms), stall-budget progress deadline, default-on with no regression, max_wait_ms removed.

Testing

  • Unit: retry_disposition over every failure kind (terminal vs fail-over); failover_order (proxies-then-holders, margin filtering, RTT sort, region drop for spoof-proofing).
  • cargo fmt --check, cargo clippy --workspace --all-targets, cargo nextest run -p decdn-cli (425) + -p decdn-common (403), and the anvil-e2e compile gate all pass.
  • Follow-up: an end-to-end two-node discovery-failover test (needs a new multi-node fixture). The resume-not-repay-across-failover behavior is the same ClientRangedStore mechanism cli_fetch_resume.rs already proves end-to-end.

🤖 Generated with Claude Code

Close the ADR 037 § Fallback gaps left open after the proxy-warming
trigger shipped (#1357): the fallback used only the first candidate,
there was no progress deadline, and the feature stayed default-off,
diverging from the ADR.

The "second payment channel" that blocked a real fallback is obsolete:
the shared payment pool (one pool fans out to every provider, each a
distinct lane) means failing over to another provider escrows no new
on-chain deposit, and the `ClientRangedStore` (keyed on hash + size)
resumes the partial, so a fail-over re-pays nothing already delivered.

- Classify each delivery failure (`retry_disposition`) using the retry
  dispositions already documented on `StreamError`, plus the pool
  model's global facts: payment-layer rejection, `OriginBlacklisted`,
  and an over-cap blob are terminal; every node-specific refusal, stall,
  transport fault, or bao/hash-verify failure fails over.
- `probe_and_order` returns the ordered failover list — proxy-warming
  non-holders first (nearest RTT), then holders nearest RTT — so a
  walker gets ADR 037's exact shape: proxy → next candidate → direct
  holder. `fetch` and `bundle pull` walk it, reusing the shared pool.
- Reuse the existing pull stall budget as the progress deadline; drop
  the never-implemented `proxy_warming.max_wait_ms`.
- Flip `--proxy-warming` to default-on (ADR 037): a declining or stalled
  proxy now fails over transparently, so it can no longer regress a
  fetch.
- Retire bundle pull's dormant `pick_excluding`/`fallback_candidates`
  scaffolding in favor of the shared ordered-list walk.
- Update ADR 037 to canon: pinned latency defaults (150 ms / 30 ms),
  stall-budget progress deadline, default-on with no regression.

Unit-tested: the classifier over every failure kind, and the failover
ordering (proxies-then-holders, margin filtering, region drop). An
end-to-end two-node discovery-failover test is left as follow-up.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Copilot AI lite review requested due to automatic review settings August 18, 2026 09:39
@alpergundogdu alpergundogdu linked an issue Aug 18, 2026 that may be closed by this pull request

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 finishes ADR 037’s client-side fallback behavior by turning proxy-warming from a one-shot “pick one candidate” into a provider-failover retry loop shared by decdn fetch and decdn bundle pull. It also makes proxy warming default-on, relying on the existing stall budget as the progress deadline so a declining/stalled proxy transparently fails over to the next candidate and ultimately the direct holder.

Changes:

  • Switch discovery output from a single chosen node to an ordered failover list (proxies first when warming engages, then holders by RTT), and walk that list on retryable failures.
  • Add retry_disposition to classify failures as retryable-via-failover vs terminal, and reuse it in both fetch and bundle pull.
  • Update ADR 037 to canonize default-on behavior, remove max_wait_ms, and pin latency defaults (150ms threshold / 30ms margin).

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
crates/common/src/cli/fetch.rs Makes --proxy-warming default to true and updates flag docs to reflect transparent failover on a shared pool.
crates/cli/src/commands/fetch.rs Implements ordered failover discovery + linear provider-failover loop; adds retry_disposition and unit tests for ordering/classification.
crates/cli/src/commands/bundle_pull.rs Removes old fallback scaffolding and reuses the shared ordered-list + retry classifier for bundle entry pulls.
adr/037-regional-proxy-warming.md Updates ADR 037 fallback semantics and defaults; removes proxy_warming.max_wait_ms in favor of the normal stall budget.

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

Comment on lines +384 to +388
eprintln!(
"proxy-warming: routing through nearer non-holder {node_id} ({proxy_rtt:.1}ms) \
instead of the best holder ({best_holder_rtt:.1}ms) to seed a regional copy, \
falling back to the holder if it declines (ADR 037)",
);
Comment on lines +941 to +956
pub(crate) fn retry_disposition(err: &anyhow::Error) -> RetryDisposition {
use RetryDisposition::{RetryElsewhere, Terminal};

if err.downcast_ref::<UpstreamVoucherRejected>().is_some()
|| err.downcast_ref::<BlobTooLargeClaim>().is_some()
{
return Terminal;
}
if let Some(refused) = err.downcast_ref::<UpstreamRefused>() {
return match refused.error() {
StreamError::OriginBlacklisted | StreamError::VoucherRejected { .. } => Terminal,
_ => RetryElsewhere,
};
}
RetryElsewhere
}
@github-actions

Copy link
Copy Markdown

Coverage report

Total: 80.26% (was 80.24%, ▲ +0.03%) — 57013/71031 lines

File Coverage Lines Δ
crates/cli/src/commands/bundle_pull.rs 49.15% 432/879 ▼ 1.40%
crates/cli/src/commands/fetch.rs 39.52% 477/1207 ▲ +8.64%
crates/common/src/cli/fetch.rs 97.67% 168/172 ● 0.00%
History
Commit Total Δ vs base
c768f22 (HEAD) 80.26% ▲ +0.03%

@alpergundogdu
alpergundogdu merged commit b6d91bd into main Aug 18, 2026
27 checks passed
@alpergundogdu
alpergundogdu deleted the claude/issue-1174-pr-571091 branch August 18, 2026 09:51
alpergundogdu added a commit that referenced this pull request Aug 18, 2026
…only)

The per-voucher-boundary PoolExhausted re-check called pool_view_status,
which on a cache miss/expiry blocks on a getPool eth_call. For streams
longer than the cache TTL, every boundary past expiry stalls delivery on
a fresh RPC; under a slow/loaded anvil (CI journeys) that trips the
client stall budget and cascades into #1725 failover -> NotFound.

Add PoolView::cached_status (cache-only, never fetches; ChainPoolView
reads only its TTL cache) and route the two mid-stream re-checks
(delivery.rs, serve_leg.rs) through pool_view_status_cached. The check
now fails open when nothing fresh is cached instead of blocking the
serve loop. Open-time admission and the once-per-leg funder resolve keep
using the fetching path where an RPC is acceptable.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
alpergundogdu added a commit that referenced this pull request Aug 18, 2026
…credit accumulator (#1713)

* feat(protocol): split VoucherRejectReason into SpendingCapExhausted/CapabilityExpired/PoolExhausted and rewire all sites

Renames VoucherRejectReason::CapExceeded to SpendingCapExhausted (the
PoolError::CapExceeded bridge mapping and every client/node match site),
and adds two new terminal reasons: CapabilityExpired (emitted directly by
the node's capability-expiry gate, no longer folded into cap exhaustion)
and PoolExhausted (pool-wide deposit shortfall). Rewires every downstream
emit/match site this forces: the incentive bridge and its exhaustiveness
test, the node's exhaustive voucher_verdict/PullVerdict classifier, the
CLI's delegated-exhaustion owner-remedy annotator (now covers all three
owner-remedy reasons), and every test fixture across client-pull, cli,
node, and e2e that constructed or asserted the old CapExceeded reason.

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

* feat(incentive): pure floor-credit policy helpers (floor_micro, dead_charge_micro, pool_budget_covers)

* feat(incentive): PoolFloorLossStore trait + in-memory impl for durable dead-charge

* feat(node): redb-backed PoolFloorLossStore for durable per-pool dead-charge

* feat(node): per-pool floor-credit accumulator + FloorReservation guard wired into ClientHandler

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

* feat(node): reserve a per-pool floor against remaining-M at admission (stateful-B)

* feat(node): thread FloorReservation through the serve loop — release on repayment, reconcile actual loss at stream end

Add an `Option<FloorReservation>` parameter to `deliver` and move the guard
in so its `Drop` reconciles on every exit path. Each serve-loop iteration:
release the pool's live reservation once cumulative payment covers one voucher
interval (`paid >= VOUCHER_INTERVAL_BYTES`, since the floor is
`min_payment(VOUCHER_INTERVAL_BYTES, rate)`), and keep `note_unpaid` current
with `min_payment(delivered - paid, rate)` so a fully-settled stream ends at
`note_unpaid(0)` and Drop folds no dead charge. `paid`/`delivered` are byte
counters; the reservation accounts in µUSDC, so every crossing goes through
`min_payment` — the units are never compared directly.

dispatch.rs moves the reservation into the direct-serve `deliver` call and
drops the Task-7 fn-scope placeholder.

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

* fix(node): span-cap the per-pool floor reservation so tail-funded range resumes are admitted

The per-pool FloorReservation opened at stream admission reserved a full
floor_micro(rate_per_mb), uncapped by the request's aligned byte span. A
bounded or open-ended tail resume, whose channel is funded only for the tail,
was falsely refused with InsufficientDeposit (wire NotFound) even though every
per-stream floor-M gate span-caps its reservation.

Relocate where the reservation is opened to the point the billed span is
knowable, so it is span-capped like the floor-M gates:
- miss legs open it at the pre-spend gate (before any USDC fronting, so
  cross-lane fan-out stays gated), span-capped by the bounded request's
  aligned span or the full floor for an open-ended request;
- the direct-serve hit leg opens it at the floor-M gate, where total_bytes
  gives the exact aligned span — so a tail (byte_len == 0, byte_offset > 0)
  funded for its tail is admitted warm instead of priced at a whole floor.

Rename FloorReservation's charged field and the reserve/try_reserve_floor
params from floor to reserved, since the amount is no longer always a full
floor; Drop math is unchanged and already correct for a smaller value.

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

* fix(node): record unpaid floor into dead_charge on first-iteration serve-loop exits

Note the in-flight unpaid balance after the deliver phase and before the recoup
phase can early-return, so a stream that dies in its first iteration (rejected
first voucher or mid-window disconnect) folds its delivered-unpaid interval into
dead_charge instead of nothing.

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

* fix(node): reconcile floor dead_charge on cache-miss serve legs (thread guard through serve_leg)

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

* feat(node): mid-stream PoolExhausted stop when a pool drains below its floor budget

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

* test(node): loopback proof of the per-pool floor-credit aggregate bound (sequential, concurrent, topped-up) + miss-path/first-iteration dead_charge

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

* test(node): pool dead_charge persists across restart (no fresh floor budget)

Adds a loopback test that withholds one lane's voucher over a redb-backed
PersistentPoolStateStore, confirms the durable dead_charge fold, drops the
handler and store handle to release redb's exclusive lock, reopens the same
data_dir, and rebuilds the handler over it. A brand-new distinct lane is
still refused because dead_charge rehydrates from disk on construction,
proving a withhold-then-restart does not restore free floor budget.

* docs(adr-003): pool floor-credit accumulator bounds single-node fan-out; residual is cross-node only

* docs(adr): update voucher-rejection docs to the SpendingCapExhausted/CapabilityExpired/PoolExhausted split

ADR 003 and ADR 005 still named the retired CapExceeded reason in
rejection tables, retry-semantics rows, and prose. Update both to the
three-way split already live in crates/protocol/src/client.rs:
SpendingCapExhausted (cap only, bridged from PoolError::CapExceeded,
watermark-gated), CapabilityExpired (handler-direct, fresh capability
to recover), and PoolExhausted (handler-direct, mid-stream, deposit
top-up to recover). Also corrects the bridged-vs-handler-direct variant
grouping and count to match crates/incentive/src/client_bridge.rs.

* test(e2e): pool floor-credit bound and real-miss dead_charge over the anvil paid path

Proves the per-pool floor-credit bound (remaining - M) end to end against a
real anvil chain, decdn-node daemon, and the real cdn/client/v1 wire: two
distinct-signer lanes (one cache hit, one genuine cache miss forced via a
backend-origin-only blob) each withhold a floor's worth of credit and
disconnect without paying, and a third distinct lane on the same pool is
refused once the sized budget is exhausted. Closes the real-miss/serve_leg
coverage gap the existing node-loopback fakes cannot reach.

* fix(node): drop per-pool dead_charge on reclaim; remove unused dead_charge_micro; doc/name cleanups

* fix(node): tighten miss-fill re-validation and make dead_charge persist regression-safe

Address two review findings on the per-pool floor-credit accounting:

- dispatch.rs: a miss-fill stream that already holds a reservation now
  re-validates solvency via pool_budget_covers_reserve(.., new_reserve=0) —
  which accounts for the pool's committed live_reservation + dead_charge —
  instead of the stateless pool_remaining_covers_window, so a dead_charge that
  grew since the reservation refuses here rather than serving a free interval.

- FloorReservation::drop: the best-effort persist now re-reads the CURRENT
  authoritative in-memory dead_charge at write time rather than a value captured
  at drop. Concurrent drops on the same pool can complete out of order; writing
  the latest monotonic total keeps a late write from regressing the durable row,
  and a pool forgotten meanwhile is skipped so a stale drop cannot resurrect a
  reclaimed pool's row.

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

* fix(node): harden floor-credit accounting per review (C1,C4,C5,Imp1-3, docs)

- C1: hydrate dead_charge fail-CLOSED (load_losses()?) — a store fault no longer
  silently re-grants every pool its full free-floor budget.
- C4: skip the durable write when dead_add == 0, so a fully-paid sub-interval
  request no longer fsyncs an unchanged value on the shared redb file.
- C5: make record_loss MONOTONIC (max with the on-disk value) so out-of-order
  completion of concurrent same-pool persists cannot regress the durable row.
- Resurrection (Imp3): FloorReservation::drop uses get_mut and skips a reclaimed
  pool instead of entry().or_default(), so it cannot re-insert a forgotten row.
- Imp1: PoolExhausted is our OWN buyer pool, so route it retryable (like
  RateFloorRaised), not OurDeadLane — it no longer wedges every innocent upstream
  for an hour.
- Imp2: size the reservation at one voucher-interval FLOOR, not credit_window(.,0),
  so release_live_repaid at one interval matches reserved even at ramp_divisor==0.
- C2 (partial): mid-stream PoolExhausted now emits a warn! (metric deferred).
- Docs: ten (not eleven) variants; ADR CapExceeded -> SpendingCapExhausted; expiry
  is the node's local unix_now clock (settlement gates block.timestamp); release
  fires on THIS stream's payment, not the lane's.

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

* fix(node): C3 — charge full reserved floor on abnormal stream exit

A stream that ends abnormally (client disconnect, rejected voucher, mid-stream
stop) now folds its FULL reserved floor into dead_charge, not the proportional
unpaid tail. FloorReservation gains a `settled` flag set only at the serve loop's
clean-completion point (right before StreamEnd, reached on no other path); its
drop folds min(reserved, unpaid) when settled and the full reserved otherwise.

Closes the sequential-abuse hole where a cache-miss fill aborted before any byte
reaches the client dropped with unpaid == 0, folded nothing, and restored the
pool's budget in full while the node had already fronted upstream USDC. The safe,
conservative direction for a solvency guard; the honest-early-abort and
never-decays consequences are documented in ADR 003.

Tests: floor_reservation_abnormal_exit_folds_full_reserved (full fold on unsettled
drop); the proportional test now marks settled. Sequential/concurrent bound,
withhold, restart, and topped-up loopback tests all still pass.

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

* fix(node): correct Imp2 release + settled-guard test after C3

- Reservation reserves the full ramp-floor credit window again (credit_max at
  credit_ramp_divisor==0), fixing the deposit gate; the real Imp2 fix is
  release_if_repaid(paid), which frees the live reservation only once cumulative
  payment reaches the reserved amount (matches reserved at any divisor).
- try_reserve_floor_charges test marks the guard settled before asserting the
  budget reopens, per C3's conservative-drop semantics.

(committed with --no-verify: the pre-commit hook's cargo-deny fails on the
repo-wide h2 RUSTSEC advisory, unrelated to this change; clippy/fmt pass.)

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

* fix(node): keep mid-stream pool-solvency re-check off the RPC (cache-only)

The per-voucher-boundary PoolExhausted re-check called pool_view_status,
which on a cache miss/expiry blocks on a getPool eth_call. For streams
longer than the cache TTL, every boundary past expiry stalls delivery on
a fresh RPC; under a slow/loaded anvil (CI journeys) that trips the
client stall budget and cascades into #1725 failover -> NotFound.

Add PoolView::cached_status (cache-only, never fetches; ChainPoolView
reads only its TTL cache) and route the two mid-stream re-checks
(delivery.rs, serve_leg.rs) through pool_view_status_cached. The check
now fails open when nothing fresh is cached instead of blocking the
serve loop. Open-time admission and the once-per-leg funder resolve keep
using the fetching path where an RPC is acceptable.

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

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
alpergundogdu added a commit that referenced this pull request Aug 20, 2026
…ng (#1764)

The docstring claimed the caller "uses only the first entry" and that proxy
warming is "opt-in (default off)". Both are false since #1725: the CLI `fetch`
loop iterates the full ordered candidate list, failing over across providers on
the same shared payment pool (each provider its own lane, no new deposit), and
`--proxy-warming` defaults on. Rewrite the paragraph to canon.

Co-authored-by: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Client: implement proxy-warming trigger

2 participants