Skip to content

feat(node): cdn/dht/v1 handler + routing table + 3-layer rate limiter (PR 2/4 of #320) - #643

Merged
alpergundogdu merged 6 commits into
mainfrom
dht-handler-routing
May 22, 2026
Merged

alpergundogdu merged 6 commits into
mainfrom
dht-handler-routing

Conversation

@thiras

@thiras thiras commented May 21, 2026

Copy link
Copy Markdown
Contributor

Summary

PR 2 of 4 for #320 (Kademlia content DHT). Wires the cdn/dht/v1 handler skeleton into the runtime and lands the routing table + rate limiter the rest of the DHT machinery will build on. Based on #642 (PR 1/4 of the same stack).

  • crates/node/src/dht/routing.rs — k-bucket routing table (K=20, 256 buckets) keyed by XOR distance to the node's own NodeId (ADR 022 §Routing Table). LRU eviction on bucket overflow; ping-then-evict deferred to PR 4 with the FindNode driver. Self-id inserts are no-ops.
  • crates/node/src/dht/rate_limit.rs — three-layer token-bucket limiter (per-peer NodeId, per-IP, global) with cheapest-first short-circuit per ADR 022 §DHT Rate Limiting. Trusted-IP exemption bypasses per-IP only. Each layer is independently disable-able (rate==0 paired with burst==0). Backed by governor, same as ConnectionLimiter.
  • crates/node/src/handlers/dht.rs — ProtocolHandler honoring FindNode; Store/FindValue return safe placeholders until PR 3. Full ADR 013 error-code mapping (0x01/0x02/0x03/0x10).
  • crates/common/src/config/{types,resolved}.rs + resolver — DhtConfig / ResolvedDht with rate/burst pairs and a parsed trusted-IPs set. Defaults match ADR 022 (20/100/1000 req/s, 40/200/2000 burst). Same pairing rules as security.per_source_* — rate>0 with burst=0 is rejected at config time.
  • decdn_dht_rate_limit_rejected_{per_peer,per_ip,global}_total metrics. ADR 022 §Observability specifies a labeled counter; iroh_metrics::MetricsGroup doesn't support per-field labels, so we follow the existing dispatch_rejected_* pattern with one Counter per layer. Operators with the ADR-022 alert form do a Prometheus sum() to recover the rolled-up rate.
  • Runtime registers cdn/dht/v1 on the router alongside cdn/probe/v1 and iroh-gossip.
  • Loopback integration test in tests/dht_loopback.rs exercising both FindNode and the PR-2 FindValue placeholder shape.

Deferred (per the approved issue-320 plan)

  • Record store, Store/FindValue admission, per-publisher quota, receiver-anchored TTL, iterative lookup — PR 3.
  • Republish scheduler, bootstrap, on-chain origin-directory fallback — PR 4.
  • BatchStore variants (ACs 17–20) and prefetch / popularity signals (ACs 7–8) — follow-up issues.

Test plan

  • cargo nextest run — 963/963 pass (28 new DHT unit tests + 2 new loopback tests + existing suite).
  • cargo clippy --all-targets -- -D warnings clean.
  • cargo fmt -- --check clean.
  • pre-commit run --all-files — every hook passes (fmt, clippy, doc, deny, ADR hygiene).
  • DHT loopback verifies FindNode returns seeded closer-nodes, refreshes the requester into the responder's table, and excludes the responder's own NodeId.
  • Rate-limiter tests cover all three layers, cheapest-first ordering, trusted-IP exemption (bypasses per-IP only), and the metric counter increments in the scrape.

Refs #320. Stacked on #642.

🤖 Generated with Claude Code

Introduces `DhtMessage` and the six request/response structs for the
Kademlia content DHT specified in ADR 022 §Message Types:
`FindValue{Request,Response}`, `Store{Request,Ack}`,
`FindNode{Request,Response}`. The variant order is frozen per
ADR 013 §Protocol Enums and pinned by per-variant discriminant tests so
a reorder fails CI loudly rather than breaking wire compatibility
silently.

Authentication on `StoreRequest` is by QUIC-bound NodeId equality, not
a per-record signature — this depends on records being pushed directly
by the holder and never relayed peer-to-peer. The module docs flag the
invariant so a future relay scheme reintroduces the signature plus
in-scope sender timestamp together (ADR 015 §Replay Safety Analysis).

`BatchStoreRequest` / `BatchStoreAck` are deferred to a follow-up
issue. ADR 022 specifies them as a bandwidth optimization with a
per-hash fallback only useful at C ≥ 10k cached blobs; when added they
append after `FindNodeResponse` so existing discriminants are
preserved.

Wire-cap constants (`MAX_PROVIDERS_PER_HASH = 50`,
`MAX_CLOSER_NODES = 20`) bound the max-size `FindValueResponse` under
the ~2.3 KB ceiling from ADR 022 §DHT Bandwidth Analysis; the upper
bound is asserted by a test so future field additions can't drift past
it unnoticed.

Refs #320.

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

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 (2/4 of #320) wires the new cdn/dht/v1 Kademlia DHT handler into the node runtime and introduces the foundational routing table + 3-layer per-request rate limiter, along with config plumbing, metrics, and loopback tests.

Changes:

  • Add cdn/dht/v1 handler skeleton (serves FindNode; placeholder responses for Store/FindValue) and register it in the runtime router.
  • Introduce an in-memory k-bucket routing table and a three-layer (global / per-IP / per-peer) token-bucket rate limiter with new rejection metrics.
  • Extend common config resolution with a [dht] section and add integration tests validating loopback behavior.

Reviewed changes

Copilot reviewed 15 out of 15 changed files in this pull request and generated 8 comments.

Show a summary per file
File Description
crates/node/tests/sighup_signal.rs Updates test config seed to include ResolvedDht.
crates/node/tests/dht_loopback.rs Adds loopback tests covering FindNode and current FindValue placeholder behavior.
crates/node/src/runtime/reload.rs Updates runtime reload test scaffolding to include ResolvedDht.
crates/node/src/runtime/mod.rs Wires DHT rate limiter + handler into runtime and registers ALPN on router.
crates/node/src/metrics.rs Adds per-layer DHT rate-limit rejection counters and helper methods.
crates/node/src/lib.rs Exposes new dht module from the crate root.
crates/node/src/handlers/mod.rs Registers the new handlers::dht module.
crates/node/src/handlers/dht.rs Implements the cdn/dht/v1 handler skeleton with routing-table refresh + per-request rate limiting.
crates/node/src/dht/routing.rs Adds k-bucket routing table implementation with unit tests.
crates/node/src/dht/rate_limit.rs Adds three-layer DHT rate limiter + unit tests.
crates/node/src/dht/mod.rs Adds DHT module facade and re-exports for routing/rate limiting.
crates/common/src/config/types.rs Adds [dht] config section types.
crates/common/src/config/resolved.rs Adds ResolvedDht to resolved config model and defaults.
crates/common/src/config/mod.rs Implements DHT config resolution + trusted IP parsing and threads into resolve_config.
crates/cli/tests/config_validate.rs Updates CLI config validation tests to include ResolvedDht.

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

Comment thread crates/node/src/dht/routing.rs Resolved
Comment thread crates/node/src/dht/routing.rs Resolved
Comment thread crates/node/src/dht/rate_limit.rs Resolved
Comment thread crates/node/src/dht/rate_limit.rs Resolved
Comment thread crates/node/src/dht/rate_limit.rs Resolved
Comment thread crates/node/src/handlers/dht.rs Resolved
Comment thread crates/node/src/dht/routing.rs Resolved
Comment thread crates/node/src/handlers/dht.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 introduces the initial implementation of the Kademlia content DHT (cdn/dht/v1), featuring a three-layer token-bucket rate limiter, a k-bucket routing table, and a protocol handler for FindNode requests. Feedback identifies a high-severity security risk regarding potential routing table poisoning from unauthenticated message fields. Furthermore, several idiomatic improvements are recommended for the routing table implementation, including the use of std::array::from_fn for cleaner initialization, zip for XOR calculations to avoid manual indexing, and sort_unstable_by_key for better readability.

Comment thread crates/node/src/handlers/dht.rs Resolved
Comment thread crates/node/src/dht/routing.rs Resolved
Comment thread crates/node/src/dht/routing.rs Resolved
Comment thread crates/node/src/dht/routing.rs Resolved
Comment thread crates/node/src/dht/routing.rs Resolved
Comment thread crates/node/src/dht/routing.rs Resolved
…nonical

Addresses PR #642 review feedback (gemini-code-assist + Copilot):

- Add `#[serde(deserialize_with = ...)]` field-level hooks enforcing
  `MAX_PROVIDERS_PER_HASH`, `MAX_CLOSER_NODES`, and `MAX_BATCH_STORE_HASHES`
  at the wire boundary. Pattern mirrors `ProbeResponseBody::rate_per_mb`:
  postcard's positional layout stays derive-driven (no mirror struct, no
  manual `Deserialize` impl), and oversize Vec fields now fail decode
  rather than allocating an attacker-chosen size up to the 16 MiB framing
  ceiling.
- Reorder `DhtMessage` variants to match ADR 022 §Message Types: the ADR
  lists `BatchStore`/`BatchStoreAck` at positions 4/5 and
  `FindNode`/`FindNodeResponse` at 6/7. The original PR put `FindNode` at
  4/5; with postcard's sequential discriminant indexing this would have
  forced a future wire-breaking shuffle once `BatchStore` lands. Define
  the `BatchStore` wire types now (no handler) so the production ordering
  matches the ADR and the future BatchStore PR is a pure handler addition.
- Replace the inner-struct-only size guard with a framed-size assertion
  that includes the `DhtMessage` enum discriminant byte AND the
  `write_frame` length-prefix varint, so the ~2.3 KB ADR 022 wire ceiling
  can't drift via discriminant or framing-layer changes.
- New tests: discriminant pinning for `BatchStore` (4) / `BatchStoreAck`
  (5) / `FindNode` (6) / `FindNodeResponse` (7); decode-time rejection
  for oversize `providers`, `closer_nodes`, `BatchStore.hashes`, and
  `BatchStoreAck.results`; exact-MAX boundary acceptance.

Refs #320, addresses #642 review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
thiras added a commit that referenced this pull request May 21, 2026
…n, docs

Addresses PR #643 review feedback (gemini-code-assist + Copilot):

- **HIGH: drop attacker-controlled routing-table refresh.**
  `handle_find_node` was calling `note_peer_seen(req.requester)` on the
  unauthenticated wire field, letting an authenticated peer A send
  `FindNode { requester: B }` to inject any NodeId B into the routing
  table without owning the matching key (routing-table poisoning). The
  authenticated peer NodeId from the QUIC handshake is already
  refreshed once per admitted request in `serve()`, which is the only
  honest signal we have. Removed the second `note_peer_seen` call;
  added a regression test that confirms the attacker-supplied
  `req.requester` is NOT inserted while the authenticated client IS.
- **Replace `unreachable_size_mismatch` with `std::array::from_fn`.**
  The previous helper recursed indefinitely on its own error path —
  the recursion is unreachable by construction but a future
  regression would stack-overflow instead of producing a clear
  diagnostic. `std::array::from_fn` builds the fixed-size array in
  place so the validation step (and the recursion) go away entirely.
- **Fix inverted bucket-index comment.** The code returns bucket 255
  for max distance and bucket 0 for the closest peers; the comment
  said the opposite. Rewrote it (and renamed the two related tests
  `bucket_index_max_distance_is_top_bucket` /
  `bucket_index_min_nonzero_is_bucket_zero`) to match the
  implementation.
- **Re-evaluate `peer_ip` per stream.** Iroh paths can switch over a
  connection's lifetime (relay-only initially, then a direct UDP path
  becomes selected). Capturing the IP once at accept would permanently
  disable the per-IP rate-limit layer for any connection that started
  relay-only. Moved the `peer_ip(&conn)` call inside the per-stream
  loop so a relay→direct switch engages the layer for subsequent
  streams.
