Skip to content

fix(node): wrap gossip ALPN with dispatch limiter (#433) - #512

Merged
thiras merged 6 commits into
mainfrom
fix-433-gossip-dispatch-limiter
May 11, 2026
Merged

thiras merged 6 commits into
mainfrom
fix-433-gossip-dispatch-limiter

Conversation

@thiras

@thiras thiras commented May 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Wrap the iroh-gossip ALPN with a new LimitedHandler<H: ProtocolHandler> adapter so the global concurrency cap (dispatch: no per-IP or per-Nodeld connection rate limit, enabling cheap connection exhaustion #235) extends to gossip — closes runtime: there is no graceful backpressure or rejection when the iroh QUIC accept loop is saturated, meaning a burst of inbound connections can exhaust Tokio worker threads before the per-IP rate limit (issue #235) is enforced #433.
  • For inline-protocol handlers (probe-shape), dropping the permit at inner.accept-return is sufficient because the protocol runs entirely inside accept. For return-fast handlers (gossip-shape: iroh-gossip 0.98's Gossip::accept hands the connection to a 16-deep mpsc and returns in microseconds), the wrapper now spawns a detached watcher that holds the permit until Connection::closed() fires, so the global semaphore actually bounds in-flight gossip connection tasks rather than just back-pressuring once the actor's mpsc saturates.
  • Watcher is detached intentionally: Router::shutdown calls endpoint.close(), which fires every pending Connection::closed(), so watchers terminate without external coordination and LimitedHandler does not need a JoinSet field. Permit::drop is unconditional, so the in-flight gauge stays balanced whether the watcher exits normally, is aborted, or panics.
  • Forward on_accepting and shutdown to the inner handler. iroh-gossip's Gossip::shutdown sends Disconnect messages and stops the actor; a wrapper that did not forward would silently break graceful drain.
  • Probe handler unchanged — keeps inline limiter.acquire for its custom per-rejection-layer close-frame timeout policy that the generic adapter intentionally omits.

The original framing of this PR (commit 9275194) implied the global cap held network-wide for gossip after the wrapper landed. Review #4262648505 flagged that this was overstated because the original wrapper dropped the permit at inner.accept-return. Commit 604b530 introduces the watcher and rewrites the module docs to describe what is actually enforced for each handler shape.

Test plan

  • cargo nextest run -p decdn-node — 88/88 pass, including 4 limited_handler tests:
    • rejects_second_connection_past_global_cap (ParkingHandler — blocks inside accept)
    • rejects_second_connection_for_return_fast_inner (new — mimics gossip's return-fast + spawn-internally shape; verified to fail without the watcher)
    • per_source_rejection_routes_through_wrapper
    • permit_releases_when_inner_returns_err
  • cargo clippy --workspace --all-targets -- -D warnings — clean.
  • cargo fmt -- --check — clean.
  • cargo doc -p decdn-node --no-deps — clean (intra-doc links resolve).

Closes #433.

🤖 Generated with Claude Code

iroh-gossip's ProtocolHandler attached directly to the Router bypassed
ConnectionLimiter (#235) entirely, so a connection flood on the gossip
ALPN was bounded only by iroh-gossip's internal limits — the global
semaphore did not hold network-wide. Wrap it in a generic
LimitedHandler<H> adapter so every ALPN attached to the Router goes
through the same admission control. Probe stays on its inline
limiter.acquire (defense in depth + custom per-layer close-frame
timeout policy the generic adapter intentionally omits).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 10, 2026 10:49

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request introduces LimitedHandler, a wrapper for ProtocolHandler that applies connection limiting to foreign handlers like iroh-gossip, ensuring consistent network-wide resource management. The implementation includes the wrapper, its integration into the node runtime, and new integration tests. A review comment suggests optimizing the tests by moving expensive setup operations outside of loops and avoiding unnecessary waits for connection closure to prevent task accumulation and improve performance.

Comment thread crates/node/tests/limited_handler.rs Resolved
@github-actions

github-actions Bot commented May 10, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 88.27% (was 88.28%, ▼ 0.02%) — 12333/13972 lines

File Coverage Lines Δ
crates/node/src/handlers/limited.rs 84.85% 56/66 new
crates/node/src/runtime/mod.rs 53.74% 388/722 ▼ 0.07%
History
Commit Total Δ vs base
9275194 87.88% ▼ 0.02%
892f2d9 87.88% ▼ 0.02%
029a277 87.87% ▼ 0.03%
604b530 88.27% ▼ 0.02%
f498489 (HEAD) 88.27% ▼ 0.02%

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 ensures the node’s global connection concurrency cap (ConnectionLimiter’s semaphore from #235) applies to all ALPN handlers attached to the iroh Router, by wrapping the iroh-gossip handler with a new LimitedHandler adapter (addressing #433).

Changes:

  • Added handlers::limited::LimitedHandler to gate a foreign ProtocolHandler::accept behind ConnectionLimiter::acquire, while forwarding on_accepting and shutdown.
  • Updated the runtime router wiring to wrap iroh-gossip’s handler with LimitedHandler.
  • Added unit + integration tests covering global-cap rejection, per-source rejection, permit release on inner error, and shutdown forwarding.

Reviewed changes

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

File Description
crates/node/src/runtime/mod.rs Wrapes the gossip ALPN handler with LimitedHandler so gossip is subject to the global limiter.
crates/node/src/handlers/mod.rs Exposes the new limited handler module.
crates/node/src/handlers/limited.rs Implements the LimitedHandler ProtocolHandler adapter and a unit test for shutdown forwarding.
crates/node/tests/limited_handler.rs Adds two-endpoint integration tests validating limiter behavior through the wrapper.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread crates/node/src/handlers/limited.rs Resolved
Comment thread crates/node/tests/limited_handler.rs Resolved
thiras and others added 2 commits May 10, 2026 13:56
- Reword "layer-label byte" → "layer-label reason bytes" in the
  rejection-path comment: `RejectReason::as_str()` returns multi-byte
  ASCII strings ("global-full"/"per-source"), not a single byte.
  (Copilot review.)
- Hoist the `client_ep` out of the per-iteration loop in
  `permit_releases_when_inner_returns_err`; endpoint construction is
  the expensive part. Trims the test from ~0.82s to ~0.26s.
  (gemini-code-assist review, partial — kept the conn.closed() wait
  because it serializes against the server-side permit drop; without
  it iteration N+1 can race iteration N's permit release. The cited
  "no conn.closed() wait" guideline applies to flood scenarios on
  the limiter's memory-pressure path, not this 3-iteration test.)
- Propagate the previously-discarded `tokio::time::timeout` error
  inside the loop: a regression that left the connection open would
  silently pass before. (Copilot review.)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Previous wording ("the connection itself is cheap") overstated the
asymmetry — `connect` does a full QUIC+TLS handshake which is not cheap
in absolute terms. Replace with the measured speedup that motivates the
hoist, so the comment survives a future where `connect` regresses.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@thiras
thiras requested a review from alpergundogdu May 10, 2026 16:32

@alpergundogdu alpergundogdu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed locally against iroh 0.98.2 / iroh-gossip 0.98.0 (per Cargo.lock).

Significant — global-cap semantics on gossip are weaker than the PR framing

The PR description and the LimitedHandler doc-comments frame this as: gossip floods now go through ConnectionLimiter, so the global concurrency cap (#235) "holds network-wide." That holds for the per-source rate-limit layer but only weakly for the global semaphore, because of how iroh-gossip's Gossip::accept is shaped.

In iroh-gossip 0.98 (src/net.rs:130 and src/net.rs:247):

impl ProtocolHandler for Gossip {
    async fn accept(&self, connection: Connection) -> Result<(), AcceptError> {
        self.handle_connection(connection).await ...  // enqueues into a 16-deep mpsc, returns
    }
}

The actor consumes the message and spawns a per-connection task that owns the Connection for its full lifetime (src/net.rs:526-562).

In LimitedHandler::accept:

let _permit = match self.limiter.acquire(&conn) { ... };
self.inner.accept(conn).await
// _permit drops here

_permit is held only until inner.accept returns — i.e. until the mpsc enqueue completes. For probe (where accept runs the protocol inline) permit lifetime ≈ connection lifetime. For gossip, permit lifetime ≈ mpsc-enqueue time (microseconds). So under sustained flood the global semaphore briefly back-pressures once the gossip actor's 16-slot channel saturates, but it doesn't bound the number of in-flight gossip handler tasks the way it does for probe.

The integration tests use a ParkingHandler that artificially blocks inside accept — that validates the wrapper's bookkeeping correctly, but doesn't reflect Gossip::accept's actual return-fast shape. rejects_second_connection_past_global_cap would pass identically against probe; it does not prove the global cap is enforced on a real gossip flood.

This is strictly better than today (per-source layer is properly gated, some back-pressure once gossip's mpsc fills), but worth deciding whether to (a) accept the limitation and tighten the doc-comments / PR-description to describe what's actually enforced for gossip, (b) extend the wrapper to keep the permit live until conn.closed() (would need a spawned watcher task, with its own costs and an interaction with Router::shutdown's drain semantics), or (c) defer.

Minor

  • Copilot's "byte vs bytes" flag on limited.rs appears stale — the wrapper's rejection-block comment already says "layer-label reason bytes" (plural), which is correct for reason.as_str().as_bytes(). The singular "reason byte" wording does live in crates/node/src/handlers/probe.rs:26 ("0x10 RATE_LIMITED reason byte (and its layer label)"), where it's defensible as referring to the QUIC application-error-code byte plus a separate label payload. Either tighten that for consistency or leave it.

  • Gemini's "hoist setup out of the loop" flag on permit_releases_when_inner_returns_err is partly stale — client_ep is already hoisted outside the loop; only client_ep.connect(...) runs per iteration, which is the test's actual subject. Gemini's secondary concern about conn.closed() waits is addressed directly in the test's own inline comment: this is a 3-iteration sequencing test, not a flood, so the limiter's memory-pressure-path guideline doesn't apply.

  • Coverage is 49/59 lines on handlers/limited.rs (83%); the uncovered chunk is presumably parts of the Err(reason) rejection path. The in-crate unit test only exercises shutdown forwarding, and the integration tests live under tests/ where coverage attribution to the crate file may differ. Not worth blocking.

Verified correct

  • Trait defaults for on_accepting (await Accepting) and shutdown (no-op) match what the wrapper explicitly forwards (iroh-0.98.2/src/protocol.rs:249-287).
  • Gossip::shutdown does send Disconnect and stop the actor (iroh-gossip-0.98.0/src/net.rs:255-267) — the forwarding rationale on shutdown is accurate.
  • Permit RAII drop and metrics-gauge balance preserved; _permit drops at end of function body in the expected order relative to inner.accept.
  • GlobalFull no-conn.closed()-wait rationale matches probe's existing reasoning (crates/node/src/handlers/probe.rs:96-106) — consistent across the two handlers.
  • #[must_use] on LimitedHandler::new, finish_non_exhaustive() in Debug, anti-panic policy honored.

thiras and others added 3 commits May 11, 2026 13:55
Review #4262648505 on PR #512 flagged that the wrapper's global-cap
semantics were weaker than advertised for iroh-gossip. `Gossip::accept`
returns after a 16-deep mpsc enqueue (iroh-gossip-0.98.0/src/net.rs:131-
136, 247-253) and the actor then spawns the long-lived per-connection
task (net.rs:526-562). The original wrapper dropped the permit when
`inner.accept` returned, so for gossip the permit covered enqueue time
(microseconds) rather than connection lifetime — the global semaphore
briefly back-pressured once the actor's mpsc filled but never bounded
in-flight gossip handler tasks.

Spawn a detached watcher on the Ok path that owns the Permit and awaits
`Connection::closed()`. The permit now stays held until the QUIC
connection actually terminates, regardless of whether the inner handler
runs inline (probe-shape) or returns fast and spawns internally
(gossip-shape). The spawn is detached because Router::shutdown calls
endpoint.close(), which fires every pending Connection::closed() future
network-wide; watchers terminate without external coordination, so
LimitedHandler does not need a JoinSet field (which would force
interior mutability for no real benefit).

Permit safety: Permit (crates/node/src/dispatch.rs:111-127) is Send
(OwnedSemaphorePermit + Arc<Metrics>); its Drop unconditionally
decrements the in-flight gauge, preserving balance whether the watcher
exits normally, is aborted, or panics. Connection::clone is a refcount
bump that does not extend the connection's lifetime past what the inner
handler keeps alive.

New test rejects_second_connection_for_return_fast_inner mimics
gossip's return-fast + spawn-internally shape and proves a second
connection is RATE_LIMITED while the first task holds its clone.
Verified to fail without the watcher. Existing tests unchanged.

Module docs rewritten to describe the inline vs. return-fast handler
shapes and exactly what the global semaphore now enforces for each.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Apply review feedback from the in-conversation multi-agent review on
the watcher fix (commit 604b530). Changes are doc/test-tightening
plus two new test assertions that catch regression classes the
original new test missed:

Test coverage:
- rejects_second_connection_for_return_fast_inner now opens a third
  connection after conn1 closes and asserts inner.accepts == 2. The
  original test only proved client 2 was rejected while the watcher
  held the permit; a future `mem::forget(permit)` or detached-leak
  regression would have slipped through. Verified to fail when the
  watcher's permit is leaked.
- New router_shutdown_releases_parked_watcher_permit: forces shutdown
  while a watcher is still parked on `closed()` and polls
  ConnectionLimiter::acquire_for_test until the permit becomes
  available. Catches the upstream-iroh-regression class where
  endpoint.close() stops firing pending Connection::closed() futures.
  Also verified to fail under a forced leak.

Comment policy (CLAUDE.md): drop issue/PR refs from long-lived code.
- Module-doc H2 heading: remove "(issue #433)".
- ReturnFastHandler docstring: remove the "review #4262648505 on PR
  #512" sentence; the test name and the `accepts == 1` assertion
  message at the failure site capture the WHY durably.
- Trim the in-test "permit held continuously" parenthetical aside to
  the one load-bearing sentence ("`spawned` fires after the wrapper
  has reached `tokio::spawn`, so the watcher owns the permit").

Comment policy (CLAUDE.md): WHY-not-WHAT.
- Drop the accept-body two-shapes recap; the module doc already
  carries the taxonomy.
- Thin the "no panicking paths" elaboration to one sentence noting
  `Permit::drop` is unconditional.
- Tighten "(which would force interior mutability for no real
  benefit)" to "watchers self-terminate".
- Remove the "Construction is cheap" body of LimitedHandler::new
  (the `#[must_use]` text already carries the load).

Skipped (YAGNI per CLAUDE.md):
- Adding `tracing::trace!` for the discarded ConnectionError. The
  wrapper's job is gauge balance, not close-reason observability;
  the inner handler owns that signal.
- Wrapping the watcher body in `tracing::Instrument` as a guardrail
  for a hypothetical future panic-able call. The current body
  provably cannot panic.
- Adding a `// moved into watcher below` comment to the `permit`
  binding. The move is visible on the next code block — explanatory
  comments for self-evident control flow rot first.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@thiras
thiras merged commit 0dbe896 into main May 11, 2026
10 checks passed
@thiras
thiras deleted the fix-433-gossip-dispatch-limiter branch May 11, 2026 11:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants