Skip to content

perf(node): remove head-of-line blocking and admission stalls on cdn/client/v1 - #1867

Merged
alpergundogdu merged 2 commits into
mainfrom
claude/issue-1788-investigation-0u8hn8
Aug 29, 2026
Merged

alpergundogdu merged 2 commits into
mainfrom
claude/issue-1788-investigation-0u8hn8

Conversation

@alpergundogdu

Copy link
Copy Markdown
Contributor

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/v1 connection, fixed together here.

1. Streams spawn instead of running on the single accept task

crates/node/src/handlers/client/dispatch.rs

Each inbound bidi stream now runs on its own tokio::spawned task via a [JoinSet], rather than as a cooperative future in a FuturesUnordered on 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.

  • The handler is shared as Arc<Self> so each task holds the 'static handle a spawn needs. The iroh ProtocolHandler::accept &self borrow is bridged by a new ClientProtocol(Arc<ClientHandler>) wrapper that owns the Arc and hands serve a clone; serve/serve_stream now take self: Arc<Self>.
  • A panicking stream task is isolated by the JoinSet (it can't take the connection down) and filed as a node-side fault (decdn_serve_stream_node_fault_total + error!).
  • The idle-close clock and per-connection stream-cap semaphore are preserved via JoinSet::is_empty() / the owned permit moved into each task.

2. Per-source keyspace prune moved off the accept path

crates/node/src/dispatch.rs

An accept now does only the constant-time governor bucket check plus an O(1) len() comparison. When the keyspace grows past cap + cap/10 it offloads one single-flighted retain_recent sweep (the O(n) walk) to a spawn_blocking task, so connection admission stays constant-time regardless of keyspace size. The single-flight flag is now an Arc<AtomicBool> so the background sweep owns a 'static handle to reset it; a sync fallback runs the sweep inline when no runtime is present (unit tests). The periodic gc_per_source (#440) is unchanged.

3. Verified client binding is lock-free

crates/node/src/handlers/client/dispatch.rs

The connection-cached verified client address moves from a tokio::Mutex<Option<Address>> to an ArcSwapOption<Address> — a write-once-then-read cell — removing two await points per StreamRequest. This matters more now that stream tasks run truly concurrently (item 1).

4. ConnectionLimiter.per_source is now lock-free

crates/node/src/dispatch.rs

per_source moves from RwLock<PerSource> to ArcSwap<PerSource>, making per-source admission reads fully lock-free and consistent with the rest of the reload surface (the semaphore is already ArcSwapOption). Reload swaps a fresh Arc<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 warnings clean.
  • cargo test -p decdn-node --lib — 768 pass (includes 22 dispatch limiter tests, 65 client-handler tests).
  • Integration suites exercising the concurrent serve path: client_loopback (111), origin_range_pull (10), node_origin_pull (65), node_to_node_pull_through (4) — all pass.
  • New deterministic unit test over_cap_accept_prunes_refilled_keyspace covering the item-2 offloaded sweep via its inline fallback.

🤖 Generated with Claude Code

https://claude.ai/code/session_019KVcsxWS7Z1TsekbLnJYPv


Generated by Claude Code

Copilot AI lite review requested due to automatic review settings August 29, 2026 11:11
…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
@alpergundogdu
alpergundogdu force-pushed the claude/issue-1788-investigation-0u8hn8 branch from d71e287 to 0df5c7b Compare August 29, 2026 11:14

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 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 ArcSwap for lock-free reads.
  • Introduces a router-facing ClientProtocol wrapper to bridge iroh’s ProtocolHandler::accept(&self, …) borrow to an Arc<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.

Comment on lines +1901 to 1905
Arc::clone(&self.0)
.serve(connection)
.await
.map_err(|e| AcceptError::from_err(std::io::Error::other(e.to_string())))
}

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.

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

Copy link
Copy Markdown
Contributor Author

CI note — the test job failed on node_origin_pull::concurrent_pulls_resume_at_their_own_frontier_not_the_channels. This is a pre-existing nondeterministic flake, not caused by this PR, and I'm re-running the job once.

Evidence it isn't this PR's: the failure is a stall, not the frontier-overshoot the test guards — pull … returned NotFound (expected AlreadyAdmitted) … topups=[] stalled=1. That's the client-pull stall-vs-top-up race in decdn_client_pull::driver (the buyer scores the upstream stalled before its reactive top-up fires), which this PR does not touch. This PR only changes the connection accept/admission path.

I A/B'd it locally against the pre-change serve model:

  • This PR's head (streams spawned per task): ~1 in 8–12 runs fails with topups=[] stalled=1.
  • Item 1 reverted (streams cooperative on one accept task, i.e. main's model), items 2–4 kept: 4/15 runs fail with the identical signature.

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 main at the same rate — it predates this PR.

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

@github-actions

Copy link
Copy Markdown

Coverage report

Total: 82.07% (was 82.04%, ▲ +0.03%) — 68037/82905 lines

File Coverage Lines Δ
crates/node/src/dispatch.rs 98.00% 589/601 ▲ +3.37%
crates/node/src/handlers/client/dispatch.rs 85.77% 464/541 ▼ 0.39%
crates/node/src/handlers/client/mod.rs 92.73% 1568/1691 ▲ +0.02%
crates/node/src/runtime/mod.rs 47.80% 1154/2414 ● 0.00%
History
Commit Total Δ vs base
26e1c99 (HEAD) 82.07% ▲ +0.03%

@alpergundogdu
alpergundogdu merged commit a208eca into main Aug 29, 2026
48 of 50 checks passed
@alpergundogdu
alpergundogdu deleted the claude/issue-1788-investigation-0u8hn8 branch August 29, 2026 15:38
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.

perf(node): accept path — per-connection head-of-line blocking and admission stalls on cdn/client/v1

3 participants