Skip to content

feat(dispatch): per-IP / per-NodeID connection rate limit (#235) - #386

Merged
alpergundogdu merged 16 commits into
mainfrom
feat/issue-235-connection-rate-limit
May 4, 2026
Merged

alpergundogdu merged 16 commits into
mainfrom
feat/issue-235-connection-rate-limit

Conversation

@thiras

@thiras thiras commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes the connection-flood exhaustion vulnerability in #235 with a layered limiter applied at the top of every ProtocolHandler::accept. The [security] config section is hot-reloadable on SIGHUP and admin_v1_reload. Reshaped following review feedback to keep cost-per-future-knob bounded — the four review asks landed as three commits on top of the original implementation.

What ships

  • Two-layer enforcement (down from three) at every accept:
  • governor::DefaultKeyedRateLimiter is the keyed-limiter implementation. The hand-rolled TokenBucket + BoundedRateMap<K> were replaced — keyed rate limiting is no longer something we own and audit ourselves.
  • APP_ERR_RATE_LIMITED = 0x10 QUIC close code added to decdn-protocol. Rejected connections close with this code; ADR 013 § Application Error Codes updated.
  • Three Prometheus metrics (ADR 020 naming):
    • decdn_dispatch_rejected_global_total (counter)
    • decdn_dispatch_rejected_per_source_total (counter)
    • decdn_dispatch_in_flight (gauge)
    • Plus decdn_dispatch_per_source_skipped_no_addr_total for relay-only connections that escape per-IP bookkeeping by design.
  • Hot-reload of every [security] field via SIGHUP and admin_v1_reload. 0 in any field disables that layer (acquire path short-circuits). All-or-nothing reload: an invalid [security] value rejects the entire reload (payment, log_level, pinned_hashes all retained), matching the existing "previous values retained on error" contract.
  • Arc<Semaphore> swap-not-resize on reload. A reload to a smaller cap doesn't retroactively bound already-held permits — they finish out against the old semaphore — but new acquires hit the new cap immediately. Operator-visible difference is sub-second on a small mesh; the reasoning is materially simpler than the old grow/shrink-with-drift-accounting pattern.
  • ReloadableSection trait + per-section impls for payment, log_level, pinned_hashes, and security. Reload is a fixed three-phase iteration (resolve all → fallible_commits in order → infallible_swaps), so the next operator-tunable knob is a small impl on a small struct rather than another inline limb in RuntimeReloadState::reload.

Reshaping commits (in response to PR review)

Commit Ask addressed
4f87586 (#1 + #2) Collapse per-IP/per-NodeID into a single per-source layer; replace hand-rolled token bucket + bounded map with governor. NodeIDs are free to mint, so the per-NodeID layer was bypassable; "per-source" naming leaves room to add it back additively if useful.
46235af (#4) Swap-not-resize the global Arc<Semaphore> on reload. Drops add_permits / acquire_many_owned(...).forget() dance, target_max_concurrent vs live_semaphore_size split, parked-shrink task, racing-N→N+1→N drift analysis.
153c335 (#3) Factor ReloadableSection trait; migrate payment / log_level / pinned_hashes / security to impls.

Test plan

  • cargo nextest run -p decdn-node --lib --jobs 1 — 213 / 213 passing
  • cargo nextest run -p decdn-node --test admin_peers --jobs 1 — 18 / 18
  • cargo nextest run -p decdn-node --test config_validate --jobs 1 — 14 / 14
  • cargo nextest run -p decdn-node --test probe_loopback --jobs 1 — 7 / 7
  • cargo nextest run -p decdn-node --test sighup_signal --jobs 1 — 2 / 2 (real OS signal)
  • cargo clippy -p decdn-node --all-targets --jobs 1 -- -D warnings — clean
  • cargo doc --workspace --no-deps --jobs 1 — clean
  • cargo fmt -- --check — clean

Manual verification (left to reviewer): flood test (open >256 concurrent probe connections, observe decdn_dispatch_rejected_global_total increments and decdn_dispatch_in_flight stays bounded); hot-reload smoke (edit [security] fields, SIGHUP, observe "config reload applied" log line and confirm live limiter reflects the change).

Note on operator-side tracing layout

The 153c335 trait factoring split the prior single "config reload applied" aggregated info line into one per-section "config reload section applied" event keyed on section = name(), plus a final aggregated marker. If any operator log pipeline grepped for the old structured fields (rate_per_mb, pinned_added, etc.) on the aggregated line, they're now on the per-section lines. No tests assert on log content, but flagged for the changelog.

🤖 Generated with Claude Code

Adds a `ConnectionLimiter` shared across all deCDN QUIC protocol handlers
to prevent connection-flood exhaustion. Three enforcement layers are applied
at the top of every `ProtocolHandler::accept` call:

1. Global semaphore — hard cap on total in-flight handler tasks (default 256).
2. Per-NodeID lazy-refill token bucket (default 20 tok/s, burst 20).
3. Per-IP lazy-refill token bucket (default 100 tok/s, burst 200).

Connections that fail any check are closed immediately with the new
`APP_ERR_RATE_LIMITED = 0x10` QUIC application error code (peers SHOULD
back off; they MUST NOT treat it as a protocol error). Using `Ok(())` on
rejection avoids polluting iroh's task logs with spurious failures.

New `[security]` TOML section with safe defaults so a stock node is
protected out of the box. Hot-reload is intentionally excluded — semaphore
rebuild or token-bucket reset mid-run would transiently allow/deny traffic
in unpredictable ways.

New Prometheus metrics: `decdn_dispatch_rejected_{global,per_node,per_ip}_total`
counters and `decdn_dispatch_in_flight` gauge, all following ADR 020 naming.

ADR 013 §Application Error Codes updated with the new `0x10 RATE_LIMITED`
row and its semantic contract.

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

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

Introduces a shared connection-accept rate limiter for deCDN QUIC handlers to mitigate connection-flood task exhaustion (#235), with new config/metrics surfaces and protocol/ADR documentation for a dedicated QUIC close code.

Changes:

  • Add dispatch::ConnectionLimiter (global concurrency semaphore + per-NodeID and per-IP token buckets) and wire it into the probe protocol handler.
  • Add [security] configuration section (SecurityConfig/ResolvedSecurity) with defaults and validation, and plumb it through runtime/test scaffolding.
  • Add Prometheus metrics for limiter rejections/in-flight permits and define/document APP_ERR_RATE_LIMITED = 0x10 (protocol constant + ADR update).

Reviewed changes

Copilot reviewed 14 out of 14 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
crates/protocol/src/lib.rs Adds APP_ERR_RATE_LIMITED QUIC application close code constant.
crates/node/src/dispatch.rs New shared connection limiter implementation + unit tests.
crates/node/src/handlers/probe.rs Acquires limiter permit at connection start; closes with APP_ERR_RATE_LIMITED on reject.
crates/node/src/runtime/mod.rs Constructs limiter from cfg.security and passes it to ProbeHandler.
crates/node/src/metrics.rs Adds counters/gauge for limiter rejections and in-flight permits.
crates/node/src/config/types.rs Adds TOML-deserializable [security] config section.
crates/node/src/config/resolved.rs Adds ResolvedSecurity and includes it in ResolvedConfig.
crates/node/src/config/mod.rs Resolves/validates security config and merges into resolved config.
crates/node/src/lib.rs Exposes new dispatch module from crate root.
crates/node/src/runtime/reload.rs Updates test/resolver scaffolding to include ResolvedSecurity.
crates/node/tests/probe_loopback.rs Uses a permissive limiter in loopback probe integration tests.
crates/node/tests/config_validate.rs Updates resolved-config test scaffolding with security defaults.
crates/node/tests/sighup_signal.rs Updates resolved-config test scaffolding with security defaults.
adr/013-schema-evolution.md Documents new 0x10 RATE_LIMITED error code contract.
Comments suppressed due to low confidence (1)

crates/node/src/runtime/mod.rs:118

  • The global/per-source limiter is only applied to ProbeHandler; GOSSIP_ALPN connections are accepted directly via gossip.clone() and therefore bypass the global semaphore + per-source throttles. If an attacker can open many iroh_gossip connections, the original task-exhaustion vector still exists on that ALPN. Consider wrapping all accepted protocol handlers (including gossip) behind a small adapter that acquires a ConnectionLimiter permit before delegating, or moving the permit acquisition to a single dispatch point before ALPN routing.
    let router = Router::builder(ep.clone())
        .accept(ProbeHandler::ALPN, probe_handler)
        .accept(GOSSIP_ALPN, gossip.clone())
        .spawn();

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

Comment thread crates/node/src/runtime/reload.rs Resolved
Comment thread crates/node/src/config/mod.rs Resolved
Comment thread crates/node/src/dispatch.rs Resolved

@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 implements a multi-layered connection rate-limiting system to mitigate potential Denial of Service attacks. It introduces a ConnectionLimiter that enforces a global concurrency cap via a semaphore and per-source throttling using token buckets for both NodeIDs and IP addresses. The changes include new configuration fields, updated protocol error codes, and metrics for monitoring rejected connections. Review feedback identifies a critical compilation error in the peer IP resolution logic and a performance concern regarding the linear scan used for entry eviction within a mutex lock.

Comment thread crates/node/src/dispatch.rs Resolved
Comment thread crates/node/src/dispatch.rs Resolved
- deny.toml: ignore RUSTSEC-2026-0118/0119 (hickory-proto transitive,
  no patch available — same pattern as existing ignores)
- reload: add [security] to FileSectionSnapshot + log_ignored_other_sections
  so SIGHUP edits to security.* emit the standard "requires restart" warning
- config: add is_finite() guard on per_node_rate_per_sec and
  per_ip_rate_per_sec so inf/NaN fail fast at load time
- dispatch: replace double-lookup (contains_key + get_mut) with
  get_mut-then-entry in try_consume, eliminating one hash on the hot path

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Second round of review feedback on the connection rate limiter.

Observability: dispatch::acquire now emits tracing::debug! per rejection
with reason/node_id/ip, and the QUIC close-frame reason bytes carry a
short layer label (global-full / per-ip / per-node-id) so peers can pick
an appropriate backoff. probe.rs gained a comment explaining why the
rate-limited path returns Ok(()) — returning Err would have iroh
amplify rejection logs as AcceptError under flood.

Correctness: per-IP is now checked before per-NodeID so a per-IP
rejection never charges a per-NodeID token. DEFAULT_PER_NODE_BURST goes
from 20 to 40 (2× the rate, matching per-IP defaults) so well-behaved
peers don't trip the limit on naturally-clumped requests.
BoundedRateMap::cap is now NonZeroUsize, ruling out the cap=0 silent
overflow at the type level. peer_ip filters is_closed paths.

Validation: SIGHUP-driven reload now pre-validates a changed [security]
section and emits a tracing::warn! if the next restart would fail to
start, instead of letting the operator discover it later under
pressure.

Tests: new integration test exercises APP_ERR_RATE_LIMITED on the wire
end-to-end (the rejection path was previously dead code under tests).
New unit tests cover global semaphore exhaustion, Permit drop releasing
the slot, per-IP/per-NodeID rejection, asymmetric-token-charge
invariant, relay-skip, concurrent contention, mutex poisoning recovery,
backward clock skew, and 8 invariants of resolve_security.

Cleanup: removed (issue #235) tags from 8 sites, dropped section
dividers, updated ADR 013 row to explain CONNECTION_CLOSE choice.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
# Conflicts:
#	crates/node/tests/probe_loopback.rs
#	deny.toml
@thiras
thiras requested a review from alpergundogdu May 2, 2026 06:45
ConnectionLimiter now resizes in place: token-bucket maps mutate under
their existing Mutex (preserving last_refill and accumulated tokens
clamped to the new burst), and Arc<Semaphore> identity stays stable
across cap changes via add_permits / acquire_many_owned(...).forget().
RuntimeReloadState gains a limiter slot wired into the reload pipeline
with the same fallible-then-commit contract as cache.pinned_hashes.

`0` in any security.* field disables that layer (no global cap, layer
short-circuit, or unbounded source map); rate>0 paired with burst=0
remains rejected as a deny-all corner. Invalid security values now
reject the entire reload (all-or-nothing), replacing the
"requires-restart" warning that became a lie once values applied live.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@thiras
thiras requested a review from Copilot May 2, 2026 11:03
@thiras

thiras commented May 2, 2026

Copy link
Copy Markdown
Contributor Author

/gemini review

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

Copilot reviewed 14 out of 14 changed files in this pull request and generated 3 comments.


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

Comment thread crates/node/src/runtime/reload.rs Resolved
Comment thread crates/node/src/config/types.rs Resolved
Comment thread crates/node/src/config/types.rs Resolved

@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 implements a comprehensive connection rate-limiting framework to mitigate connection exhaustion attacks. It introduces a ConnectionLimiter that manages global concurrency permits and per-source token buckets (IP and NodeID), integrated with the node's hot-reload system and metrics. The review feedback highlights a critical safety issue where non-monotonic clock behavior could cause a panic and identifies significant performance bottlenecks in the rate-limit map's eviction and resizing logic, specifically pointing out O(N) and O(N^2) complexities that could lead to excessive lock contention.

Comment thread crates/node/src/dispatch.rs Resolved
Comment thread crates/node/src/dispatch.rs Resolved
Comment thread crates/node/src/dispatch.rs Resolved
thiras and others added 2 commits May 2, 2026 14:26
- ConnectionLimiter::reload's public doc no longer links to private
  BoundedRateMap::{set_rate_burst,set_cap}; rustdoc -D warnings rejects
  intra-doc links from public to private items.
- SecurityConfig per-field docs now match resolve_security: rate=0 alone
  disables the layer; the paired burst is ignored (the limiter's
  try_consume short-circuits before the bucket is touched). Previously
  the docs claimed "both rate=0 AND burst=0 to disable" while validation
  only checked the rate.
- BoundedRateMap::set_cap: replace the O(N²) shrink loop (evict_oldest
  in a loop) with a single O(N) select_nth_unstable_by_key partition +
  bulk remove. Worst case at the default 4096 cap drops from ~16M
  comparisons under the held mutex to a linear scan plus a partial sort.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Doc/comment fixes:
- Replace stale (#issue) placeholder in BoundedRateMap::set_rate_burst
- Drop acquire_for_test's invented rustdoc-discoverability claim
- Correct set_cap complexity: select_nth_unstable_by_key is average O(n)
  via introselect, not "linear with a log factor"
- Point Permit doc at acquire_inner (the actual gauge-increment site)
- Trim acquire_inner's stale doc that predates acquire_for_test
- Replace "now fully reloadable" / "no longer get a warning" wording
  with steady-state phrasing in log_ignored_other_sections trailing comment
- Document the .min(burst) clamp's role in safe set_rate_burst across
  dramatic rate drops with stale last_refill
- Clarify attach_cache/attach_limiter poison handling: recovery stores the
  new value but does NOT clear the poison flag; subsequent reloads
  fail-stop with "<slot> attach mutex poisoned"

Operator-visibility fixes:
- Bind err in shrink-task Err arm (was throwing it away). Bound %err
  surfaces if a future tokio AcquireError variant appears.
- Spell out all-or-nothing semantics in every reload reject warn line:
  payment+security typo no longer leaves operators wondering whether
  their unrelated payment edit applied.
- Add walkable example trace (cap=4 → 0 → 3 → 5) to ConnectionLimiter
  ::reload doc + ties-on-last_refill caveat to set_cap doc

New tests (5):
- concurrent_reloads_converge: 8 concurrent reloads racing for the same
  limiter; pins target_lock serialization.
- bounded_map_disable_then_reenable_preserves_existing_buckets: rate=0
  → rate>0 round-trip preserves bucket fairness state.
- reload_disabled_to_disabled_preserves_live_baseline: (0,0) reload
  must not reset live_semaphore_size.
- bounded_map_set_cap_zero_makes_unbounded_and_retains_entries: set_cap(0)
  transitions to unbounded mode without clearing entries.
- reload_preserves_metrics_handle_for_post_reload_rejects: Arc<Metrics>
  handle survives reload; reject counters still increment.

Make Metrics::encode pub(crate) so dispatch tests can verify post-reload
counter increments.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@thiras

thiras commented May 2, 2026

Copy link
Copy Markdown
Contributor Author

Addressed review feedback in 147002b. Summary of what changed and what was deliberately left unchanged:

Fixed (doc/comment accuracy)

  • Stale (#issue) placeholder in BoundedRateMap::set_rate_burst doc
  • acquire_for_test's invented rustdoc-discoverability claim — #[doc(hidden)] excludes it from rendered docs, so the "see also" line was wrong
  • set_cap complexity claim — select_nth_unstable_by_key is average O(n) via introselect, not "linear with a log factor"
  • Permit doc points at acquire_inner (where the gauge-increment lives), not acquire
  • Trimmed acquire_inner's stale doc that predated acquire_for_test
  • Replaced "now fully reloadable" / "no longer get a warning" wording in the trailing log_ignored_other_sections comment with steady-state phrasing
  • Documented the .min(burst) clamp's role in keeping set_rate_burst safe across dramatic rate drops with stale last_refill
  • Clarified attach_cache/attach_limiter poison handling: recovery stores the new value but does NOT clear the poison flag — subsequent reloads then fail-stop, by design

Fixed (operator visibility)

  • Bound err in the shrink-task Err(_) arm (was discarded). Surfaces if a future tokio AcquireError variant appears.
  • Spelled out all-or-nothing semantics in every reload-reject warn! line. A [payment] (valid) + [security] (invalid) typo no longer leaves operators wondering whether the payment change applied.
  • Added a walkable example trace (cap=4 → 0 → 3 → 5) to ConnectionLimiter::reload doc + ties-on-last_refill caveat to set_cap doc.

New tests (5)

  • concurrent_reloads_converge — 8 concurrent reloads racing for the same limiter; pins target_lock serialization (was previously asserted only in prose).
  • bounded_map_disable_then_reenable_preserves_existing_buckets — rate=0 → rate>0 round-trip preserves bucket fairness state. Was claimed in the docstring but uncovered.
  • reload_disabled_to_disabled_preserves_live_baseline — (0,0) reload must not reset live_semaphore_size.
  • bounded_map_set_cap_zero_makes_unbounded_and_retains_entries — set_cap(0) transitions to unbounded mode without clearing entries.
  • reload_preserves_metrics_handle_for_post_reload_rejects — Arc<Metrics> survives reload; reject counters still increment.

(Metrics::encode was made pub(crate) to support the metrics-after-reload assertion.)

Deliberately not addressed

  • Issue-number proliferation in comments — house style of this codebase; not a regression.
  • SecurityConfig doc bleeds implementation detail ([N, N+1] window, acquire_many_owned) — operators tuning these knobs benefit from knowing the racing-reload semantics. Keeping it.
  • Add a decdn_security_layer_disabled metric — real value but scope creep for this PR; can be a follow-up.
  • Deterministic shrink-task synchronization — current yield_now() + sleep slack (~64ms) is adequate; deterministic sync would require a test-only API surface.
  • set_cap(cap) where new == len — <= early-return is robust enough; one-liner test of low value.
  • Production wiring test for runtime::run calling attach_limiter — would require a test seam on runtime::run. Out of scope.
  • All-zeros / fully-disabled→fully-enabled holistic transition — covered by per-layer tests + connection_limiter_disabled_global_skips_semaphore.
  • attach_limiter(None) detach — production never does this; the None case is documented as a test seam only.

273/273 tests pass; clippy, fmt, cargo doc, cargo deny all clean.

@thiras
thiras requested a review from Copilot May 2, 2026 11:57
@thiras

thiras commented May 2, 2026

Copy link
Copy Markdown
Contributor Author

/gemini review

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

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


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

Comment thread crates/node/src/metrics.rs Resolved
Comment thread crates/node/src/dispatch.rs Resolved

@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 implements a multi-layered connection rate-limiting system to protect the node from connection floods, featuring a global concurrency cap and per-source token buckets. The security configuration is hot-reloadable via SIGHUP, and new metrics are introduced to monitor load-shedding. Feedback focuses on a critical race condition in the TokenBucket constructor that could cause panics due to timestamp inconsistencies, as well as a performance concern regarding the O(N) linear scan used for entry eviction in the rate-limiting maps.

Comment thread crates/node/src/dispatch.rs Resolved
Comment thread crates/node/src/dispatch.rs Resolved
Comment thread crates/node/src/dispatch.rs Resolved
Comment thread crates/node/src/dispatch.rs Resolved
Comment thread crates/node/src/dispatch.rs Resolved
Comment thread crates/node/src/dispatch.rs Resolved
Comment thread crates/node/src/dispatch.rs Resolved
thiras and others added 2 commits May 2, 2026 15:08
The OpenMetrics encoder appends `_total` to counter fields per the
spec; field names that already end in `_total` get rendered as
`*_total_total`, which is awkward and inconsistent with `probe_requests`
(no `_total` in the field, exposed as `decdn_probe_requests_total`).

Rename the three dispatch counter fields:
  dispatch_rejected_global_total → dispatch_rejected_global
  dispatch_rejected_per_node_total → dispatch_rejected_per_node
  dispatch_rejected_per_ip_total → dispatch_rejected_per_ip

Operator-visible metric names are unchanged from what they will be
once this PR merges; only the internal Rust field names move. The
gossip_*_total fields are pre-existing on main and out of scope here.

Update the metrics-after-reload test assertion to match the corrected
exposition name.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Critical:
- resolve_security clamps max_concurrent_handlers at
  Semaphore::MAX_PERMITS so a too-large value fails config rather than
  panicking inside Semaphore::new / add_permits during SIGHUP reload.
- Permit/acquire_inner doc-comments now describe the real gauge
  bookkeeping site (dispatch_permit_acquired runs on success before
  Permit construction; Drop decrements unconditionally).
- lock_recover takes a per-mutex AtomicBool gate so poison-error logs
  fire once per process, not once per acquire.

Important:
- Shrink-task forget() failure logs at error! and bumps a new
  dispatch_shrink_skipped counter so live_semaphore_size drift is
  observable rather than silent.
- IPv6 addresses bucket by /64 prefix in the per-IP layer so a
  customer-grade allocation can't be churned to defeat the limit.
- New dispatch_per_ip_skipped_no_addr counter (gated on a per_ip_enabled
  AtomicBool mirror) records relay-only acceptances under an enabled
  per-IP layer.
- Rate-limit rejection in probe handler awaits conn.closed() with a
  bounded 250 ms timeout so peers reliably observe the 0x10 reason byte
  and its layer label.

Polish:
- Permit is #[must_use] so let _ = limiter.acquire(...) is a compile
  error.
- frame_err_code matches every FrameError variant explicitly.
- pin_diff log emits Option<count> + pinned_skipped_no_cache_attached
  rather than misleading zeros.
- Stale issue-number references and speculative future-state comments
  trimmed; set_cap O(n²) doc corrected to introselect O(n).

Tests:
- Encoded-scrape assertions for the global and per-IP reject counters.
- Relay-only-with-layer-enabled skip counter test.
- IPv6 /64 bucket-collapse + cross-/64 separation test.
- Multi-thread acquire-storm vs reload-storm convergence test.
- 278/278 nextest pass; cargo clippy --workspace -- -D warnings clean;
  cargo doc with -D warnings clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@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.

Thanks for the thorough work — the layered limiter is solving the right threat and the new metrics + ADR 013 update are well-placed. My pushback is on the cost-per-reloadable-knob this establishes, not on hot-reload as a feature: I want every future config field that wants live tuning to be a small ask, not another inline limb in RuntimeReloadState::reload with its own state-preservation contract.

Four asks, in priority order:

1. Collapse per-IP and per-NodeID into a single per-source layer

NodeIDs are free to mint (ADR 001 acknowledges this), so per-NodeID alone is bypassable for ~zero cost. Keeping per-IP and per-NodeID as separate layers means two token-bucket maps, two metrics, two disable knobs, two reject reasons, and two sets of tests for what is effectively the same defense.

Concretely, replace per_node_rate_per_sec / per_node_burst / per_ip_rate_per_sec / per_ip_burst with per_source_rate_per_sec / per_source_burst. The "source" is the peer IP today; if NodeID-keying ever becomes useful later, it is a small additive change to make the source key configurable. This drops RejectReason::PerNodeId, the per-NodeID counter, the per-NodeID disable path, and the related tests.

2. Replace the hand-rolled token bucket with governor

governor::DefaultKeyedRateLimiter (or governor::RateLimiter::keyed(...)) is the maintained crate the rest of the Rust ecosystem already uses for exactly this — keyed rate limiting with burst, eviction, and well-tested clock handling (including the IPv6-backward-clock-skew case this PR has its own test for). Adopting it deletes:

  • TokenBucket and its tests
  • BoundedRateMap and its eviction policy + tests
  • The IPv4/IPv6 backward-clock-skew test
  • The disable→re-enable resume contract for buckets

…in exchange for one dependency we don't have yet. The bigger win is that keyed-limiter logic stops being something we own and audit ourselves.

3. Factor a Reloadable trait now, with security as a concrete impl

The hot-reload story is the right feature, but the per-section glue accreting inline in RuntimeReloadState::reload is the bit that won't scale. After payment + log_level + pinned_hashes + security, the function grows linearly per knob. The next operator-tunable config field becomes another resolve / validate / diff-log / lock / commit-with-rollback limb inline in the same function.

A small abstraction, paid once, fixes this. Roughly:

```rust
trait ReloadableSection {
type Resolved;
fn name(&self) -> &'static str; // log + diff snapshot key
fn resolve(&self, file: &FileConfig) -> ResultSelf::Resolved;
fn fallible_commit(&self, _: &Self::Resolved) -> Result<()> { Ok(()) }
fn infallible_swap(&self, _: Self::Resolved);
}
```

`RuntimeReloadState` holds a list of sections; the reload algorithm becomes fixed:

  1. Resolve every section. Any failure → return early, previous values retained (the existing contract).
  2. Run every `fallible_commit` in order. The log-level filter swap and (with #4 below relaxed) the semaphore resize live here. This is the rollback boundary — commits already applied stay applied; a later failure aborts the rest. Document that explicitly.
  3. Run every `infallible_swap` (atomic stores, `Arc` swaps, in-place mutations under each section's own `Mutex`).

Migrate the existing sections (payment / log_level / pinned_hashes) to impls in the same PR. Security becomes another impl. Net code change for this PR is roughly neutral; the next reloadable knob is a small impl on a small struct rather than another inline limb.

I think it is fine to do this in this PR — the security section is the third+fourth section to land and is the natural forcing function for the abstraction. If you would rather defer, negotiable, but I would want a clear follow-up issue + a first-user commitment for whatever lands next.

4. Reset bucket state on reload, and swap the semaphore instead of resizing

Two places where the limiter's apply is doing more than it needs to:

  • Token-bucket state preservation across reload — `set_rate_burst`'s contract that `last_refill` is preserved and `tokens` is clamped to the new burst, plus the disable→re-enable resume guarantee. At any timescale operators care about, "reset buckets on reload" is operationally indistinguishable. Drop the `set_rate_burst` mutator. With #2 above, this is moot — `governor` does not have these mutators in the first place.
  • Semaphore identity preservation via `add_permits` + `acquire_many_owned(...).forget()`, with `target_max_concurrent` vs `live_semaphore_size` split, the parked-shrink task, and the drift-accounting comments. Replace with an `Arc` swap at next-acquire boundary. Already-acquired permits hold the old semaphore alive until they drop; new acquires hit the new one. The operator-visible difference is sub-second on a small mesh.

This collapses the `target_lock: Mutex<()>` serialization, the bulk-shrink `select_nth_unstable_by_key` path, the racing-reload-storm test, and most of the reasoning the doc comments justify.


What stays:

  • Three-layer enforcement → two-layer (global cap + per-source). Both layers are still defended.
  • `APP_ERR_RATE_LIMITED` / `0x10` close code and ADR 013 update.
  • Hot-reload as a feature, end-to-end (SIGHUP + `admin_v1_reload`).
  • Metrics: `decdn_dispatch_rejected_global_total`, `decdn_dispatch_rejected_per_source_total` (renamed from per-IP), `decdn_dispatch_in_flight`. Drop the per-NodeID counter.
  • The all-or-nothing reload semantics (the trait soaks them up; the contract stays).

Net: same operator-facing feature surface, considerably less code we have to reason about, and the next operator-tunable config field added is a small implementation on a small struct rather than another inline limb. Happy to pair on the trait shape if that helps.

alpergundogdu and others added 2 commits May 4, 2026 06:15
…vernor

Drop the hand-rolled `TokenBucket` + `BoundedRateMap<K>` and the parallel
per-NodeID layer; replace both with a single `governor::DefaultKeyedRateLimiter`
keyed on `IpAddr`. Two of the four asks on PR #386's review collapse into
this commit because they're entangled: the keyed limiter no longer needs
to know about NodeID, and adopting `governor` (0.10) is the maintained-
crate replacement for the bespoke token-bucket code.

Surface changes:
- Config: `per_ip_*`/`per_node_*` → single `per_source_*` pair.
  `per_source_rate_per_sec = 0` disables the layer; per-NodeID is gone.
- Metrics: `dispatch_rejected_per_ip` + `dispatch_rejected_per_node`
  fold into `dispatch_rejected_per_source`. The skip counter for relay-
  only connections is renamed to `dispatch_per_source_skipped_no_addr`.
- `RejectReason::PerIp`/`PerNodeId` → `RejectReason::PerSource`. Reason
  string `"per-source"`. ADR 013's close-code description trimmed to
  match.
- `ConnectionLimiter::acquire_for_test` no longer takes a node key —
  `peer_ip: Option<IpAddr>` is the only argument.

Naming: "per-source" is intentional. Today the source axis is the
remote `IpAddr` (`/64`-grouped for IPv6, as before). Future keying
axes (NodeID, ASN, etc.) can land without renaming the operator-
visible config and metrics surface.

Implementation:
- `governor::DefaultKeyedRateLimiter<IpAddr>` behind an `RwLock<Option<Arc<...>>>`.
  `None` = layer disabled.
- Cap enforcement: when `limiter.len() > cfg.max_tracked_sources`,
  call `retain_recent()` lazily under the read guard so the keyspace
  stays bounded without a background task.
- `reload()` rebuilds the keyed limiter from the new quota and swaps
  it under the write lock. Token-bucket state is *not* preserved
  across the rebuild — operators tuning a live quota should expect
  the next acquire from each source to start with a fresh burst
  budget. (This was PR #386 review ask #4; falls out for free with
  the rebuild-and-swap approach.)
- Semaphore resize logic untouched (PR #386 ask #2 lands in a follow-up).

Tests: dispatch.rs test module rewritten end-to-end. Dropped tests
covered TokenBucket internals (refill, burst-cap, clock-skew) and
BoundedRateMap mutators (eviction, set_cap, set_rate_burst, disable→
re-enable resume) — governor owns those now. Kept tests cover
ConnectionLimiter behaviour: rejection on global/per-source exhaustion,
relay bypass, IPv6 /64 grouping, hot-reload grow/shrink/disable→re-enable,
concurrent-reload convergence, acquire-storm-vs-reload-storm. All 218
unit tests + 7 probe_loopback + 18 admin_peers + 14 config_validate +
2 sighup_signal pass; clippy and rustdoc clean.

Out of scope (tracked for follow-up commits on the same PR):
- swap-not-resize the global `Arc<Semaphore>` on reload (PR #386 ask #2)
- factor a `Reloadable` trait and migrate sections (PR #386 ask #3)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Replace the add-permits / acquire_many_owned(...).forget() resize
pattern in `ConnectionLimiter` with a whole-`Arc<Semaphore>` swap via
`arc_swap::ArcSwapOption`. On reload the limiter builds a fresh
`Arc<Semaphore>` (or `None` when `max_concurrent_handlers == 0`) and
atomically stores it; new acquires hit the new cell while
already-acquired `OwnedSemaphorePermit`s hold a clone of the previous
`Arc` and drop it harmlessly when released.

Drops the drift-accounting machinery (`target_max_concurrent`,
`live_semaphore_size`, `target_lock`) and the parked-shrink task that
reconciled them, plus the `dispatch_shrink_skipped` metric (no shrink
task left to fail). Drops tests that exercised those invariants
(`concurrent_reloads_converge`, `reload_disabled_to_disabled_preserves_
live_baseline`, `connection_limiter_reload_target_tracking_handles_
repeated_grow`, `acquire_storm_during_reload_storm_does_not_panic`)
and rewrites the grow/shrink/disable+re-enable tests around the new
"new acquires hit the new cap immediately" semantics.

The operator-visible difference is sub-second permit-count freshness
on a small mesh in exchange for materially simpler reload reasoning:
no parked task, no racing N->N+1->N drift, no recorded-vs-actual
divergence on shrink failure. Addresses review-comment #2 on PR #386.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…tions

Extract the inline per-section glue in `RuntimeReloadState::reload` into
a small `ReloadableSection` trait so adding the next reloadable knob no
longer means touching the central reload body. Addresses ask #3 from the
review on PR #386.

## Trait shape

```rust
trait ReloadableSection: Send + Sync {
    fn name(&self) -> &'static str;
    fn clear_buffer(&self);
    fn resolve(&self, file: &FileConfig) -> anyhow::Result<()>;
    fn fallible_commit(&self) -> anyhow::Result<()> { Ok(()) }
    fn infallible_swap(&self);
}
```

The associated `Resolved` type is erased via a per-section
`Mutex<Option<Resolved>>` buffer cell (option (a) from the brief). This
keeps the trait `dyn`-safe — `RuntimeReloadState` holds
`Vec<Arc<dyn ReloadableSection>>` and iterates it three times per
reload — without forcing a single uniform `Resolved` type across
sections. The buffer's lifecycle: emptied at the start of every
`reload()` (via `clear_buffer`), filled by `resolve`, read by
`fallible_commit`, drained by `infallible_swap`.

## What moved

Each of the four current sections becomes a concrete impl that owns
the state it mutates:

- `PaymentSection` — holds the `Arc<AtomicU64>` for `rate_per_mb` and
  the `PaymentArgs` CLI override.
- `LogLevelSection` — holds the `LogLevelSetter` closure, the
  `current` cache (Mutex<Option<LogLevel>>) for first-reload-applies,
  and the `ObservabilityArgs` CLI override. This is the only section
  with a non-trivial `fallible_commit` (the tracing-filter swap).
- `PinnedHashesSection` — holds the optional `CacheEngine` (attached
  via `attach_cache`).
- `SecuritySection` — holds the optional `Arc<ConnectionLimiter>`
  (attached via `attach_limiter`).

`RuntimeReloadState::reload` becomes a fixed three-phase iteration:

1. Resolve every section. Any failure → return early, previous values
   retained for every section (existing all-or-nothing contract).
2. Run every `fallible_commit`. Documented as the rollback boundary:
   commits already applied stay applied if a later section fails.
3. Run every `infallible_swap`. Atomic stores, `Arc` swaps, and
   `ConnectionLimiter::reload` (the semaphore swap from 46235af is
   infallible, so it lives here, not in phase 2).

## What stayed

- Public API of `RuntimeReloadState`: `new`, `attach_cache`,
  `attach_limiter`, `seed_initial_file_snapshot`, `reload`,
  `rate_per_mb`, `current`, `for_test_with_setter`. Unchanged.
- The all-or-nothing contract: previous values retained for every
  section on any resolve failure.
- The `last_file_sections: Mutex<FileSectionSnapshot>` snapshot/diff
  machinery and the "log changes to non-reloadable sections once"
  plumbing — driven inline in `reload()`, not through the trait, since
  it's cross-cutting rather than per-section.
- Section ordering (`payment`, `log_level`, `pinned_hashes`,
  `security`) — preserved verbatim so operator-visible commit
  ordering doesn't shift behind the refactor.
- Every existing test passes unchanged in behaviour. The poisoned-
  mutex tests adapt to the new field paths
  (`state.cache` → `state.pinned.engine`, `state.limiter` →
  `state.security.limiter`, `state.current_log_level` →
  `state.log_level.current`) but the contracts they enforce — setter
  not called when log-level mutex is poisoned, rate atomic not moved
  on snapshot-mutex poison, etc. — are identical.

## Tracing

Each section emits its own `config reload section applied` info
event keyed by `section = name()`, instead of the prior monolithic
"config reload applied" line carrying every field at once. The
aggregated "config reload applied" line is retained as an
end-of-reload marker for any operators / log scrapers that grep for
it.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@alpergundogdu

Copy link
Copy Markdown
Contributor

All four review asks addressed across three commits on top of the original work:

PR body updated to reflect the new shape. Tree green: clippy clean, doc clean, fmt clean, lib 213/213, four integration test binaries individually 18+14+7+2/41. Ready for re-review.

CI clippy on Rust 1.95 caught a map(...).unwrap_or(false) on the swap_applied poison-recoverable lock; rewrite as is_ok_and(...). Local clippy on a slightly older toolchain didn't flag it.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@alpergundogdu

Copy link
Copy Markdown
Contributor

/gemini review

@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 implements per-source rate limiting and a global concurrency cap for QUIC connections, featuring hot-reloadable security configurations and enhanced metrics. The review highlights opportunities to reduce resource overhead and lock contention, such as bypassing the closure timeout for global rejections to prevent task accumulation and moving expensive map pruning operations outside of read-lock guards. A minor suggestion was also provided to update imports for the RejectReason enum.

Comment thread crates/node/src/handlers/probe.rs Resolved
Comment thread crates/node/src/dispatch.rs Resolved
Comment thread crates/node/src/handlers/probe.rs Resolved
@alpergundogdu

Copy link
Copy Markdown
Contributor

Quick triage of the new comments — most are stale on the post-reshape branch.

Stale (concerns about code deleted in 4f87586 / 46235af / 153c335):

Bot Concern Status
Gemini BoundedRateMap::evict_oldest linear-scan lock contention (DoS risk) BoundedRateMap deleted entirely; governor::DefaultKeyedRateLimiter owns eviction now.
Gemini TokenBucket::try_consume Instant::now() race / duration_since panic TokenBucket deleted entirely; governor handles its own clock arithmetic with documented monotonic guarantees.
Gemini set_cap shrink loop O(N²) The whole set_cap mutator is gone — reload rebuilds the keyed limiter from new quota and swaps. No iterative shrink path.
Copilot BoundedRateMap::try_consume two-hash-lookup hot-path Same as above — BoundedRateMap deleted.
Copilot per_node_* disable-doc disagreement (rate=0 alone disables, docs imply both) per_node_* fields removed entirely; per-source is the single layer now.
Copilot Counter fields ..._total_total double suffix Already addressed in 58024c4 ("drop redundant _total suffix from dispatch counter fields") before reshape.
Copilot PR description claims [security] not reloadable but implementation reloads it PR description was updated post-reshape; security is reloadable per the ReloadableSection migration in 153c335.
Copilot Test asserts on ..._total_total exposition Test was updated alongside the metric rename.

Genuinely on the latest commit (0cb0520) — replied inline below:

Bot Concern Verdict
Gemini conn.paths().peek().clone() won't compile (claims PathIter lacks peek() and Clone) False alarm; compiles cleanly on iroh 0.98 (which we depend on after 35c10d8). Workspace clippy is green.
Copilot [security] missing from FileSectionSnapshot / log_ignored_other_sections Misreading — security is reloadable, so it shouldn't be in the "requires restart" snapshot.

Pinging @gemini-code-assist for a fresh re-scan against the post-reshape HEAD if useful.

…ip close-flush on GlobalFull

Two review fixes from gemini-code-assist on the post-reshape branch:

1. dispatch.rs: snapshot the limiter Arc and cap under the per_source read guard, drop the guard, then run check_key + retain_recent. Holding the read guard across an O(n) walk would block reload writers under flood. The Arc clone keeps the observed KeyedRateLimiter alive across a concurrent reload swap — operating on the prior generation is operationally indistinguishable.

2. probe.rs: skip the post-rejection conn.closed() flush wait on RejectReason::GlobalFull. Under a global-cap flood every rejection would otherwise park a task for up to REJECTION_CLOSE_TIMEOUT (250ms); at thousands of rejections per second that is the exact memory-pressure path the limiter exists to prevent. Layer label is least useful for GlobalFull anyway (operators pivot on the metric counter). Per-source rejections still wait — the bucket itself rate-limits the parking cost.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@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 a connection rate-limiting and concurrency-capping mechanism for the node, utilizing a global semaphore and a per-source keyed rate limiter. The system supports hot-reloading of security configurations and includes comprehensive metrics for monitoring load-shedding. Feedback points out a bug in dispatch.rs where an iterator is incorrectly peeked, recommending the use of a Vec for multiple iterations. Additionally, there is a performance concern regarding the O(N) cost of pruning the rate limiter's keyspace during every connection acquisition.

Comment thread crates/node/src/dispatch.rs Resolved
Comment thread crates/node/src/dispatch.rs Resolved
Gemini flagged that calling retain_recent every acquire when over cap could be a sustained-flood bottleneck. Add a 10% margin so the O(n) walk only fires when the keyspace is materially over (cap + cap/10), not on 1-key-over-cap fluctuations. Worst-case overhead is one prune per cap/10 newly-tracked sources rather than one prune per accept.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@alpergundogdu

Copy link
Copy Markdown
Contributor

/gemini review

@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 a connection rate-limiting and concurrency-capping mechanism for the node. It implements a ConnectionLimiter that enforces a global semaphore for total in-flight tasks and a per-source rate limit using the governor crate, with IPv6 addresses masked to their /64 prefix to prevent allocation-based bypasses. The security configuration is hot-reloadable via SIGHUP, supported by a refactored ReloadableSection trait in the runtime. Additionally, new metrics have been added to track rejections and in-flight tasks. Feedback identifies a potential performance bottleneck in the lazy pruning of the rate-limiter's keyed map, which could lead to CPU exhaustion during a sustained connection flood.

Comment thread crates/node/src/dispatch.rs Resolved
Gemini flagged that even with the 10% slack from 3fd1288, N threads observing over-cap simultaneously would each spawn an O(n) retain_recent walk. Add a pruning_in_progress AtomicBool guard: at most one thread prunes at a time; concurrent over-cap observers skip; the next observer after the prune completes picks up any remaining work. Bounds the worst-case prune throughput to one O(n) walk in flight regardless of accept-thread count.

Co-Authored-By: Claude Opus 4.7 (1M context) <[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.

dispatch: no per-IP or per-Nodeld connection rate limit, enabling cheap connection exhaustion

3 participants