- **Align `rate_limit.rs` doc references with the actual emitted
  metric names** (`decdn_dht_rate_limit_rejected_{per_peer,per_ip,
  global}_total` — one Counter per layer, since the metrics backend
  doesn't support per-field labels).
- **`sort_unstable_by_key` in `RoutingTable::closest`.** Computes
  `xor_distance` once per element instead of twice per pairwise
  comparison; lower asymptotic XOR cost on fully-populated tables.
- **`BatchStore`/`BatchStoreAck` dispatch arms.** PR-1 fix
  re-introduced these enum variants at their ADR-canonical
  discriminants; the handler now answers `BatchStore` with a
  per-hash `accepted: false` ack so publishers fall back to per-hash
  `Store` per ADR 022 §Schema Evolution. Handler-side admission
  (two-stage rate limit, holder check, per-hash quota) is the
  follow-up issue tracking `BatchStore` proper.

Deferred to a follow-up issue (raised in PR #643 review):

- Per-IP / per-peer keyed-rate-limiter keyspace cap + periodic GC
  (mirror of `dispatch::ConnectionLimiter::max_tracked_sources` +
  `retain_recent`). Same DoS shape as the dispatch limiter; meaningful
  fix but a self-contained chunk of work with its own runtime wiring.

Refs #320, addresses #643 review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@thiras
thiras force-pushed the dht-handler-routing branch from 052ddd7 to cd6e074 Compare May 21, 2026 17:12
thiras and others added 4 commits May 21, 2026 20:33
Round 2 of PR #642 review (pr-test-analyzer + comment-analyzer).

- `find_value_response_max_framed_size_under_ceiling` previously had
  only `framed_len <= 2_300`. A regression that dropped `providers` or
  `closer_nodes` from the wire shape would shrink the encoded size
  well below the ADR's modeled payload (~2.27 KB) and the test would
  silently pass. Add `framed_len > 2_000` so an accidental field
  removal fails the test loudly.

- Module-level doc for `BatchStore` previously said the runtime "treats
  inbound BatchStore frames as unsupported until then." After the
  PR-#643 fix the handler explicitly closes the stream with
  `APP_ERR_UNSUPPORTED_MESSAGE` (the stream-close-without-ack signal
  ADR 022 §Schema Evolution requires); the doc now reflects the
  precise wire behaviour and cites the matching ADR section.

Refs #320, addresses PR #642 multi-agent review.

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

PR 2 of 4 for #320 (Kademlia content discovery). Wires the
`cdn/dht/v1` handler skeleton into the runtime and lands the routing
table + rate limiter the rest of the DHT machinery will build on.

What's in:

- `crates/node/src/dht/routing.rs` — k-bucket routing table at K=20,
  256 buckets keyed by XOR distance to the node's own NodeId (ADR 022
  §Routing Table). LRU eviction on bucket overflow; the
  ping-then-evict variant is deferred until the FindNode driver lands
  in PR 4 of #320. Self-id inserts are no-ops so iterative lookup
  never terminates on the local table.
- `crates/node/src/dht/rate_limit.rs` — three-layer token-bucket
  limiter (per-peer NodeId, per-IP, global) with cheapest-first
  short-circuit per ADR 022 §DHT Rate Limiting. Trusted-IP exemption
  bypasses the per-IP layer only; per-peer and global still apply.
  Each layer can be independently disabled (rate == 0 with burst ==
  0). Backed by `governor` like `ConnectionLimiter`.
- `crates/node/src/handlers/dht.rs` — `ProtocolHandler` implementing
  the full ADR 013 error-code mapping and the ADR 022 admission
  order: dispatch limiter → per-stream rate limit → routing-table
  refresh → dispatch. `FindNode` is fully implemented; `Store` and
  `FindValue` return safe placeholders (StoreAck{accepted: false},
  empty providers) so the wire surface is reachable from upgraded
  peers. Real handling for those variants lands in PR 3 of #320.
- `crates/common/src/config/{types,resolved}.rs` and resolver —
  `DhtConfig` / `ResolvedDht` with per-layer rate/burst pairs and a
  parsed trusted-IPs set. Defaults match ADR 022 (20/100/1000 req/s,
  40/200/2000 burst). Pairing rules mirror the existing
  `security.per_source_*` resolver: rate>0 with burst=0 is rejected
  at config time.
- `decdn_dht_rate_limit_rejected_{per_peer,per_ip,global}_total`
  metrics. ADR 022 §Observability specifies a single labeled counter,
  but `iroh_metrics::MetricsGroup` doesn't support per-field labels;
  we follow the existing convention (cf. `dispatch_rejected_*`) and
  surface one counter per layer. Operators with the ADR-022 alert
  form do a Prometheus `sum()` to recover the rolled-up rate.
- Runtime registers `cdn/dht/v1` on the iroh router alongside
  `cdn/probe/v1` and `iroh-gossip`.
- Loopback integration test (`tests/dht_loopback.rs`) covering a
  seeded routing table responding to FindNode plus the FindValue
  placeholder shape (pinned now so a future regression while the
  record store lands can't pass under the same loopback name).

What's deferred (per the issue-320 plan):

- Record store + Store/FindValue admission, per-publisher quota,
  receiver-anchored TTL, iterative lookup — PR 3.
- Republish scheduler, bootstrap, on-chain origin fallback — PR 4.
- BatchStore variants and prefetch — follow-up issues.

Refs #320.

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

Addresses PR #643 review feedback (gemini-code-assist + Copilot):

- **HIGH: drop attacker-controlled routing-table refresh.**
  `handle_find_node` was calling `note_peer_seen(req.requester)` on the
  unauthenticated wire field, letting an authenticated peer A send
  `FindNode { requester: B }` to inject any NodeId B into the routing
  table without owning the matching key (routing-table poisoning). The
  authenticated peer NodeId from the QUIC handshake is already
  refreshed once per admitted request in `serve()`, which is the only
  honest signal we have. Removed the second `note_peer_seen` call;
  added a regression test that confirms the attacker-supplied
  `req.requester` is NOT inserted while the authenticated client IS.
- **Replace `unreachable_size_mismatch` with `std::array::from_fn`.**
  The previous helper recursed indefinitely on its own error path —
  the recursion is unreachable by construction but a future
  regression would stack-overflow instead of producing a clear
  diagnostic. `std::array::from_fn` builds the fixed-size array in
  place so the validation step (and the recursion) go away entirely.
- **Fix inverted bucket-index comment.** The code returns bucket 255
  for max distance and bucket 0 for the closest peers; the comment
  said the opposite. Rewrote it (and renamed the two related tests
  `bucket_index_max_distance_is_top_bucket` /
  `bucket_index_min_nonzero_is_bucket_zero`) to match the
  implementation.
- **Re-evaluate `peer_ip` per stream.** Iroh paths can switch over a
  connection's lifetime (relay-only initially, then a direct UDP path
  becomes selected). Capturing the IP once at accept would permanently
  disable the per-IP rate-limit layer for any connection that started
  relay-only. Moved the `peer_ip(&conn)` call inside the per-stream
  loop so a relay→direct switch engages the layer for subsequent
  streams.
- **Align `rate_limit.rs` doc references with the actual emitted
  metric names** (`decdn_dht_rate_limit_rejected_{per_peer,per_ip,
  global}_total` — one Counter per layer, since the metrics backend
  doesn't support per-field labels).
- **`sort_unstable_by_key` in `RoutingTable::closest`.** Computes
  `xor_distance` once per element instead of twice per pairwise
  comparison; lower asymptotic XOR cost on fully-populated tables.
- **`BatchStore`/`BatchStoreAck` dispatch arms.** PR-1 fix
  re-introduced these enum variants at their ADR-canonical
  discriminants; the handler now answers `BatchStore` with a
  per-hash `accepted: false` ack so publishers fall back to per-hash
  `Store` per ADR 022 §Schema Evolution. Handler-side admission
  (two-stage rate limit, holder check, per-hash quota) is the
  follow-up issue tracking `BatchStore` proper.

Deferred to a follow-up issue (raised in PR #643 review):

- Per-IP / per-peer keyed-rate-limiter keyspace cap + periodic GC
  (mirror of `dispatch::ConnectionLimiter::max_tracked_sources` +
  `retain_recent`). Same DoS shape as the dispatch limiter; meaningful
  fix but a self-contained chunk of work with its own runtime wiring.

Refs #320, addresses #643 review.

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

Round 2 of PR #643 review (after the prior poisoning/recursion/comment
round). Addresses findings from five specialized review agents
(code-reviewer, pr-test-analyzer, silent-failure-hunter,
type-design-analyzer, comment-analyzer).

CRITICAL

- **BatchStore now closes the stream with `APP_ERR_UNSUPPORTED_MESSAGE`
  instead of replying with an all-`false` `BatchStoreAck`.** ADR 022
  §STORE Flow line 138 + §Schema Evolution specify that the unsupported
  signal MUST be stream-close-without-ack — an all-`false` ack reads to
  a conformant publisher as "your batch was processed, every hash
  rejected" and triggers NO fallback to per-hash `Store`. The fix is
  structural: `read_dht_request` now narrows the wire `DhtMessage` to a
  new `DhtServerRequest` enum (`FindNode` / `FindValue` / `Store`),
  rejecting `BatchStore` and response-on-server-stream variants up
  front. `dispatch` is then exhaustive over the active set without a
  panic / echo fallback for impossible cases. Loopback test
  `batch_store_returns_unsupported_code_not_ack` guards the contract.

- **`dht.*` wired into the SIGHUP reload pipeline.** `FileSectionSnapshot`
  gains a `dht` field and `log_ignored_other_sections` emits the
  "requires restart" warning when `[dht]` changes. Previously an
  operator who edited `dht.rate_limit.trusted_ips` and SIGHUPed got no
  feedback that the change wasn't applied.

- **`[dht.rate_limit]` is now nested under `[dht]` per ADR 022 §Trusted-IP
  exemption.** Operator key path is `dht.rate_limit.trusted_ips` (matching
  the ADR), not the flat `dht.trusted_ips` from the prior commit. All
  six rate/burst knobs moved with it.

IMPORTANT

- **`DhtServerRequest` narrowing enum replaces `dispatch`'s
  match-all-fallback** (code-reviewer #5, silent-failure-hunter
  Critical #2). The previous arm echoed an empty `FindNodeResponse` if
  reached — dead code that masked a real protocol violation if the
  filter ever drifted. Removed entirely.

- **`decdn_dht_requests_failed_total` counter added.** Bumps when
  `handle_one` returns Err after rate-limit admission (frame decode,
  encode, write, finish, read timeout, etc). Operator running at
  default `RUST_LOG=info` no longer needs to enable debug logs to see
  "DHT requests are failing" (silent-failure-hunter Critical #1).

- **ADR 013 error-code roundtrip loopback tests** for
  `APP_ERR_MALFORMED_MESSAGE`, `APP_ERR_UNSUPPORTED_MESSAGE` (response
  on server stream + `BatchStore`), and `APP_ERR_RATE_LIMITED`
  (pr-test-analyzer Critical #1, #3). `APP_ERR_MESSAGE_TOO_LARGE`
  needs a low-level varint writer to exercise; noted in a comment.

- **`closest_returns_distance_sorted_results` strengthened** to assert
  the full vector is monotonically non-decreasing by XOR distance,
  not just endpoints — catches "first and last correct, middle
  scrambled" regressions (pr-test-analyzer #4).

- **Stale / misleading comments fixed** (comment-analyzer #2, #6, #7):
  routing.rs no longer claims a non-existent "follow-up PR" lands
  ping-then-evict; handler module docs now correctly describe the
  BatchStore stream-close behavior; the dispatch comment reflects the
  new narrowing-enum shape.

DEFERRED (genuine but out of scope for this PR slice)

- `NodeId` newtype (type-design-analyzer single biggest recommendation,
  touches the wire format + multiple crates — file as standalone
  follow-up).
- Per-IP / per-peer keyspace bound (already issue #645).
- Read-timeout app code, `FrameError::Io` mapping nuances (silent-failure-hunter
  MEDIUM, match existing probe handler precedent).

Refs #320, addresses PR #643 multi-agent review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@thiras
thiras force-pushed the dht-handler-routing branch from cd6e074 to 6f863ce Compare May 21, 2026 17:34
@thiras
thiras requested a review from alpergundogdu May 21, 2026 21:21
alpergundogdu pushed a commit that referenced this pull request May 22, 2026
…642)

* feat(protocol): add cdn/dht/v1 wire types (ADR 022)

Introduces `DhtMessage` and the six request/response structs for the
Kademlia content DHT specified in ADR 022 §Message Types:
`FindValue{Request,Response}`, `Store{Request,Ack}`,
`FindNode{Request,Response}`. The variant order is frozen per
ADR 013 §Protocol Enums and pinned by per-variant discriminant tests so
a reorder fails CI loudly rather than breaking wire compatibility
silently.

Authentication on `StoreRequest` is by QUIC-bound NodeId equality, not
a per-record signature — this depends on records being pushed directly
by the holder and never relayed peer-to-peer. The module docs flag the
invariant so a future relay scheme reintroduces the signature plus
in-scope sender timestamp together (ADR 015 §Replay Safety Analysis).

`BatchStoreRequest` / `BatchStoreAck` are deferred to a follow-up
issue. ADR 022 specifies them as a bandwidth optimization with a
per-hash fallback only useful at C ≥ 10k cached blobs; when added they
append after `FindNodeResponse` so existing discriminants are
preserved.

Wire-cap constants (`MAX_PROVIDERS_PER_HASH = 50`,
`MAX_CLOSER_NODES = 20`) bound the max-size `FindValueResponse` under
the ~2.3 KB ceiling from ADR 022 §DHT Bandwidth Analysis; the upper
bound is asserted by a test so future field additions can't drift past
it unnoticed.

Refs #320.

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

* fix(protocol): bound Vec wire fields and reorder DhtMessage to ADR-canonical

Addresses PR #642 review feedback (gemini-code-assist + Copilot):

- Add `#[serde(deserialize_with = ...)]` field-level hooks enforcing
  `MAX_PROVIDERS_PER_HASH`, `MAX_CLOSER_NODES`, and `MAX_BATCH_STORE_HASHES`
  at the wire boundary. Pattern mirrors `ProbeResponseBody::rate_per_mb`:
  postcard's positional layout stays derive-driven (no mirror struct, no
  manual `Deserialize` impl), and oversize Vec fields now fail decode
  rather than allocating an attacker-chosen size up to the 16 MiB framing
  ceiling.
- Reorder `DhtMessage` variants to match ADR 022 §Message Types: the ADR
  lists `BatchStore`/`BatchStoreAck` at positions 4/5 and
  `FindNode`/`FindNodeResponse` at 6/7. The original PR put `FindNode` at
  4/5; with postcard's sequential discriminant indexing this would have
  forced a future wire-breaking shuffle once `BatchStore` lands. Define
  the `BatchStore` wire types now (no handler) so the production ordering
  matches the ADR and the future BatchStore PR is a pure handler addition.
- Replace the inner-struct-only size guard with a framed-size assertion
  that includes the `DhtMessage` enum discriminant byte AND the
  `write_frame` length-prefix varint, so the ~2.3 KB ADR 022 wire ceiling
  can't drift via discriminant or framing-layer changes.
- New tests: discriminant pinning for `BatchStore` (4) / `BatchStoreAck`
  (5) / `FindNode` (6) / `FindNodeResponse` (7); decode-time rejection
  for oversize `providers`, `closer_nodes`, `BatchStore.hashes`, and
  `BatchStoreAck.results`; exact-MAX boundary acceptance.

Refs #320, addresses #642 review.

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

* test(protocol): add lower bound + align BatchStore module doc

Round 2 of PR #642 review (pr-test-analyzer + comment-analyzer).

- `find_value_response_max_framed_size_under_ceiling` previously had
  only `framed_len <= 2_300`. A regression that dropped `providers` or
  `closer_nodes` from the wire shape would shrink the encoded size
  well below the ADR's modeled payload (~2.27 KB) and the test would
  silently pass. Add `framed_len > 2_000` so an accidental field
  removal fails the test loudly.

- Module-level doc for `BatchStore` previously said the runtime "treats
  inbound BatchStore frames as unsupported until then." After the
  PR-#643 fix the handler explicitly closes the stream with
  `APP_ERR_UNSUPPORTED_MESSAGE` (the stream-close-without-ack signal
  ADR 022 §Schema Evolution requires); the doc now reflects the
  precise wire behaviour and cites the matching ADR section.

Refs #320, addresses PR #642 multi-agent review.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Base automatically changed from dht-protocol-types to main May 22, 2026 09:09
@github-actions

Copy link
Copy Markdown

Coverage report

Total: 90.21% (was 90.44%, ▼ 0.24%) — 19108/21182 lines

File Coverage Lines Δ
crates/common/src/config/mod.rs 96.06% 4409/4590 ▼ 0.32%
crates/common/src/config/resolved.rs 100.00% 11/11 new
crates/node/src/dht/rate_limit.rs 100.00% 194/194 new
crates/node/src/dht/routing.rs 96.08% 245/255 new
crates/node/src/handlers/dht.rs 67.26% 150/223 new
crates/node/src/metrics.rs 83.94% 366/436 ▲ +0.45%
crates/node/src/runtime/mod.rs 51.29% 438/854 ▼ 1.05%
crates/node/src/runtime/reload.rs 95.47% 1390/1456 ▼ 0.51%
History
Commit Total Δ vs base
6f863ce (HEAD) 90.21% ▼ 0.24%

@alpergundogdu
alpergundogdu merged commit 6aad5cc into main May 22, 2026
31 checks passed
@alpergundogdu
alpergundogdu deleted the dht-handler-routing branch May 22, 2026 09:13
thiras added a commit that referenced this pull request May 22, 2026
Resolve conflicts from #643 (PR 2/4) landing on main while this branch
(PR 3/4) had its own copy of the same review-fix history:

- `crates/node/src/dht/mod.rs`, `crates/node/src/handlers/dht.rs`,
  `crates/node/tests/dht_loopback.rs` — keep HEAD; PR 3's real
  Store/FindValue admission replaces PR 2's placeholder responses.
- `crates/common/src/config/{mod,resolved,types}.rs` — keep HEAD's
  `dht.static_active_nodes` config surface; main has no competing
  changes in these spans.
- `crates/node/src/metrics.rs` — keep HEAD's four new
  `dht_store_*` counters.
- `crates/node/src/runtime/mod.rs` — combine: HEAD's record-store +
  staker-set wiring AND `record_store_gc_stop_tx` signal, plus main's
  `admin_stop_order` drain ordering from #604.

Verified: cargo build, cargo clippy --all-targets -D warnings,
cargo fmt --check, cargo nextest run (1068/1068 pass).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
thiras added a commit that referenced this pull request May 22, 2026
… of #320) (#646)

* feat(protocol): add cdn/dht/v1 wire types (ADR 022)

Introduces `DhtMessage` and the six request/response structs for the
Kademlia content DHT specified in ADR 022 §Message Types:
`FindValue{Request,Response}`, `Store{Request,Ack}`,
`FindNode{Request,Response}`. The variant order is frozen per
ADR 013 §Protocol Enums and pinned by per-variant discriminant tests so
a reorder fails CI loudly rather than breaking wire compatibility
silently.

Authentication on `StoreRequest` is by QUIC-bound NodeId equality, not
a per-record signature — this depends on records being pushed directly
by the holder and never relayed peer-to-peer. The module docs flag the
invariant so a future relay scheme reintroduces the signature plus
in-scope sender timestamp together (ADR 015 §Replay Safety Analysis).

`BatchStoreRequest` / `BatchStoreAck` are deferred to a follow-up
issue. ADR 022 specifies them as a bandwidth optimization with a
per-hash fallback only useful at C ≥ 10k cached blobs; when added they
append after `FindNodeResponse` so existing discriminants are
preserved.

Wire-cap constants (`MAX_PROVIDERS_PER_HASH = 50`,
`MAX_CLOSER_NODES = 20`) bound the max-size `FindValueResponse` under
the ~2.3 KB ceiling from ADR 022 §DHT Bandwidth Analysis; the upper
bound is asserted by a test so future field additions can't drift past
it unnoticed.

Refs #320.

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

* fix(protocol): bound Vec wire fields and reorder DhtMessage to ADR-canonical

Addresses PR #642 review feedback (gemini-code-assist + Copilot):

- Add `#[serde(deserialize_with = ...)]` field-level hooks enforcing
  `MAX_PROVIDERS_PER_HASH`, `MAX_CLOSER_NODES`, and `MAX_BATCH_STORE_HASHES`
  at the wire boundary. Pattern mirrors `ProbeResponseBody::rate_per_mb`:
  postcard's positional layout stays derive-driven (no mirror struct, no
  manual `Deserialize` impl), and oversize Vec fields now fail decode
  rather than allocating an attacker-chosen size up to the 16 MiB framing
  ceiling.
- Reorder `DhtMessage` variants to match ADR 022 §Message Types: the ADR
  lists `BatchStore`/`BatchStoreAck` at positions 4/5 and
  `FindNode`/`FindNodeResponse` at 6/7. The original PR put `FindNode` at
  4/5; with postcard's sequential discriminant indexing this would have
  forced a future wire-breaking shuffle once `BatchStore` lands. Define
  the `BatchStore` wire types now (no handler) so the production ordering
  matches the ADR and the future BatchStore PR is a pure handler addition.
- Replace the inner-struct-only size guard with a framed-size assertion
  that includes the `DhtMessage` enum discriminant byte AND the
  `write_frame` length-prefix varint, so the ~2.3 KB ADR 022 wire ceiling
  can't drift via discriminant or framing-layer changes.
- New tests: discriminant pinning for `BatchStore` (4) / `BatchStoreAck`
  (5) / `FindNode` (6) / `FindNodeResponse` (7); decode-time rejection
  for oversize `providers`, `closer_nodes`, `BatchStore.hashes`, and
  `BatchStoreAck.results`; exact-MAX boundary acceptance.

Refs #320, addresses #642 review.

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

* test(protocol): add lower bound + align BatchStore module doc

Round 2 of PR #642 review (pr-test-analyzer + comment-analyzer).

- `find_value_response_max_framed_size_under_ceiling` previously had
  only `framed_len <= 2_300`. A regression that dropped `providers` or
  `closer_nodes` from the wire shape would shrink the encoded size
  well below the ADR's modeled payload (~2.27 KB) and the test would
  silently pass. Add `framed_len > 2_000` so an accidental field
  removal fails the test loudly.

- Module-level doc for `BatchStore` previously said the runtime "treats
  inbound BatchStore frames as unsupported until then." After the
  PR-#643 fix the handler explicitly closes the stream with
  `APP_ERR_UNSUPPORTED_MESSAGE` (the stream-close-without-ack signal
  ADR 022 §Schema Evolution requires); the doc now reflects the
  precise wire behaviour and cites the matching ADR section.

Refs #320, addresses PR #642 multi-agent review.

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

* feat(node): add cdn/dht/v1 handler, routing table, rate limiter (ADR 022)

PR 2 of 4 for #320 (Kademlia content discovery). Wires the
`cdn/dht/v1` handler skeleton into the runtime and lands the routing
table + rate limiter the rest of the DHT machinery will build on.

What's in:

- `crates/node/src/dht/routing.rs` — k-bucket routing table at K=20,
  256 buckets keyed by XOR distance to the node's own NodeId (ADR 022
  §Routing Table). LRU eviction on bucket overflow; the
  ping-then-evict variant is deferred until the FindNode driver lands
  in PR 4 of #320. Self-id inserts are no-ops so iterative lookup
  never terminates on the local table.
- `crates/node/src/dht/rate_limit.rs` — three-layer token-bucket
  limiter (per-peer NodeId, per-IP, global) with cheapest-first
  short-circuit per ADR 022 §DHT Rate Limiting. Trusted-IP exemption
  bypasses the per-IP layer only; per-peer and global still apply.
  Each layer can be independently disabled (rate == 0 with burst ==
  0). Backed by `governor` like `ConnectionLimiter`.
- `crates/node/src/handlers/dht.rs` — `ProtocolHandler` implementing
  the full ADR 013 error-code mapping and the ADR 022 admission
  order: dispatch limiter → per-stream rate limit → routing-table
  refresh → dispatch. `FindNode` is fully implemented; `Store` and
  `FindValue` return safe placeholders (StoreAck{accepted: false},
  empty providers) so the wire surface is reachable from upgraded
  peers. Real handling for those variants lands in PR 3 of #320.
- `crates/common/src/config/{types,resolved}.rs` and resolver —
  `DhtConfig` / `ResolvedDht` with per-layer rate/burst pairs and a
  parsed trusted-IPs set. Defaults match ADR 022 (20/100/1000 req/s,
  40/200/2000 burst). Pairing rules mirror the existing
  `security.per_source_*` resolver: rate>0 with burst=0 is rejected
  at config time.
- `decdn_dht_rate_limit_rejected_{per_peer,per_ip,global}_total`
  metrics. ADR 022 §Observability specifies a single labeled counter,
  but `iroh_metrics::MetricsGroup` doesn't support per-field labels;
  we follow the existing convention (cf. `dispatch_rejected_*`) and
  surface one counter per layer. Operators with the ADR-022 alert
  form do a Prometheus `sum()` to recover the rolled-up rate.
- Runtime registers `cdn/dht/v1` on the iroh router alongside
  `cdn/probe/v1` and `iroh-gossip`.
- Loopback integration test (`tests/dht_loopback.rs`) covering a
  seeded routing table responding to FindNode plus the FindValue
  placeholder shape (pinned now so a future regression while the
  record store lands can't pass under the same loopback name).

What's deferred (per the issue-320 plan):

- Record store + Store/FindValue admission, per-publisher quota,
  receiver-anchored TTL, iterative lookup — PR 3.
- Republish scheduler, bootstrap, on-chain origin fallback — PR 4.
- BatchStore variants and prefetch — follow-up issues.

Refs #320.

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

* fix(node): address PR #643 review — routing-table poisoning, recursion, docs

Addresses PR #643 review feedback (gemini-code-assist + Copilot):

- **HIGH: drop attacker-controlled routing-table refresh.**
  `handle_find_node` was calling `note_peer_seen(req.requester)` on the
  unauthenticated wire field, letting an authenticated peer A send
  `FindNode { requester: B }` to inject any NodeId B into the routing
  table without owning the matching key (routing-table poisoning). The
  authenticated peer NodeId from the QUIC handshake is already
  refreshed once per admitted request in `serve()`, which is the only
  honest signal we have. Removed the second `note_peer_seen` call;
  added a regression test that confirms the attacker-supplied
  `req.requester` is NOT inserted while the authenticated client IS.
- **Replace `unreachable_size_mismatch` with `std::array::from_fn`.**
  The previous helper recursed indefinitely on its own error path —
  the recursion is unreachable by construction but a future
  regression would stack-overflow instead of producing a clear
  diagnostic. `std::array::from_fn` builds the fixed-size array in
  place so the validation step (and the recursion) go away entirely.
- **Fix inverted bucket-index comment.** The code returns bucket 255
  for max distance and bucket 0 for the closest peers; the comment
  said the opposite. Rewrote it (and renamed the two related tests
  `bucket_index_max_distance_is_top_bucket` /
  `bucket_index_min_nonzero_is_bucket_zero`) to match the
  implementation.
- **Re-evaluate `peer_ip` per stream.** Iroh paths can switch over a
  connection's lifetime (relay-only initially, then a direct UDP path
  becomes selected). Capturing the IP once at accept would permanently
  disable the per-IP rate-limit layer for any connection that started
  relay-only. Moved the `peer_ip(&conn)` call inside the per-stream
  loop so a relay→direct switch engages the layer for subsequent
  streams.
- **Align `rate_limit.rs` doc references with the actual emitted
  metric names** (`decdn_dht_rate_limit_rejected_{per_peer,per_ip,
  global}_total` — one Counter per layer, since the metrics backend
  doesn't support per-field labels).
- **`sort_unstable_by_key` in `RoutingTable::closest`.** Computes
  `xor_distance` once per element instead of twice per pairwise
  comparison; lower asymptotic XOR cost on fully-populated tables.
- **`BatchStore`/`BatchStoreAck` dispatch arms.** PR-1 fix
  re-introduced these enum variants at their ADR-canonical
  discriminants; the handler now answers `BatchStore` with a
  per-hash `accepted: false` ack so publishers fall back to per-hash
  `Store` per ADR 022 §Schema Evolution. Handler-side admission
  (two-stage rate limit, holder check, per-hash quota) is the
  follow-up issue tracking `BatchStore` proper.

Deferred to a follow-up issue (raised in PR #643 review):

- Per-IP / per-peer keyed-rate-limiter keyspace cap + periodic GC
  (mirror of `dispatch::ConnectionLimiter::max_tracked_sources` +
  `retain_recent`). Same DoS shape as the dispatch limiter; meaningful
  fix but a self-contained chunk of work with its own runtime wiring.

Refs #320, addresses #643 review.

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

* fix(node): apply consolidated review fixes from PR #643 multi-agent review

Round 2 of PR #643 review (after the prior poisoning/recursion/comment
round). Addresses findings from five specialized review agents
(code-reviewer, pr-test-analyzer, silent-failure-hunter,
type-design-analyzer, comment-analyzer).

CRITICAL

- **BatchStore now closes the stream with `APP_ERR_UNSUPPORTED_MESSAGE`
  instead of replying with an all-`false` `BatchStoreAck`.** ADR 022
  §STORE Flow line 138 + §Schema Evolution specify that the unsupported
  signal MUST be stream-close-without-ack — an all-`false` ack reads to
  a conformant publisher as "your batch was processed, every hash
  rejected" and triggers NO fallback to per-hash `Store`. The fix is
  structural: `read_dht_request` now narrows the wire `DhtMessage` to a
  new `DhtServerRequest` enum (`FindNode` / `FindValue` / `Store`),
  rejecting `BatchStore` and response-on-server-stream variants up
  front. `dispatch` is then exhaustive over the active set without a
  panic / echo fallback for impossible cases. Loopback test
  `batch_store_returns_unsupported_code_not_ack` guards the contract.

- **`dht.*` wired into the SIGHUP reload pipeline.** `FileSectionSnapshot`
  gains a `dht` field and `log_ignored_other_sections` emits the
  "requires restart" warning when `[dht]` changes. Previously an
  operator who edited `dht.rate_limit.trusted_ips` and SIGHUPed got no
  feedback that the change wasn't applied.

- **`[dht.rate_limit]` is now nested under `[dht]` per ADR 022 §Trusted-IP
  exemption.** Operator key path is `dht.rate_limit.trusted_ips` (matching
  the ADR), not the flat `dht.trusted_ips` from the prior commit. All
  six rate/burst knobs moved with it.

IMPORTANT

- **`DhtServerRequest` narrowing enum replaces `dispatch`'s
  match-all-fallback** (code-reviewer #5, silent-failure-hunter
  Critical #2). The previous arm echoed an empty `FindNodeResponse` if
  reached — dead code that masked a real protocol violation if the
  filter ever drifted. Removed entirely.

- **`decdn_dht_requests_failed_total` counter added.** Bumps when
  `handle_one` returns Err after rate-limit admission (frame decode,
  encode, write, finish, read timeout, etc). Operator running at
  default `RUST_LOG=info` no longer needs to enable debug logs to see
  "DHT requests are failing" (silent-failure-hunter Critical #1).

- **ADR 013 error-code roundtrip loopback tests** for
  `APP_ERR_MALFORMED_MESSAGE`, `APP_ERR_UNSUPPORTED_MESSAGE` (response
  on server stream + `BatchStore`), and `APP_ERR_RATE_LIMITED`
  (pr-test-analyzer Critical #1, #3). `APP_ERR_MESSAGE_TOO_LARGE`
  needs a low-level varint writer to exercise; noted in a comment.

- **`closest_returns_distance_sorted_results` strengthened** to assert
  the full vector is monotonically non-decreasing by XOR distance,
  not just endpoints — catches "first and last correct, middle
  scrambled" regressions (pr-test-analyzer #4).

- **Stale / misleading comments fixed** (comment-analyzer #2, #6, #7):
  routing.rs no longer claims a non-existent "follow-up PR" lands
  ping-then-evict; handler module docs now correctly describe the
  BatchStore stream-close behavior; the dispatch comment reflects the
  new narrowing-enum shape.

DEFERRED (genuine but out of scope for this PR slice)

- `NodeId` newtype (type-design-analyzer single biggest recommendation,
  touches the wire format + multiple crates — file as standalone
  follow-up).
- Per-IP / per-peer keyspace bound (already issue #645).
- Read-timeout app code, `FrameError::Io` mapping nuances (silent-failure-hunter
  MEDIUM, match existing probe handler precedent).

Refs #320, addresses PR #643 multi-agent review.

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

* feat(node,cache): record store + Store/FindValue + cache hook (ADR 022)

PR 3 of 4 for #320 (Kademlia content discovery). Replaces the
PR-2 placeholder responses with the spec-conformant admission pipeline
and exposes the cache → DHT republish hook that PR 4 will consume.

What's in:

- `crates/node/src/dht/records.rs` — receiver-side `RecordStore`
  enforcing the ADR 022 §Content Records and TTL admission rules:
  * Per-publisher cap of 200 records — hard reject above cap.
  * Global cap of 100k records — global LRU eviction when over cap
    and the inserting publisher is below their per-publisher cap.
  * Per-hash provider cap of 50 — evict oldest holder for that hash.
  * Receiver-anchored TTL of 1 hour; refresh-in-place on re-publish
    (no double-count against the publisher quota).
  * Periodic GC sweep + on-demand expiry scrub on every providers
    lookup.
- `crates/node/src/dht/staker_set.rs` — `StakerSet` trait + file-
  config-driven `ConfigStakerSet`. The chain-backed `ChainStakerSet`
  that reads `StakingRegistry.getActiveNodes()` lives in the on-chain
  origin-directory follow-up issue; same trait, drop-in swap.
- `handlers/dht.rs` — real `Store` admission (holder == authenticated
  NodeId → active-staker filter → record-store insert) and real
  `FindValue` (record-store providers + routing-table closer_nodes).
  Per ADR 022 §Lookup integrity the requester-side filters (XOR-
  distance check, active-staker filter, negative-probe-cache,
  randomisation) belong on the iterative-lookup side and land with
  PR 4 of #320 — the responder is intentionally minimal here.
- `crates/cache/src/engine.rs` — `CacheEngine::subscribe_inserts()`
  broadcast hook. Emits the committed hash from the `pull_through`
  success arm (the single convergence point for streaming + buffered
  commits); the local-store-hit short-circuit deliberately does NOT
  emit (a hit doesn't start a new TTL cycle).
- `dht.static_active_nodes` config field — operator-supplied 64-char
  hex `NodeId` list parsed via the existing `parse_node_id_hex`
  helper; malformed entries fail config resolution.

What's deferred (per the issue-320 plan):

- Iterative requester-side `FindValue` lookup (α=3 parallelism, three
  requester-side filters from ADR 022 §Lookup integrity, provider-set
  randomisation) — PR 4 of #320, where it pairs naturally with the
  bootstrap and republish-scheduler call sites.
- Republish scheduler that consumes `subscribe_inserts` and pushes
  `Store` to the K+3 closest peers with jittered (30–50 min) cadence —
  PR 4 of #320.
- Subscribe-to-staker-changes (broadcast channel on `StakerSet`) — the
  current `ConfigStakerSet` set is immutable post-startup, so the
  subscriber surface doesn't pay rent yet.

Tests:

- 11 new `RecordStore` unit tests covering insert / refresh / quota /
  global LRU / per-hash cap / TTL / GC.
- 4 new `ConfigStakerSet` tests.
- 2 new `CacheEngine::subscribe_inserts` tests: emit on pull-through
  success, NO emit on cache hit.
- 3 new DHT loopback tests under `store_admission`: round-trip for a
  staked publisher; rejection for a non-staked publisher; rejection
  when `holder != authenticated NodeId` (lying-`holder` attack).

Refs #320.

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

* fix(node,common): address PR #646 multi-bot review (TTL drift, eviction, GC)

Addresses PR #646 review (Copilot + gemini-code-assist):

Correctness:

- **TTL no longer drifts with insert volume.** Previously
  `monotonic_tail` was added directly into `receive_us` and propagated
  into `expiry_us`, so 1M unrelated inserts shifted a record's expiry
  forward by ~1s; 1B inserts ~17 min — material against the 1-hour
  TTL. Per ADR 022 §Content Records and TTL line 122,
  `expiry_us = receive_us + ttl_us` is the contract. Replaced with a
  separate `sequence` field that's used only as the second component
  of the `global_lru` key, never mixed into time-domain values.
  Regression test: a record inserted at wall-clock 500 with
  `ttl_us = 1_000` has `expiry_us == 1_500` exact after 10k unrelated
  prior inserts.
- **No more "two evictions for one insert".** The prior order was
  "global LRU first, then per-hash cap" — when both were full this
  evicted an unrelated record AND a per-hash holder for one insert,
  leaving the store under-full by one and dropping an unrelated hash's
  oldest holder. Per-hash cap now fires first; the global LRU is
  skipped when the per-hash eviction already nets the store out at
  the same global count. Regression test pins both invariants.
- **Periodic record-store GC task added.** Without it, expired records
  accumulated against the per-publisher and global caps until any
  query for the specific hash forced a scrub. A publisher who put
  one record and stopped requesting it would eventually fill its
  200-record quota with stale entries and have every future `Store`
  rejected. The task runs on the existing `DISPATCH_GC_INTERVAL` (60s)
  and shuts down via the same `oneshot` shape as `run_dispatch_gc`.
- **`RecordStore::gc` now `O(expired × log N)` instead of `O(N)`.**
  Since `ttl_us` is constant, `global_lru` (ordered by `receive_us`)
  is also ordered by `expiry_us` — pop the front until non-expired
  and stop. gemini-code-assist's exact suggestion.

Cleanup:

- `parse_node_id_hex`'s error message is now field-agnostic ("must be
  64 hex chars, got X"). Callers (`gossip.allowlist[idx]` and
  `dht.static_active_nodes`) already wrap with the field path; the
  helper no longer hardcodes "gossip.allowlist".
- `AllStaked` test stub: `len()` now returns 0 to stay consistent
  with the empty `active_nodes()` (was `usize::MAX`, an inconsistency
  the bot flagged). Doc on the helper now spells out that it's not
  enumerable — tests that need a concrete set use `ConfigStakerSet`.

Tests:

- 2 new `RecordStore` unit tests pinning the TTL-no-drift and
  no-double-eviction contracts.
- Existing 12 record-store + 4 staker-set + 2 cache subscribe + 10
  DHT loopback tests still green (998/998 workspace).

Refs #320, addresses PR #646 review.

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

* fix(node,cache): apply PR #646 round-3 review (correctness + comments + tests)

Five-agent review on PR #646 surfaced 4 correctness issues, 6 comment
factual errors, and several test gaps.

Correctness:

- **Empty staker-set startup warning** — `dht.static_active_nodes` missing
  silently rejects every `Store` (ADR 022 line 140). Runtime now logs
  `warn!` at startup when the set is empty so the failure mode is one
  high-signal line, not silent per-request debug rejections.
- **`now_us()` clock-broken log** — `SystemTime` before-UNIX-EPOCH used
  to silently fall back to `receive_us=0`, collapsing every record to
  the same `expiry_us` and triggering mass eviction at the 1-hour
  mark when the clock recovered. Now logs `error!` once per affected
  insert so the operator sees the host-clock fault. Fallback keeps
  the store functional in the degraded state.
- **Refresh corruption-path** — `entries.get_mut(idx)` returning `None`
  after `position()` returned `Some(idx)` used to surface as
  `InsertOutcome::Refreshed` → `accepted: true` on the wire,
  confirming a write that never happened. Now returns
  `RejectedQuotaExceeded` and logs `error!` with full context.
- **Store-rejection metrics** — three new counters
  (`decdn_dht_store_rejected_holder_mismatch_total`,
  `decdn_dht_store_rejected_non_staked_total`,
  `decdn_dht_store_rejected_quota_total`) plus
  `decdn_dht_store_accepted_total`. Lying-holder + non-staked +
  quota-exhaustion are operator-actionable security/abuse signals
  that previously needed `RUST_LOG=debug` to see.

Comment factual errors:

- `cache/engine.rs:765` line citation 124 → 126 (the quoted "When a
  node caches blob H" sits at line 126, not the section header at 124).
- `handlers/dht.rs:527` "PR-2-of-#320 slice" → "this slice" (the file
  is now PR 3).
- `handlers/dht.rs:530` "§Schema Evolution line 138" was misattributed;
  line 138 is in §STORE Flow. Now reads "§STORE Flow line 138 +
  §Schema Evolution".
- `handlers/dht.rs:301` dispatch by-value comment referenced
  `FindValueResponse` (the response shape); the function takes
  request variants. Now says "request variants whose payloads include
  Vec fields (e.g. a `BatchStoreRequest::hashes` once the handler-side
  admission lands)".
- `records.rs:451` test comment claimed "receive_us is monotonic-
  counter-mixed"; that was the pre-fix behaviour. Now asserts exact
  equality with `receive_us = 200` + `expiry_us = 200 + ttl_us`.
- `records.rs:587/600` test internally cited 10k AND 100k AND 1M
  unrelated inserts; only 10k is real. All references now match.

Tests:

- `default_config_matches_adr_022` pins the four `RecordStoreConfig`
  defaults (200 / 100k / 50 / 1h) against the ADR 022 §Content Records
  and TTL table. Without it, a regression that halved any value would
  pass the entire existing test suite (all use `small_cfg()`).
- `publisher_quota_beats_global_lru` regression-pins the rule that a
  publisher at their per-publisher cap hard-rejects WITHOUT touching
  the global LRU — a future refactor that swapped check order would
  let quota-exceeded publishers displace other publishers' records.
- `run_record_store_gc_exits_promptly_on_shutdown` mirrors the
  `run_dispatch_gc_exits_promptly_on_shutdown` precedent: a regression
  that reorders the `tokio::select!` arms or drops `biased` would
  silently extend `SHUTDOWN_DEADLINE` by up to 60s.

Pushed back / filed for follow-up:

- Extracting `add_entry`/`remove_entry` helpers to make the tri-index
  `RecordStore` invariant structural rather than convention. Real
  recommendation; non-trivial refactor that's well-covered by the
  existing regression tests today. Worth doing but not in this PR.
- Stripping unused `StakerSet::{active_nodes, len, is_empty}` (YAGNI).
  `active_nodes` is the bootstrap surface PR 4 needs, and trait
  methods are harder to add once an external impl exists. Keep.
- `Hash` type alias same fate as `NodeId` (already a filed follow-up).

1001/1001 workspace tests pass. Clippy + fmt + cargo doc + cargo deny
+ ADR-hygiene hooks all clean.

Refs #320, addresses PR #646 round-3 review.

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

* refactor(node): drop dht.static_active_nodes; wire empty StakerSet pending PR 4

Per review discussion: maintaining a TOML-file mirror of
StakingRegistry.getActiveNodes() invites drift (operators omitting
stakers, censoring, forgetting to update). Drop the config surface
now — the chain-backed StakerSet is what ADR 022 §STORE Flow line 140
specifies, and PR 4 of #320 already needs the same on-chain read for
bootstrap, so it's the natural home for ChainStakerSet too.

Until PR 4 lands, the runtime wires ConfigStakerSet::empty() with a
loud startup warn. The cache → DHT republish hook exposed in this PR
has no producer yet (PR 4 brings the scheduler), so no publisher-side
traffic is gated either.

Tests build StakerSet programmatically via ConfigStakerSet::{new,
empty} and are unaffected. The StakerSet trait and ConfigStakerSet
remain exported (tests still use them; runtime swap is one line when
ChainStakerSet lands).

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
alpergundogdu pushed a commit that referenced this pull request May 30, 2026
…) (#726)

* feat(protocol+node): promote NodeId/Hash from aliases to newtypes (#653)

Promote node-identity and content-hash values from raw `[u8; 32]` (and the
node-crate local aliases `routing::NodeId`, `records::Hash`, `origin::Hash`)
to distinct `#[repr(transparent)] #[serde(transparent)]` newtypes
`decdn_protocol::NodeId` and `decdn_protocol::ContentHash`. The wire format is
byte-for-byte unchanged — postcard sees the same 32 raw bytes, so no
discriminant tests move and no ALPN bump is required
(`nodeid_postcard_identical_to_array` pins this).

The security crux is the new node-crate `AuthenticatedNodeId` (in
`dht/auth.rs`), constructible ONLY from a live QUIC connection's
`remote_id()` — there is no `From<NodeId>`/`From<[u8;32]>` impl, so wire data
cannot fabricate one. `handle_store`/`handle_batch_store`/`note_peer_seen` now
take `AuthenticatedNodeId`, forcing an explicit `.node_id()` at the
`req.holder` comparison and making the routing-table-poisoning bug class caught
in PR #643 (inserting a wire-provided `requester`) a compile error.

Also adds the `CloserNodes` wrapper (issue "consider also"): the
`MAX_CLOSER_NODES` cap is now enforced at construction and decode by the type
rather than only by a `deserialize_with` hook.

Notes:
- ContentHash and NodeId share the 256-bit XOR keyspace; `routing` gains
  `xor_distance_bytes(&[u8;32],&[u8;32])` and `closest`/`closest_unbounded`
  take a raw keyspace point so the FindValue (hash) and FindNode (id) paths
  both fit without fake-wrapping a hash as a NodeId.
- Named `ContentHash` (not `Hash`) to avoid colliding with
  `decdn_config_types::Hash`.
- The stale issue bullet about `ResolvedDht.static_active_nodes` was a no-op —
  no such field exists (active-staker set is a runtime `StakerSet` trait).

Verified: `cargo fmt --check`, `cargo clippy --workspace --all-targets`,
`cargo nextest run --workspace` (1181 passed).

Closes #653

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

* refactor(dht): address review — enforce auth boundary, fix docs, cache XOR keys

- AuthenticatedNodeId::from_remote_id(&PublicKey) -> from_connection(&Connection):
  a PublicKey can be minted from arbitrary bytes, so the old constructor did not
  actually enforce the "only from a live QUIC connection" boundary. A Connection's
  remote_id is set only by the handshake, so this closes the fabrication path.
- FindValueRequest/FindNodeRequest `requester` docs: stop claiming the responder
  uses the wire value for routing-table updates — it deliberately ignores it and
  refreshes only the authenticated QUIC peer. The old docs could lead a future
  implementer to reintroduce the routing-table-poisoning bug.
- RoutingTable::closest_unbounded: compute xor_distance_bytes once per candidate
  (Schwartzian transform) instead of via sort_unstable_by_key, which does not
  cache its key and would recompute the XOR O(n log n) times on the hot path. The
  old comment claiming the key was cached was incorrect.

Verified: cargo fmt --check, clippy --workspace --all-targets, nextest (396 passed).

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

* test+docs(dht): address multi-agent PR review — close doc/test gaps

Polish from a comprehensive review (no bugs found; all items doc/test accuracy):

- identity.rs: the `from_bytes` const-fn doc claimed it enables a `const fn`
  routing-table construction that doesn't exist (RoutingTable::new is a plain
  fn) — reword to the real reason (const-context + accessor consistency).
- identity.rs test: assert `ContentHash` *decodes* from the bare-[u8;32]
  encoding too (the test pinned NodeId decode but only ContentHash encode; the
  no-ALPN-bump claim needs both directions for both types).
- dht.rs: add `closer_nodes_try_new_enforces_cap` — the construction-time cap
  that the type's docs advertise had no direct test (only the decode path did).
- auth.rs: add a "# Scope" note clarifying the boundary covers the handler's
  requester/holder-substitution decisions, NOT every routing insert — the
  iterative-lookup/bucket-refresh/bootstrap paths legitimately insert
  response-learned NodeIds as probe candidates by design. Mirror that with a
  one-line comment at the two response-learned insert sites.
- routing.rs: correct the `closest` cost comment to match the new Schwartzian
  transform (XOR once + sort over cached distances, not "XOR-compares").

Verified: cargo fmt --check, clippy --all-targets, doc, nextest (397 passed).

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

---------

Co-authored-by: Claude Opus 4.8 (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.

3 participants