Repository navigation
Description
Problem
decdn fetch is single-file/single-node/sequential today. As soon as we fetch
multiple blobs concurrently and reuse a channel for overlapping nodes (the
same node serves several of the requested files — the efficient, expected CDN
case), concurrent voucher issuance on the shared channel collides.
A payment channel is a single serial cumulative ledger: nonce, bytes_delivered,
and amount are all channel-wide monotonic values. The client, however, snapshots
that ledger immutably per stream:
ChannelContext.prior_nonce / prior_bytes_delivered / prior_amountis a value
snapshot read once when the context is built
(crates/client-pull/src/lib.rs:49, built atcrates/cli/src/commands/fetch.rs:457).- Each stream runs its own
VoucherProgress, seeded tovouchers_sent = 0
(crates/client-pull/src/lib.rs:154). self_paycomputesnonce = prior_nonce + vouchers_sent + 1and
bytes/amountfrom the same snapshot (crates/client-pull/src/lib.rs:879-896).
Two concurrent streams to the same provider both snapshot prior_nonce = N,
both start at vouchers_sent = 0, both sign nonce N+1 for overlapping
cumulative bytes. The seller rejects the second (NonceNotIncreasing,
crates/incentive/src/channel.rs:272) and that fetch fails. The existing test
client_concurrent_same_channel_accepts_one_voucher
(crates/node/tests/client_loopback.rs:1639) already asserts exactly one of
two concurrent fetches succeeds — i.e. the collision is real and currently
"handled" by failing all-but-one.
There is no client-side serialization of voucher issuance per channel.
Why this is client-only
The node and wire are already built for concurrent streams sharing one channel:
- Per-channel async mutex serializes voucher application across a channel's
concurrent streams — "ADR 003 §concurrent streams"
(crates/node/src/handlers/client.rs:241). - The node tracks one
bytes_delivered_cumulativeper channel and reconstructs
bytes_deliveredserver-side; it is not on the wire
(crates/node/src/handlers/client.rs:90,crates/protocol/src/client.rs:406).
So multiplexing many blobs from one node over one reused channel is a supported
shape on the wire — the gap is purely the client's per-stream snapshot.
Goal
Pull multiple blobs concurrently from a single node over one reused payment
channel (BitTorrent-style multiplexing) without nonce collision or double-counted
bytes. Data transfer stays parallel; only voucher issuance serializes.
Recommended fix
Replace the per-stream watermark snapshot with one serialized watermark per
channel that all concurrent streams to that provider draw from (a Mutex-guarded
live watermark, or a single-owner issuer task). Each voucher's send→ack holds the
per-channel lock so vouchers reach the node in monotonic nonce/cumulative order;
the data streams interleave freely. Concurrency across distinct nodes is already
independent (different channel → different lock), so no change there.
Concretely:
- The client-side channel watermark becomes shared mutable state per provider/channel,
not a value copied into eachChannelContext. - Voucher signing draws
nonce/cumulative-bytes/cumulative-amountfrom that
shared state under the lock, advancing it on ack — replacing the per-stream
prior_* + vouchers_sentarithmetic.
Open design point [decide before implementing]
Two shapes for where the voucher round-trip happens:
- Per-stream voucher exchange, shared watermark (smaller change). Each delivery
stream still sends its own vouchers, but draws nonce/cumulative from the shared
per-channel watermark under the lock. No wire change. - Dedicated payment side-channel (cleaner, bigger change). Data streams carry no
vouchers; one issuer pumps cumulative vouchers over a separate stream. Touches the
cdn/client/v1protocol and the node serve loop.
Proposal: implement (1) first; revisit (2) only if the per-stream lock contention
shows up under real concurrency.
Tests to add
- Concurrent fetch of N blobs from the same provider over one reused channel —
all succeed, nonces strictly increasing, channel cumulative bytes/amount correct. - Mixed: concurrent fetches across overlapping + distinct providers — distinct ones
run in parallel, overlapping ones serialize correctly. - Update/replace
client_concurrent_same_channel_accepts_one_voucher: its current
"exactly one succeeds" assertion encodes the bug and must flip to "all succeed".
Acceptance
Concurrent multi-blob fetch from overlapping nodes completes with every blob
delivered and a single monotonic voucher sequence per channel; no NonceNotIncreasing
rejections under honest concurrent issuance.
Hot-path / overhead notes (avoid the obvious trap)
The synchronization must stay in-memory. Do not read or write the redb store
per chunk.
- The durable store (
RedbBuyerChannelStore) is touched twice per fetch today —
at open, and once after the stream completes (crates/cli/src/commands/fetch.rs:416,
gated onprogress.acked()). Per-voucher advance is in-memorycommit_ack
(crates/client-pull/src/lib.rs:909). Keep it that way: the shared per-channel
watermark is in-memory; redb persists at open + completion only. - The live coordination is an in-memory
Mutex<watermark>per channel. Uncontended
acquisition is nanoseconds — acquisition is not the cost. - The real cost is holding the channel lock across a voucher's send→ack RTT, which
serializes concurrent streams' payment round-trips. Bound it by voucher
cadence, not chunk count: vouchers are cumulative + channel-wide, so issue one
every M bytes / T ms aggregated across all streams. Data streams interleave freely
in between; the voucher only has to stay ahead of served bytes within the node's
rate tolerance. - Spurious rejection risk = out-of-order nonce arrival at the node (strictly-increasing
check,crates/incentive/src/channel.rs:272). Serializing the send→ack under the
per-channel lock is what prevents it. This is the correctness anchor, not an
optimization.
Anti-pattern to avoid: a DB read for the current nonce at the end of every chunk,
and/or one voucher per stream per chunk. That is the overhead this issue is worried
about, and it is not required.
Cross-process concurrency (two decdn fetch at once)
The in-memory per-channel watermark above only coordinates streams within one
process. Two separate decdn fetch processes are handled by redb's lock instead:
- Same (default)
data_dir: redb (4.1.0) holds an exclusive cross-process file
lock on the buyer-channel DB for the lifetime of the openDatabase
(crates/cli/src/commands/fetch.rs:329→RedbBuyerChannelStore::open). The second
process'sDatabase::createreturnsDatabaseAlreadyOpenand the fetch fails fast.
Blunt (whole-process granularity, fail-not-queue) but SAFE — no shared live watermark,
so no nonce corruption. - Different
--data-direach: independent stores → independent channels →
independent nonces, no collision. Works, but each process opens its own on-chain
channel to the node and locks its own deposit (no reuse, split funds).
Decisions [your call]:
- Confirm the
DatabaseAlreadyOpenpath surfaces a clear user-facing message
("another decdn fetch is using this data dir"), not a raw redb backend string.
Add a test for it. - Truly-concurrent cross-process shared-channel fetch is explicitly out of scope:
it would require cross-process nonce coordination, which redb's single-writer model
only provides via read-advance-commit per voucher under the DB write lock — the
per-chunk DB sync overhead this issue rules out. The supported answer is one fetch
process that multiplexes internally (the fix above), not N fetch processes.
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Activity
github-actions commentedon Jun 18, 2026
🎯 Triage report
Confirmed client-side race condition: concurrent streams to the same node both snapshot
prior_nonce = Nand independently compute voucherN+1, causing the node to reject all-but-one withNonceNotIncreasing. The bug is already encoded in an existing test (client_concurrent_same_channel_accepts_one_voucher) which asserts only one of two concurrent fetches succeeds. The server side already supports concurrent streams over a shared channel via a per-channel async mutex — the gap is purely in the client's per-stream watermark snapshot.📊 Assessment
high,testingadded (existing:bug,technical,rust,cli)Mutex-guarded watermark), specific tests listed, acceptance criteria stated, performance anti-patterns documented🔗 Similar issues
client-pullvoucher tracking subsystem, similar pattern of per-stream state diverging from channel-level truth💡 Notes and suggestions
Root cause (one-liner):
ChannelContextis a value snapshot — once cloned per stream it's frozen, so two concurrent streams each believe they're the first to issue a voucher on the channel.Recommended implementation path (option 1 from the issue):
Arc<Mutex<ChannelWatermark>>keyed by(provider_peer_id, channel_id)in the fetch command, replacing the currentChannelContextvalue copy.ChannelWatermarkholds{nonce, bytes_delivered_cumulative, amount_cumulative}— the three fields currently inprior_*snapshot.self_pay, acquire the lock, sign, send voucher, await ack, advance the watermark, release the lock. Data chunks interleave freely; only the voucher round-trip serializes.VoucherProgress.vouchers_sentper-stream counter becomes unnecessary and can be removed (or kept for per-stream diagnostics only, decoupled from the cumulative).Test checklist (from the issue):
client_concurrent_same_channel_accepts_one_voucher— flip assertion from "exactly one succeeds" to "all succeed, nonces strictly increasing"Design decision to resolve before merging: The issue flags option 2 (dedicated payment side-channel with no vouchers on data streams) as a cleaner long-term shape, but recommends deferring until lock contention is observable under real concurrency. The open question should be acknowledged in the PR with an explicit "revisit under profiling" note to avoid it being re-raised in review.
File locations to change:
crates/client-pull/src/lib.rs—ChannelContext,VoucherProgress,self_pay(~lines 49, 154, 879–896)crates/cli/src/commands/fetch.rs—ChannelContextconstruction and reuse (~lines 416, 457)crates/node/tests/client_loopback.rs— updateclient_concurrent_same_channel_accepts_one_voucher(~line 1639)Add this agentic workflows to your repo
To install this agentic workflow, run
alpergundogdu commentedon Jun 18, 2026
Design proposal: client puller daemon (an unregistered, pull-only node)
The fix sections above coordinate voucher issuance within one process. This
proposal addresses the broader case the original problem hints at — multiple
independent local processes (e.g. concurrent
pnpm install-style dependencypulls) wanting to share one wallet, one channel per node, and a deduplicated
blob cache — by introducing a single local owner instead of trying to make N
processes co-sign on one channel.
Why a daemon, not cross-process coordination
A payment channel is a single serial cumulative ledger, and the shared wallet
has two nonce spaces: the on-chain tx nonce (open/deposit/settle) and the
per-channel voucher nonce (per delivery). Two independent processes signing on
one channel hit:
crates/incentive/src/channel.rs:272)— out-of-order arrival rejects the laggard even though it delivered bytes;
send→ack RTT (a file lock around network I/O — bad).
A single owner of the wallet + channels removes all of it. Add a shared,
content-addressed blob cache and the same owner also stops re-paying the network
for content already pulled. That owner is a local, ephemeral, pull-only node —
conceptually a torrent client's background process: it serves nothing to the
network, never registers, and coordinates the user's downloads.
Shape
It is the existing
decdn-node, wired in a pull-only mode: cache engine +buyer-channel service + client-pull + a local control socket — minus serve
handlers, gossip announce, registration, seller-channel, and origin adapters.
Mode selection stays strictly at the node crate's wiring layer (per
appendix-poc-production-seams); leaf crates keep no mode branching.Decisions
decdn-nodecrate, selected at the wiring layerprotocol::framing) over a local socket — unix domain socket (0600) on Unix, named pipe on Windows — behind a transport seam. No HTTP. In-process and HTTP remain pluggable adaptersCacheEngine(iroh-blobs) + auto-evict; dedups the paid network pull; single-flight coalescing of concurrent same-hash requests--output; control-plane/data-plane split;rangereserved for partial; streaming deferredTransport seam (communication layer, fully separated)
The team's requirement: no HTTP for the daemon, and the comms layer swappable
(socket / IPC / in-process / future HTTP). Three layers, the middle one generic
so transports are interchangeable. Zero new dependencies —
protocol::framingand
tokio(features=["full"], which includesUnixListener+named_pipe+duplex) are already in the tree.trait DownloadService { async fn handle(&self, DaemonRequest) -> DaemonResponse },implemented by the download manager (cache + buyer-channel + client-pull). It
knows nothing about sockets.
DaemonRequest/DaemonResponseare serde enums incommon(alongside the admin DTOs;common → protocolalready holds, so it canuse
framing).DaemonRequestframe via
read_frame/decode_message, callssvc.handle, writes theDaemonResponseframe. Generic overAsyncRead + AsyncWrite + Unpin, so it runsunchanged over a
UnixStream, a named pipe, an in-memoryduplex, or TCP.UnixSocketListener(0600 socket in thedata-dir),
NamedPipeListener(Windows),InProcess(direct call /mpsc+oneshot— the same-process "multi-thread / sync" case), and HTTP remainspossible as just another adapter. Each only accepts a connection and hands the
stream to the serve loop. The only platform-specific code is a ~dozen-line
cfgsplit selecting the default local listener.
Rust IPC options considered: tokio UDS +
named_pipe+ existingframing(chosen — already in-tree);
interprocess(unifies UDS/pipe behind one API —back-pocket if the
cfgsplit gets annoying, costs a dep);tarpc(transport-agnostic RPC framework — overkill vs. a 30-line serve loop when
framingexists);tonic/gRPC and Cap'n Proto (gRPC is HTTP/2 — the thing we're removing; Cap'nProto is heavy codegen) — both rejected.
Components
CacheEngine,BuyerChannelService,client-pull, the local control listener, iroh endpointwith client discovery. No announce/register/serve/seller wiring.
common):DaemonRequest/DaemonResponse+ theDownloadServiceport + the generic serve loop + a
DaemonClient. ThedecdnCLI uses theclient. No secret ever on this channel.
BuyerChannelService): holds the unlocked signer; asingle in-memory watermark per channel feeds cumulative voucher signing;
open_or_reuse+advance_progressalready exist. Being the sole signer alsoserializes the on-chain tx nonce for free.
CacheEngine): single-flight per hash (concurrent/sequentialrequests for the same content share one pull and one payment); auto-evict
manages lifetime.
the node in pull-only mode, waits for ready, connects. A startup lock collapses
the "two CLIs spawn at once" race to a single daemon.
Data flow (one fetch)
decdn fetch <hash> -o outconnects to the local control socket; if a node isalready listening (registered or pull-only) it is used as-is, otherwise the
daemon is auto-spawned.
Fetch { hash, out, range? }.out, done. Miss → single-flight: the first callerdrives discovery →
open_or_reusechannel → multiplexedstream_fetchoverthe owned channel, signing cumulative vouchers from the single watermark;
concurrent callers for the same hash await that pull.
out. Watermarkadvances and persists (single owner → no cross-process lock contention).
Security / trust
A UDS with 0600 perms gives per-user access control for free — only the owning
user can reach the socket and trigger spends, strictly better than a loopback-TCP
"any local process" model. Windows named pipes get an equivalent restricted DACL.
The daemon still holds the unlocked wallet after a spawn-time keystore password.
Secrets never traverse the control channel. It carries
Fetch/status messagesonly. A secret crosses exactly one boundary — parent→child at spawn:
PasswordSource::Env/Filesources (DECDN_KEYSTORE_PASSWORD[_FILE]), exactlyas the node does at startup today. Nothing is handed over. (File preferred over
env: env is readable via
/proc/<pid>/environand inherited by children.)prompt, so the CLI prompts once (it has the TTY) and pipes the password to the
child's stdin at fork/exec. Requires a new
PasswordSource::Stdinvariant.[your call] — ssh-agent model: the CLI may instead decrypt the keystore itself
and hand the daemon the unlocked signer over the spawn pipe, so the passphrase
never reaches the daemon at all. Cleaner trust boundary, slightly more plumbing.
Partial / streaming (reserved, not built)
range: Option<(offset, len)>onFetchreserves the partial case (bao-verifiedrange export — "first N layers of a model"). Bulk bytes never traverse the control
socket as RPC payloads; they are exported to files. Future live-streaming is an
additive data channel (caller fd / named pipe, or iroh-blobs streaming export),
built only when a real consumer exists — and it slots in as another transport
adapter, not a redesign.
How the in-process fix above folds in
The "single serialized watermark per channel" fix is no longer a standalone
client change — it is the daemon's voucher path, and the daemon is the one
process that touches channels. The cross-process cases (two raw
decdn fetchprocesses sharing a channel) are obviated rather than solved. redb stays as the
buyer store: with a single writer the earlier multi-process-lock concern
(SQLite / nonce-agent) is moot.
Scope / phasing
DownloadServiceport +generic serve loop + UDS/named-pipe + in-process adapters) +
Fetchmessage +auto-spawn/5s-grace-exit + single-owner channel watermark (subsumes the
in-process fix) + single-flight cache +
PasswordSource::Stdin. Full-blob only.range/partial export; eviction tuning; streaming data plane.Open decisions [your call]
interprocesscrate vs. in-treecfg-split for the UDS/named-pipe glue.alpergundogdu commentedon Jun 18, 2026
Phase 1 — PR breakdown
Six PRs, each independently reviewable and green on its own. The chain is mostly
linear; PR0 is independent and can land anytime. Phase 2 (range/partial,
streaming data plane, eviction tuning) stays out of all of these.
PR0 —
PasswordSource::Stdin(independent, tiny)Stdinvariant toPasswordSourceincrates/incentive/src/eth_identity.rsthat reads one line from stdin (zeroized), for the prompt-only spawn hand-off. Leaf change, no daemon involved.read_password.PR1 — Transport seam (no daemon, no network)
DaemonRequest/DaemonResponseserde enums +DownloadServiceport trait + genericserve_conn<S: AsyncRead+AsyncWrite+Unpin>(built onprotocol::framing) + aDaemonClient. In-process/in-memorytokio::io::duplexadapter. All incommon.duplex(request → handle → response), framing edge cases, oversized-frame rejection.PR2 — Local socket transports
UnixSocketListener(0600 socket in the data-dir) +UnixStreamclient connect;NamedPipeListener+ client behindcfg(windows)(restricted DACL). The ~dozen-line cfg split selecting the default local listener.PR3 — Pull-only daemon wiring (skeleton, no fetch yet)
--pull-onlyflag/subcommand ondecdn-node.DownloadServiceimpl answersStatus/Health, returnsUnimplementedforFetch.Statusround-trips; clean shutdown.PR4 — Cache-engine fetch path (cache hit + single pull)
DownloadService::handle(Fetch)— cache hit → export blob to the caller's output path; miss → discovery →open_or_reusechannel → onestream_fetch_tracked→ persist watermark → export. Moves today'sdecdn fetchpull logic behind the daemon service. No coalescing/multiplexing yet.PR5 — Single-flight coalescing + single-owner channel watermark (subsumes the in-process fix)
Fetchfor the same content share one pull and one payment; one shared serialized watermark per channel feeding cumulative voucher signing across concurrent pulls to the same node.client_concurrent_same_channel_accepts_one_voucherfrom "exactly one succeeds" to "all succeed".PR6 — CLI client-side hand-off + lifecycle
decdn fetchconnects to the data-dir socket; if a node (registered or pull-only) is listening, use it; else auto-spawndecdn-node --pull-only(startup lock to dedupe concurrent spawns, wait-for-ready), then sendFetch. Daemon idle self-exit (5s grace after last client + no in-flight pull). Spawn-time password hand-off: env/file self-resolve, else pipe to the child's stdin (uses PR0'sStdinvariant).decdn fetchtransparently uses or spawns the daemon; bursts of pulls share one channel + cache.decdn fetchinvocations collapse to one daemon; idle daemon exits after grace.Review order
PR0 ∥ (PR1 → PR2 → PR3 → PR4 → PR5 → PR6). Each ~one focused diff; PR4 and PR5 are the substantive ones.
alpergundogdu commentedon Jun 18, 2026
Decision: single-client engine, no cross-process daemon
After working the daemon design through, we're dropping it. Reasoning:
instances races both the on-chain tx nonce (open/deposit/settle) and the
voucher nonce, and invites double-spend — it was never a valid state to support.
Coordinating it cross-process solved a problem that shouldn't exist.
(browser/web, mobile sandboxes). A single-process engine + UI (qBittorrent /
uTorrent style) ports everywhere: you queue downloads into the one instance and
watch progress there.
per-context wallet (account abstraction), fund it, pull, drain it. Independent
keys → independent channels → independent nonce spaces → zero coordination.
So the surviving deliverable is the original bug only: in-process voucher-nonce
coordination for parallel pulls (e.g. pulling a bundle's blobs concurrently over
one reused channel), all within a single instance where voucher management is
straightforward.
The daemon design proposal above is retracted; the transport-seam / lifecycle /
password-hand-off work is moot. A focused plan for the in-process fix follows.
fix(incentive): graceful failure on concurrent buyer-store open (#942) (
feat(client-pull): in-process voucher ledger for parallel pulls (#944) (