Repository navigation
perf(node): remove head-of-line blocking and admission stalls on cdn/client/v1 - #1867
Conversation
…client/v1 Group A of the serve-path hot-path audit (#1788). All four items sit on the connection accept / stream admission path shared by every stream on a cdn/client/v1 connection. 1. Serve each inbound bidi stream on its own tokio task via a JoinSet instead of a FuturesUnordered on the single accept task. Every synchronous per-stream CPU cost — the open-time ecrecovers and the response ECDSA signature, the per-voucher ecrecover, the up-to-255-keccak preimage walk, the per-frame copies — now runs off the accept loop and off sibling streams. The handler is shared as Arc<Self>; the iroh ProtocolHandler &self borrow is bridged by a new ClientProtocol wrapper that owns the Arc and hands serve a 'static clone. A panicking stream task is isolated by the JoinSet and filed as a node fault rather than taking the connection down. 2. Keep the per-source keyspace prune off the accept path. An accept does only the constant-time governor bucket check and an O(1) len() comparison; when the keyspace grows past cap + cap/10 it offloads one single-flighted retain_recent sweep to a spawn_blocking task, so connection admission stays constant-time regardless of keyspace size. 3. Replace the connection-cached verified client binding's tokio Mutex with an ArcSwapOption, removing two await points per StreamRequest — a write-once-then -read cell the now-concurrent stream tasks read and publish lock-free. 4. Publish ConnectionLimiter.per_source through an ArcSwap instead of an RwLock, making per-source admission reads fully lock-free and consistent with the rest of the reload surface; the lock-poison recovery machinery goes with it. Closes #1788. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_019KVcsxWS7Z1TsekbLnJYPv
d71e287 to
0df5c7b
Compare
There was a problem hiding this comment.
Pull request overview
This PR improves decdn-node’s cdn/client/v1 serve-path accept/admission hot path by removing head-of-line blocking and making admission checks lock-free / constant-time under load.
Changes:
- Spawns each inbound client stream onto its own task (via
JoinSet) to prevent per-stream CPU work from stalling the connection accept loop. - Moves per-source limiter keyspace pruning off the accept path and switches reload-fed limiter state to
ArcSwapfor lock-free reads. - Introduces a router-facing
ClientProtocolwrapper to bridge iroh’sProtocolHandler::accept(&self, …)borrow to anArc<ClientHandler>.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/node/src/handlers/client/dispatch.rs | Serve loop now spawns per-stream tasks; replaces async mutex binding cache with lock-free cell and adds join-result handling. |
| crates/node/src/dispatch.rs | Makes per-source limiter lock-free via ArcSwap and offloads retain_recent pruning via spawn_blocking. |
| crates/node/src/handlers/client/mod.rs | Adds ClientProtocol wrapper implementing ProtocolHandler for cdn/client/v1. |
| crates/node/src/runtime/mod.rs | Registers ClientProtocol with the iroh router instead of the handler directly. |
| crates/node/tests/support/mod.rs | Updates test server harness to accept connections via ClientProtocol. |
| crates/node/tests/origin_range_pull.rs | Updates concurrent server helper to use ClientProtocol. |
| crates/node/tests/node_origin_pull.rs | Updates multiple test server helpers to use ClientProtocol. |
Suppressed comments (1)
crates/node/src/handlers/client/dispatch.rs:215
- The connection-scoped client binding is described as "write-once-then-read", but this code will accept a later valid binding that changes the recovered address, and concurrent streams can race to publish different bindings. That can lead to inconsistent lane keys / authorization decisions across streams on the same connection. Reject attempts to change an already-established binding (and avoid overwriting an existing value).
let mut verified_client: Option<Address> = bound_addr.load().as_deref().copied();
if let Some(binding) = &ext.binding {
let addr_bytes = binding.ethereum_address;
match verify_binding(
client_node_id,
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| Arc::clone(&self.0) | ||
| .serve(connection) | ||
| .await | ||
| .map_err(|e| AcceptError::from_err(std::io::Error::other(e.to_string()))) | ||
| } |
There was a problem hiding this comment.
Keeping the .to_string() conversion here for consistency with the sibling ALPN handlers: ProbeHandler::accept and DhtHandler::accept both build the AcceptError identically (AcceptError::from_err(std::io::Error::other(e.to_string()))), and the three are deliberately mirrored. The AcceptError is terminal at the iroh router boundary — the connection is already tearing down — and the node-attributable serve faults are logged with their full chain inside serve/log_stream_end before control ever reaches here, so no diagnostic chain is lost in practice. Preserving the source chain across all three handlers is a reasonable follow-up, but it's out of scope for this perf PR (which doesn't touch the probe/dht handlers).
Generated by Claude Code
…cache doc - note_joined_stream: a JoinError can be a panic OR a cancellation. Only a panic is a node-side fault (metered + error!); a cancellation is a benign teardown artifact (debug!, uncounted), so the hard-coded "panic" wording is replaced with an is_panic() split. - Correct the connection binding cache comment: the cell is last-writer-wins (as under the prior mutex), not write-once. It is only a fallback — every spend-authorizing decision uses the binding on its own stream when present — so a client racing two identities only muddies the fallback for its own unbound streams. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_019KVcsxWS7Z1TsekbLnJYPv
|
CI note — the Evidence it isn't this PR's: the failure is a stall, not the frontier-overshoot the test guards — I A/B'd it locally against the pre-change serve model:
The two remaining changes are provably inert on this path: each pull carries its own client binding, so the new lock-free binding cell is never read for these streams, and the dispatch limiter isn't on the delivery path. So the flake reproduces on the model equivalent to Fixing the underlying client-pull race (or the test's stall-deadline sizing) is out of scope for a perf PR on the accept path, and there's no existing fix to port. Flagging it as a repo-level flaky test worth hardening separately. I'll keep the PR watched until it's green. Generated by Claude Code |
Coverage reportTotal: 82.07% (was 82.04%, ▲ +0.03%) — 68037/82905 lines
History
|
Closes #1788 (Group A of the serve-path hot-path audit). All four items sit on the connection accept / stream admission path shared by every stream on a
cdn/client/v1connection, fixed together here.1. Streams spawn instead of running on the single accept task
crates/node/src/handlers/client/dispatch.rsEach inbound bidi stream now runs on its own
tokio::spawned task via a [JoinSet], rather than as a cooperative future in aFuturesUnorderedon the one accept task. Every synchronous per-stream CPU cost — the two open-time ecrecovers and the response ECDSA signature, the per-voucher ecrecover, the up-to-255-keccak preimage walk, the per-frame copies — now runs off the accept loop and off its sibling streams. A voucher-heavy stream no longer stalls the others or delays acceptance of new streams, and per-connection throughput is not bounded by one core's worth of serialized CPU.Arc<Self>so each task holds the'statichandle a spawn needs. The irohProtocolHandler::accept&selfborrow is bridged by a newClientProtocol(Arc<ClientHandler>)wrapper that owns theArcand handsservea clone;serve/serve_streamnow takeself: Arc<Self>.JoinSet(it can't take the connection down) and filed as a node-side fault (decdn_serve_stream_node_fault_total+error!).JoinSet::is_empty()/ the owned permit moved into each task.2. Per-source keyspace prune moved off the accept path
crates/node/src/dispatch.rsAn accept now does only the constant-time governor bucket check plus an
O(1)len()comparison. When the keyspace grows pastcap + cap/10it offloads one single-flightedretain_recentsweep (theO(n)walk) to aspawn_blockingtask, so connection admission stays constant-time regardless of keyspace size. The single-flight flag is now anArc<AtomicBool>so the background sweep owns a'statichandle to reset it; a sync fallback runs the sweep inline when no runtime is present (unit tests). The periodicgc_per_source(#440) is unchanged.3. Verified client binding is lock-free
crates/node/src/handlers/client/dispatch.rsThe connection-cached verified client address moves from a
tokio::Mutex<Option<Address>>to anArcSwapOption<Address>— a write-once-then-read cell — removing twoawaitpoints perStreamRequest. This matters more now that stream tasks run truly concurrently (item 1).4.
ConnectionLimiter.per_sourceis now lock-freecrates/node/src/dispatch.rsper_sourcemoves fromRwLock<PerSource>toArcSwap<PerSource>, making per-source admission reads fully lock-free and consistent with the rest of the reload surface (the semaphore is alreadyArcSwapOption). Reload swaps a freshArc<PerSource>wholesale; the lock-poison recovery machinery (and its test) is removed with the lock.Testing
cargo fmt --check,cargo clippy --workspace --all-targets -- -D warningsclean.cargo test -p decdn-node --lib— 768 pass (includes 22 dispatch limiter tests, 65 client-handler tests).client_loopback(111),origin_range_pull(10),node_origin_pull(65),node_to_node_pull_through(4) — all pass.over_cap_accept_prunes_refilled_keyspacecovering the item-2 offloaded sweep via its inline fallback.🤖 Generated with Claude Code
https://claude.ai/code/session_019KVcsxWS7Z1TsekbLnJYPv
Generated by Claude Code