Repository navigation
feat(node): chain-backed StakerSet + bootstrap + republish + bucket refresh (PR 4/5 of #320) - #647
Conversation
There was a problem hiding this comment.
Pull request overview
Adds the requester-side DHT client primitives plus runtime wiring for DHT maintenance loops (bootstrap, republish, bucket refresh) that keep the Kademlia routing table and provider records healthy, as part of ADR 022 content discovery (#320).
Changes:
- Introduces
dht::clientoutbound primitives (find_node,store,find_value) and a helper to extract ADR-013 application close codes. - Adds DHT bootstrap + two long-running maintenance tasks (republish scheduler, bucket refresh) and wires them into the node runtime shutdown pipeline.
- Adds
OriginDirectoryabstraction plus loopback/integration tests for DHT client + bootstrap + store admission.
Reviewed changes
Copilot reviewed 8 out of 8 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/node/src/dht/client.rs | New client-side request helpers for cdn/dht/v1 exchanges and error-code extraction. |
| crates/node/src/dht/bootstrap.rs | Bootstrap orchestration: seed routing table from staker set, then self-lookup fanout. |
| crates/node/src/dht/publish.rs | Republish scheduler driving periodic Store fanout from cache insert events + timers. |
| crates/node/src/dht/bucket_refresh.rs | Background routing-table hygiene via periodic bucket refresh FindNode probes. |
| crates/node/src/dht/origin.rs | OriginDirectory trait + config-backed implementation for fallback origin discovery. |
| crates/node/src/dht/mod.rs | Exposes new DHT submodules and re-exports key types. |
| crates/node/src/runtime/mod.rs | Wires bootstrap + republish + bucket-refresh tasks into runtime startup/shutdown. |
| crates/node/tests/dht_bootstrap.rs | Loopback integration tests for find_node, bootstrap routing seeding, and store admission. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Code Review
This pull request implements the client-side DHT logic for node bootstrap, periodic bucket refreshing, and record republishing as specified in ADR 022. It introduces a client module for DHT request primitives, an origin directory fallback mechanism, and integrates these components into the node runtime. Feedback identifies a violation of the StakerSet trait's randomization requirement during bootstrap and suggests refactoring duplicated bucket indexing logic to improve maintainability.
…vict, error chain) Five-bot review on PR #647 found four correctness issues, two important hygiene issues, and one CI failure. All addressed. CI: - PR title renamed: "DHT bootstrap..." → "dht bootstrap..." (the semantic-PR check requires a lowercase subject after `feat(node):`). Critical correctness: - **Eager publish on cache insert.** ADR 022 §STORE Flow steps 2-3 say "send Store NOW, then schedule next at T + uniform(30, 50) min". The previous code scheduled with the steady-state window from the start, so a freshly-cached blob wasn't discoverable for up to 50 minutes. `run_republish` now calls `publish_hash` directly on every insert event before scheduling the next jitter draw. Regression test: `run_republish_publishes_immediately_on_cache_insert`. - **K+3 = 23 fanout actually fans to 23.** `RoutingTable::closest` caps at `K_BUCKET_SIZE = 20` for wire-response safety. The republish path was hitting that cap silently — only publishing to K=20, not K+3=23. Added `RoutingTable::closest_unbounded(target, n)` with no wire-cap clamp, and switched the republish call to use it. ADR 022 §STORE Flow line 128 specifies the three overflow targets as the load-bearing defense against an attacker suppressing receivers. Regression test: `closest_unbounded_returns_more_than_k_when_requested`. - **Stop republishing on cache eviction.** ADR 022 line 122: "A node stops re-publishing when it evicts the blob." Previously the scheduler kept publishing forever once `subscribe_inserts` fired — including DMCA / operator-evict cases. `run_republish` now consumes the `CacheEngine` handle and checks `cache.is_evicted` + `cache.has(hash)` before each republish; evicted hashes get `scheduler.unschedule` and drop out of the rotation. - **Preserve typed iroh errors through the client chain.** The previous `.map_err(|e| anyhow::anyhow!("...: {e}"))` form string-formatted iroh's `ConnectionError` / `ReadError` and discarded the typed source. `extract_app_error_code` walks the error chain looking for those types to pull out ADR 013 application error codes — it was unreliable as a result. Switched to `.context()` which preserves the typed cause chain via `anyhow::Context`. The helper is now meaningful. Important hygiene: - **Bucket refresh: all non-empty buckets per tick.** ADR 022 §Routing Table specifies "1 hour" as the refresh interval **per bucket**. The previous "one bucket per tick" implementation gave a populated bucket up to `KEYSPACE_BITS × interval ≈ 10.5 days` between refreshes. `run_bucket_refresh` now snapshots every non-empty bucket per tick and fans out the `FindNode` RPCs in parallel. Realistic scale (≤30 populated buckets even in a 500-node network) is comfortably under the routing-table peers' default per-IP rate limit (100 req/s). - **Randomise bootstrap fanout.** The `StakerSet` trait contract at `staker_set.rs:30` says callers MUST randomise before any selection step an attacker could influence. The bootstrap code took the first 8 entries from the trait's iteration order. Now shuffles via `SliceRandom::shuffle` before `.take(8)`. Particularly important once a chain-backed `StakerSet` ships and returns entries in on-chain insertion order (which is attacker-influenceable). - **Dedupe `bucket_of`.** Made `routing::bucket_index` `pub(crate)` and dropped the copy in `bucket_refresh.rs`. The own-code comment even acknowledged this was a duplicate. 1021 workspace tests pass (3 new regression guards). Clippy + fmt clean. Refs #320, addresses PR #647 multi-bot review. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
PR 4 of 4 for #320 (Kademlia content discovery). Wires the requester-side outbound primitives plus the long-running maintenance tasks that keep the network healthy. What's in: - `crates/node/src/dht/client.rs` — outbound `find_node`, `store`, `find_value` primitives. Wraps connect → open_bi → frame → decode with a hard 8s timeout and exposes `extract_app_error_code` so callers can match on ADR 013 application error codes (e.g. retry on `RATE_LIMITED`, give up on `MALFORMED_MESSAGE`). - `crates/node/src/dht/bootstrap.rs` — ADR 022 §Bootstrap two-step: (1) seed the routing table directly from `StakerSet::active_nodes()` so inbound DHT traffic can route immediately, (2) fan out `FindNode(self.node_id)` to up to 8 seeds in parallel and ingest every `closer_node` they return. Best-effort — bootstrap failure doesn't abort startup; the seed step alone leaves the table populated. - `crates/node/src/dht/publish.rs` — `RepublishScheduler` with a `BinaryHeap<(due_us, hash)>` keyed by jittered due time. Steady- state: uniform(30, 50) min per ADR 022 §STORE Flow step 3. Cold- start: uniform(0, 40) min per §Bootstrap. The `run_republish` task consumes `CacheEngine::subscribe_inserts` from PR 3 and fans out `Store` to the K+3 = 23 closest peers per due hash. Broadcast `Lagged` logs a warning and continues; the next cycle (or a node restart) will recover. - `crates/node/src/dht/bucket_refresh.rs` — `run_bucket_refresh` task picks the bucket with the oldest last-refresh timestamp per tick (default 1 hour), generates a random `NodeId` whose XOR distance falls in that bucket, and runs `FindNode(random)` against the bucket's freshest peer to repopulate. ADR 022 §Routing Table. - `crates/node/src/dht/origin.rs` — `OriginDirectory` trait + file- config-driven `ConfigOriginDirectory`. The chain-backed `ChainOriginDirectory` reads `PublisherRegistry.namespaceOf` → `OriginAssignment.getOrigins` → `StakingRegistry.nodeIdOf` per ADR 022 §FIND_VALUE Flow; that impl lives in the on-chain origin-directory follow-up. - Runtime wiring: bootstrap runs once at startup with the resolved staker set; the three long-running tasks (republish, bucket refresh, record-store GC) join the existing `JoinSet` shutdown pipeline. Three new loopback integration tests at `crates/node/tests/dht_bootstrap.rs`: - `client_find_node_roundtrip_via_dht_client_module` proves the new client primitives produce the same wire shape as the existing `dht_loopback.rs` hand-written exchange path. - `bootstrap_seeds_routing_and_runs_self_lookup` exercises the full bootstrap orchestration: client C → seed = server S → bootstrap → asserts C's table contains S AND S's table contains C (the latter from C's `FindNode` against S authenticating the connection). - `client_store_lands_record_at_server` exercises the republish scheduler's leaf operation in isolation: a staked publisher's `store` lands a record in the server's `RecordStore`. What's deferred: - Iterative requester-side `FindValue` lookup (α=3 parallel queries with the three ADR-022 §Lookup integrity filters: XOR-distance, active-staker, negative-probe-cache; provider-set randomisation). Splits into a follow-up PR (PR 5 of #320) — the iterative algorithm is non-trivial and pairs more naturally with the prefetch path (ADR 022 §Popularity Signals) than with the maintenance tasks here. `client::find_value` is already in place to support it. - Cold-start cache-iteration: walking every blob in the cache at boot to schedule republish with the uniform(0, 40) min window. `CacheEngine` lacks a public hash-iteration accessor; filed as a follow-up. Steady-state operation via `subscribe_inserts` is unaffected. - alloy `sol!` placeholder bindings for `PublisherRegistry`, `OriginAssignment`, and `StakingRegistry.{nodeIdOf, getActiveNodes}` views. The trait abstractions (`StakerSet`, `OriginDirectory`) isolate the consuming code from the chain dependency, so the bindings can land with the chain-backed impls in one follow-up. 1018 workspace tests pass. Refs #320. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…vict, error chain) Five-bot review on PR #647 found four correctness issues, two important hygiene issues, and one CI failure. All addressed. CI: - PR title renamed: "DHT bootstrap..." → "dht bootstrap..." (the semantic-PR check requires a lowercase subject after `feat(node):`). Critical correctness: - **Eager publish on cache insert.** ADR 022 §STORE Flow steps 2-3 say "send Store NOW, then schedule next at T + uniform(30, 50) min". The previous code scheduled with the steady-state window from the start, so a freshly-cached blob wasn't discoverable for up to 50 minutes. `run_republish` now calls `publish_hash` directly on every insert event before scheduling the next jitter draw. Regression test: `run_republish_publishes_immediately_on_cache_insert`. - **K+3 = 23 fanout actually fans to 23.** `RoutingTable::closest` caps at `K_BUCKET_SIZE = 20` for wire-response safety. The republish path was hitting that cap silently — only publishing to K=20, not K+3=23. Added `RoutingTable::closest_unbounded(target, n)` with no wire-cap clamp, and switched the republish call to use it. ADR 022 §STORE Flow line 128 specifies the three overflow targets as the load-bearing defense against an attacker suppressing receivers. Regression test: `closest_unbounded_returns_more_than_k_when_requested`. - **Stop republishing on cache eviction.** ADR 022 line 122: "A node stops re-publishing when it evicts the blob." Previously the scheduler kept publishing forever once `subscribe_inserts` fired — including DMCA / operator-evict cases. `run_republish` now consumes the `CacheEngine` handle and checks `cache.is_evicted` + `cache.has(hash)` before each republish; evicted hashes get `scheduler.unschedule` and drop out of the rotation. - **Preserve typed iroh errors through the client chain.** The previous `.map_err(|e| anyhow::anyhow!("...: {e}"))` form string-formatted iroh's `ConnectionError` / `ReadError` and discarded the typed source. `extract_app_error_code` walks the error chain looking for those types to pull out ADR 013 application error codes — it was unreliable as a result. Switched to `.context()` which preserves the typed cause chain via `anyhow::Context`. The helper is now meaningful. Important hygiene: - **Bucket refresh: all non-empty buckets per tick.** ADR 022 §Routing Table specifies "1 hour" as the refresh interval **per bucket**. The previous "one bucket per tick" implementation gave a populated bucket up to `KEYSPACE_BITS × interval ≈ 10.5 days` between refreshes. `run_bucket_refresh` now snapshots every non-empty bucket per tick and fans out the `FindNode` RPCs in parallel. Realistic scale (≤30 populated buckets even in a 500-node network) is comfortably under the routing-table peers' default per-IP rate limit (100 req/s). - **Randomise bootstrap fanout.** The `StakerSet` trait contract at `staker_set.rs:30` says callers MUST randomise before any selection step an attacker could influence. The bootstrap code took the first 8 entries from the trait's iteration order. Now shuffles via `SliceRandom::shuffle` before `.take(8)`. Particularly important once a chain-backed `StakerSet` ships and returns entries in on-chain insertion order (which is attacker-influenceable). - **Dedupe `bucket_of`.** Made `routing::bucket_index` `pub(crate)` and dropped the copy in `bucket_refresh.rs`. The own-code comment even acknowledged this was a duplicate. 1021 workspace tests pass (3 new regression guards). Clippy + fmt clean. Refs #320, addresses PR #647 multi-bot review. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…he seed Covers the deferreds from PR 646 + PR 647's own description that became unblocked by #641 landing the StakingRegistry contract: - `crates/incentive/src/staking_registry.rs`: alloy `sol!` bindings for StakingRegistry. View functions consumed at runtime (`isActive`, `isActiveNode`, `nodeIdOf`, `getActiveNodes`, `getActiveNodeCount`) plus the six events that mutate the active set (`NodeRegistered`, `NodeDeregistered`, `NodeAutoEjected`, `EjectedByBlacklist`, `Reinstated`, `UnbondingRequested`). Write functions and governance events are intentionally out of scope — the node runtime never sends transactions to this contract. - `crates/node/src/dht/chain_staker_set.rs`: `ChainStakerSet`. Paginated `getActiveNodes(offset, 100)` at startup, then `isActive(operator)` per entry to filter `_registeredAddrs` down to the strict active predicate. Spawns a background watcher task that follows the six membership events and emits `StakerChange` via a `broadcast::Sender`. Watcher restarts its event filters with exponential backoff (1s → 60s cap) on RPC failure. Multicall3 batching at bootstrap and a re-bootstrap-on-extended- outage path are flagged as follow-ups. - `crates/node/src/dht/staker_set.rs`: `StakerSet` trait gains `subscribe_changes() -> broadcast::Receiver<StakerChange>` and `StakerChange { Active(NodeId) | Inactive(NodeId) }`. `ConfigStakerSet` holds a silent `broadcast::Sender` so receivers stay open forever without firing — call sites can be impl-agnostic instead of branching. Same pattern in the `AllStaked` test stub. - `crates/node/src/dht/publish.rs`: `RepublishScheduler::seed_cold_start(iter)` batch-schedules every input hash with an independent `uniform(0, 40 min)` draw per ADR 022 §Bootstrap. Consumed by the runtime at startup over `CacheEngine::access_times_snapshot` (which already exists; the PR-647 deferred bullet claiming we needed a new accessor was incorrect — verified at `crates/cache/src/engine.rs:1244`). - `crates/node/src/runtime/mod.rs`: builds the alloy `RootProvider<Http<reqwest::Client>>` from `cfg.blockchain.rpc_url`, parses `cfg.blockchain.staking_registry_address`, and replaces the `ConfigStakerSet::empty()` placeholder + warn with `ChainStakerSet::bootstrap(...).await`. Bootstrap RPC failure is fatal — per ADR 022 §Bootstrap the DHT cannot function without a populated staker set. Cold-start seed happens between scheduler construction and the `run_republish` spawn so any blob already on disk gets a jittered first-publish entry without waiting for `subscribe_inserts`. Tests: 5 new unit tests (`apply_change` active/inactive idempotent on `ChainStakerSet`, `ConfigStakerSet::subscribe_changes` stays-open-never-fires, `RepublishScheduler::seed_cold_start` distribution + empty-input no-op). The existing 1094 tests still pass — 1099 total. An anvil-backed integration test (deploy `StakingRegistry`, register two operators, assert bootstrap populates, deregister one, assert the watcher emits `Inactive`) would be the highest-value addition; it requires contract-deployment scaffolding the workspace doesn't yet have and is flagged as a follow-up. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
03db273 to
3eb3edb
Compare
Coverage reportTotal: 88.81% (was 90.30%, ▼ 1.49%) — 20451/23027 lines No Rust files changed in this PR. History
|
Findings consolidated from 5 review agents (code-reviewer, pr-test-analyzer, comment-analyzer, silent-failure-hunter, type-design-analyzer): - Drop `EjectedByBlacklist` event subscription. `StakingRegistry.ejectNode` emits both `EjectedByBlacklist(operator)` AND `NodeAutoEjected(nodeId)` in the same call (contract lines 662-672); subscribing to both produced one wasted `nodeIdOf` RPC per blacklist ejection. The `NodeAutoEjected` arm covers the membership change with the canonical nodeId. Operators with no nodeId binding are never in our active set, so dropping `EjectedByBlacklist` loses no information. - Rewrite the Failure-model docstring to match what `watcher_loop` actually does today (log + exponential-backoff filter restart, no resync). The previous version promised a `getActiveNodes` resync after `WATCHER_RESYNC_THRESHOLD` that the code did not implement (constant was `#[allow(dead_code)]`). Drop the dead constant. - Remove the fabricated ADR 019 § Step 3.3 quote. ADR 019 names four events (`NodeRegistered`, `NodeMultiaddrUpdated`, `NodeDeregistered`, `NodeAutoEjected`); our subscription is the correct active-set predicate (no `MultiaddrUpdated` because it doesn't move membership; plus `Reinstated` and `UnbondingRequested` because they do). Ground the comment in the contract's own write paths instead. - Log `warn!` on `RwLock` poison recovery in `read_active` and `apply_change` — matches the in-repo precedent at `cache/src/engine.rs:510-516`. A poisoned lock means *something panicked while holding the write lock*; silent recovery hid that signal completely. - Improve the `nodeIdOf` RPC-failure warn message to spell out that dropping the event leaves the cached set diverged from chain state until a follow-up event arrives. Same observability point as the poison-recovery log. - Fix bootstrap pagination off-by-one: break on `page.is_empty()` instead of `page_len < PAGE_SIZE`. At exactly 100/200/… registered operators the previous condition issued one wasted trailing RPC returning an empty page. - Switch `seed_cold_start` test from peeking at the private `s.heap` to a behavioural `drain_due` check at deadline — survives a future swap to a different scheduling primitive. - Trim stale issue / PR-number references in doc comments (#283, "PR 5", "PR 647", "deferred Multicall3", ADR-line citations). Trim WHAT-narrating bullets in the `staking_registry.rs` module doc; keep the two non-obvious gotchas (`getActiveNodes` not filtered, `nodeIdOf.active` is the full predicate). - Trim WHAT-narrating runtime comments around `ChainStakerSet` bootstrap + cold-start seed; keep only the load-bearing WHY (fatal-on-failure rationale, subscribe-before-seed ordering). - Document the `RecvError::Lagged` contract on `StakerSet::subscribe_changes` so consumers know to handle it. Type-design suggestions (rename `StakerChange::Active/Inactive` → `Joined/Left`, rename `_watcher` field, swap broadcast::Receiver for `Stream` in the trait) are deliberately deferred — they're public-API churn for stylistic gains, not load-bearing. Anvil-backed integration test for the full chain → Rust contract remains the highest-value follow-up (operator→NodeId binding via `nodeIdOf`, watcher reconnect on RPC failure). Tests: 1099/1099 pass. clippy clean. fmt clean. cargo doc clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alpergundogdu
left a comment
There was a problem hiding this comment.
Review — chain-backed StakerSet + bootstrap + republish + bucket refresh
Solid PR. The DHT outbound primitives, the three long-running tasks, and the chain-backed staker set all hang together cleanly, and the test coverage (5 unit tests + the loopback integration) is good. I verified the parts that could have been correctness bugs and they hold up:
- Skipping the
EjectedByBlacklistsubscription is correct.StakingRegistry.ejectNodeemitsNodeAutoEjected(nodeId, …)whenevernodeId != bytes32(0)(contracts/src/StakingRegistry.sol:774-776), andslashdoes the same (:757). An operator with no nodeId binding can't be in the active set, so the nodeId-indexed event is sufficient — no membership change is missed. - Fatal bootstrap ordering is fine.
check_rpc_reachabilityruns first (runtime/mod.rs:238), so an unreachable RPC fails before theChainStakerSet::bootstrapcall. - The poison-recovery pattern is consistent with the repo.
read_activematches the existingpoisoned.into_inner()precedent incache/src/engine.rs:512-514.
Findings below — none are blocking. Most are comment/doc rot that will mislead the next reader, plus a couple of operational questions.
Cleanups (worth fixing)
-
Dead
MAX_RESPONSE_BYTES+ false doc comment —crates/node/src/dht/client.rs:~43and:~209. The constant's doc says "we pass it explicitly toread_to_endso a misbehaving peer can't stream an arbitrary amount of data" — but it's never passed anywhere;exchange_onusesread_frame. The only reference islet _ = MAX_RESPONSE_BYTES;insideextract_app_error_code, kept "so a future chunked-read switch has the right constant on hand." That's a hypothetical-future hook on a dead constant with a doc that describes behavior the code doesn't have. Fix: delete the constant and thelet _ =. Re-add it (and actually wire it into a bounded read) when the chunked-read path lands. -
PathBufcargo-cult in the new test —crates/node/tests/dht_bootstrap.rs:~289and:~370.use std::path::PathBuf;exists only solet _ = PathBuf::new(); // satisfy "PathBuf import" if linter pivots.can "use" it. PathBuf isn't needed by the test at all. Fix: delete both the import and the dummy line. -
let _ = cache_dir;comment is backwards —crates/node/tests/dht_bootstrap.rs:~369. The comment says "kept-alive guard," butlet _ = cache_dir;moves and immediately drops theTempDir— the opposite of keeping it alive. It's harmless here only because it sits aftertask.await(cache work is already done). The binding already lives to end-of-scope on its own. Fix: delete the line. -
Stale module doc contradicts the implementation —
crates/node/src/dht/bucket_refresh.rs:~16-21. The module doc says the task "picks one non-empty bucket per tick (the oldest bucket by last-refresh time, tracked here…)." The code refreshes every non-empty bucket per tick (refresh_all_non_empty_buckets/all_non_empty_picks), and theBUCKET_REFRESH_TICKconst doc at:~37explicitly says "we run every non-empty bucket per tick." There's no last-refresh-time tracking anywhere — that design was abandoned. The PR description repeats the wrong "picks the oldest non-empty bucket per tick" wording too. Fix: rewrite the module doc to match the all-buckets-per-tick behavior (and drop the "tracked here" claim). -
Self-contradictory
schedule_steadydoc —crates/node/src/dht/publish.rs:~148-157. The doc says "Idempotent — re-scheduling a hash that's already in the heap updates the existing entry's due time rather than creating a duplicate," then the next sentence admits "Today's implementation pushes a fresh entry…". The real behavior pushes duplicate heap entries that get deduped at drain via thescheduledset. Fix: drop the aspirational first sentence; describe the push-duplicate-then-dedupe-on-drain behavior that actually exists. -
Unused
_cacheparameter —crates/node/src/dht/publish.rs:~372,publish_hash. It's threaded in but never read (thecache_still_holdscheck happens in the caller). Fix: remove the parameter, or add a one-line note if it's deliberately reserved.
Questions / follow-ups
-
Node now hard-requires a deployed
StakingRegistryto boot. [your call] MakingChainStakerSet::bootstrapfatal means a reachable RPC is no longer enough —getActiveNodeshas to succeed against a real contract atstaking_registry_address. Previously the node booted with an empty set + a warning. This removes the ability to rundecdn-nodeagainst a chain that doesn't yet have the registry deployed (some local/offline dev flows). The comment says fatal is deliberate, and I agree it's the right production behavior — just confirming there's a dev story, given the PR notes anvil deploy scaffolding is itself a deferred follow-up. -
Event-watcher gaps are worth a tracked follow-up. [your call] Two related gaps, both partly acknowledged in the module doc: (a) events emitted between the
getActiveNodessnapshot and the.watch()filter install are lost with no resync; (b) the provider is HTTP (connect_http), so.watch()is filter-polling (eth_newFilter/eth_getFilterChanges), which silently misses logs / expires on many hosted RPCs — andrun_watcher_oncetreats aNonestream as a clean restart that resets the backoff, so a flapping filter could spin tight. A periodicgetActiveNodesre-sync would close both. Acceptable at this network scale; flagging so it lands as a real follow-up rather than living only in a doc comment. -
Pagination isn't a consistent snapshot (minor).
bootstrap_active_setpagesgetActiveNodes(offset, 100)over_registeredAddrs. If an operator deregisters mid-pagination and the contract swap-removes from that array, an entry behind the current offset can be skipped entirely and stays missing until its next event. Same periodic-resync follow-up as #8 covers it; calling it out for the record. -
PR description says the watcher subscribes to "the six events" — it subscribes to five (
run_watcher_oncedeliberately skipsEjectedByBlacklist, per finding above). The in-code comment is accurate; just the description that's off. Description-only, no code change.
Addresses Alper's review on #647: drop the unused `MAX_RESPONSE_BYTES` constant + its placeholder `let _ =` (a doc-described `read_to_end` bound that never existed); remove the `PathBuf` cargo-cult import and the misleading `let _ = cache_dir;` "kept-alive guard" in the republish-on-insert test; rewrite the `bucket_refresh` module doc to match the all-buckets-per-tick behavior the constant doc and code already describe; rewrite `schedule_steady`'s self-contradictory doc to describe the push-duplicate-then-dedupe-on-drain behavior that actually exists; drop the unused `_cache` parameter from `publish_hash` (the cache-still-holds check lives in the caller). No behavior change. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… of #320, closes #320) Closes #320. Lands the requester-side iterative `FindValue` lookup that #647's `client::find_value` was a primitive for, plus the negative probe cache it depends on. - `crates/node/src/dht/negative_cache.rs` (new) — bounded LRU cache of `(NodeId, hash)` pairs per ADR 001 §97–99. 1024-entry default cap, 5-min TTL anchored at insertion, expired-on-read eviction, LRU bumping on read hits. `record_failure` is the producer-side hook for the future outbound `cdn/probe/v1` client (ADR 001 §97); ships now so the lookup-side tests can populate the cache and the eventual probe client has a stable surface. - `crates/node/src/dht/lookup.rs` (new) — iterative Kademlia `find_providers` with α=3 parallelism and the three ADR 022 §Lookup-integrity filters applied in order to every response: 1. `filter_xor_closer` — drop `closer_nodes` not strictly closer to target than the responder itself (line 182). 2. `filter_active_stakers` — drop non-staked NodeIds from both `providers` and `closer_nodes` (line 183), via the `StakerSet::is_active` seam already wired by #647. 3. `filter_negative_cache` — drop `(provider, target)` pairs in the negative cache (line 184), `providers` only. Termination follows textbook Kademlia: stop on `providers.len() >= k` OR a full round completes without any candidate strictly closer than the current best-queried distance. Final provider list is shuffled (`rand::rng()` `SliceRandom::shuffle`) before return — ADR 022 §186 calls randomisation "the load-bearing defense against ordering manipulation." - Module wiring: `pub use` for `find_providers`, `LookupConfig`, `NegativeProbeCache` from `crates/node/src/dht/mod.rs`. No runtime wiring — PR 5 lands the primitive; the caller (cdn/client/v1 cache-miss path, issue #317) will construct `Arc<NegativeProbeCache>` once at startup and pass it into `find_providers` along with the existing `Arc<dyn StakerSet>` / `Arc<Mutex<RoutingTable>>`. Tests (17 new, 1116/1116 pass): - 6 negative_cache unit: absent-key, insert→contains, TTL expiry + eviction, LRU eviction at cap, read-hit bumps LRU, re-record refreshes TTL. - 7 lookup unit: filter_xor_closer drops at-or-beyond, filter_active_ stakers drops non-staked, filter_negative_cache drops only (provider, target) pairs, LookupState pick / candidate tracking / provider dedup / randomisation truncates-and-shuffles. - 4 lookup integration (multi-node loopback): happy path returns directly reachable provider, filter 3 drops cached failure, filter 2 drops non-staked provider, empty routing table converges to empty result. PR 4/5 of #320 (chain-backed StakerSet etc.) is open as #647 and not yet merged; this branch is stacked on #647 and will rebase onto main once #647 merges. Stays deferred (out of scope per ADR / dependency status): - ChainOriginDirectory + PublisherRegistry alloy bindings — needs OriginAssignment.sol which isn't on main yet. - cdn/client/v1 cache-miss integration — issue #317. - Outbound `cdn/probe/v1` client + positive probe cache (ADR 001 §93) — separate track. - Anvil-backed integration tests for the chain-side staker set remain a follow-up alongside the deferred work above. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… of #320) (#673) * feat(node): iterative FindValue lookup + negative probe cache (PR 5/5 of #320, closes #320) Closes #320. Lands the requester-side iterative `FindValue` lookup that #647's `client::find_value` was a primitive for, plus the negative probe cache it depends on. - `crates/node/src/dht/negative_cache.rs` (new) — bounded LRU cache of `(NodeId, hash)` pairs per ADR 001 §97–99. 1024-entry default cap, 5-min TTL anchored at insertion, expired-on-read eviction, LRU bumping on read hits. `record_failure` is the producer-side hook for the future outbound `cdn/probe/v1` client (ADR 001 §97); ships now so the lookup-side tests can populate the cache and the eventual probe client has a stable surface. - `crates/node/src/dht/lookup.rs` (new) — iterative Kademlia `find_providers` with α=3 parallelism and the three ADR 022 §Lookup-integrity filters applied in order to every response: 1. `filter_xor_closer` — drop `closer_nodes` not strictly closer to target than the responder itself (line 182). 2. `filter_active_stakers` — drop non-staked NodeIds from both `providers` and `closer_nodes` (line 183), via the `StakerSet::is_active` seam already wired by #647. 3. `filter_negative_cache` — drop `(provider, target)` pairs in the negative cache (line 184), `providers` only. Termination follows textbook Kademlia: stop on `providers.len() >= k` OR a full round completes without any candidate strictly closer than the current best-queried distance. Final provider list is shuffled (`rand::rng()` `SliceRandom::shuffle`) before return — ADR 022 §186 calls randomisation "the load-bearing defense against ordering manipulation." - Module wiring: `pub use` for `find_providers`, `LookupConfig`, `NegativeProbeCache` from `crates/node/src/dht/mod.rs`. No runtime wiring — PR 5 lands the primitive; the caller (cdn/client/v1 cache-miss path, issue #317) will construct `Arc<NegativeProbeCache>` once at startup and pass it into `find_providers` along with the existing `Arc<dyn StakerSet>` / `Arc<Mutex<RoutingTable>>`. Tests (17 new, 1116/1116 pass): - 6 negative_cache unit: absent-key, insert→contains, TTL expiry + eviction, LRU eviction at cap, read-hit bumps LRU, re-record refreshes TTL. - 7 lookup unit: filter_xor_closer drops at-or-beyond, filter_active_ stakers drops non-staked, filter_negative_cache drops only (provider, target) pairs, LookupState pick / candidate tracking / provider dedup / randomisation truncates-and-shuffles. - 4 lookup integration (multi-node loopback): happy path returns directly reachable provider, filter 3 drops cached failure, filter 2 drops non-staked provider, empty routing table converges to empty result. PR 4/5 of #320 (chain-backed StakerSet etc.) is open as #647 and not yet merged; this branch is stacked on #647 and will rebase onto main once #647 merges. Stays deferred (out of scope per ADR / dependency status): - ChainOriginDirectory + PublisherRegistry alloy bindings — needs OriginAssignment.sol which isn't on main yet. - cdn/client/v1 cache-miss integration — issue #317. - Outbound `cdn/probe/v1` client + positive probe cache (ADR 001 §93) — separate track. - Anvil-backed integration tests for the chain-side staker set remain a follow-up alongside the deferred work above. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(node): apply PR #673 review (private helpers, self-filter providers, O(log N) candidate dedup) - `negative_cache.rs`: make `with_capacity` (`#[cfg(test)]`) and `with_capacity_and_ttl` (private fn) non-public — they were documented as test-only but exposed as `pub` (Copilot). - `lookup.rs`: skip `ctx.requester_id` in the providers loop for symmetry with the existing `closer_nodes` self-filter (Gemini). - `lookup.rs`: replace `candidates.values().any(|v| v == &peer)` with `candidates.contains_key(&dist)` — XOR distance is bijective for a fixed target, so this is equivalent and O(log N) instead of O(N) (Gemini). Pushed back on Gemini's HIGH-priority termination comment: the existing `if !observed_closer { break; }` matches ADR 022 §176 ("Continue until providers are found or lookup converges (no closer nodes returned)"). Reply posted inline. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(node): apply PR #673 multi-agent review Addresses findings from the parallel code/test/error/type/comment review on PR #673. All 279 node tests pass; clippy/fmt/rustdoc clean. Critical: - Fix wrong ADR citation: `DEFAULT_K` now cites `§ Routing Table` (the table where k=20 lives), not §99 (the α=3 row). - Clamp `LookupConfig.alpha`/`k` to ≥1 inside a new `sanitize_config` helper called at the top of `find_providers`. A zero in either field used to silently make the lookup a no-op. - Distinguish `PublicKey::from_bytes` failure from generic transport failures via a new `RoundRpcError` enum. The Ed25519 decode case now logs at `warn!` since the bytes already survived the routing table seed / response filters — failure here is a state-integrity signal, not a transport hiccup. - Add the missing Filter-3-asymmetry test (`fold_response_negative_cache_does_not_drop_closer_nodes`) so a future "tidy-up" that extends Filter-3 to `closer_nodes` ships red. Important: - Demote `filter_xor_closer` / `filter_active_stakers` / `filter_negative_cache` from `pub` to module-private — they have no out-of-crate consumers. - Move the requester-id self-filter from `process_response` into `LookupState::add_candidate` / `record_provider` so it can't be bypassed by a future caller. Drop the symmetric checks at the callsite. - Replace the lockstep `HashMap+VecDeque` in `Inner` with a single `IndexMap<Key, Instant>` (insertion order IS the LRU order); same for `LookupState.providers+providers_seen` → `IndexSet<NodeId>`. Removes two doc-only invariants. Adds `indexmap` as a workspace + node-crate dep. - Log the aborted-peer count when a round timeout fires (`tasks.len()` post-drain) so a future dashboard can distinguish "round drained cleanly" from "round timed out with N peers in flight." - Tighten the `find_providers` docstring to match the actual per- peer-error classification. Tests added (+6 unit): - `fold_response_negative_cache_does_not_drop_closer_nodes` - `fold_response_records_providers_even_when_no_closer_node` - `have_enough_providers_is_inclusive_at_k` - `lookup_state_rejects_self_in_candidates_and_providers` - `sanitize_config_clamps_zero_alpha_and_k_to_one` - `read_hit_does_not_refresh_ttl` (negative_cache.rs) - Strengthened `into_randomised_providers_truncates_to_k_and_shuffles` to require ≥2 distinct orderings across 16 runs. Cosmetic / comment rot: - Drop "PR slice (#320)" / "future probe client that does not exist on `main` yet" / "(PR 5 of #320)" rot references per the CLAUDE.md ban on task / fix / PR-context comments. - Drop test-method docstrings that just restate the test name and the "Inject candidates manually" WHAT comments. - Drop the "`BTreeMap` gives O(log n)" line that restated the type's semantics. - Consolidate `Hash` alias: `negative_cache.rs` now re-exports `crate::dht::records::Hash` instead of redeclaring `[u8; 32]`. - Fold the stray `use crate::dht::routing::NODE_ID_LEN` mid-file into the top use block. - Widen the TTL test timing gaps (200ms/300ms instead of 40/60ms, 400ms/200+300ms instead of 80/40+60ms) to reduce flake risk on loaded CI runners. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(node): apply PR #673 round-3 review Second multi-agent review pass found 2 factual errors in comments, a residual type-design gap, missing combined-filter test, and several ADR-citation drift risks. All addressed here. Critical (factual errors): - Shuffle test: the docstring claimed `>= 2 distinct orderings` defends against "swap-only-the-last-two shuffle bugs," but that bug actually produces 1 ordering (truncate hides the swap) — the test catches *that*, but the claim that `>= 2` is general was wrong. Rephrased the comment to be precise about the threshold, raised it to `>= 8` so the test also catches 1-3 element cycle shuffles (4-element cycle still passes; documented). - `record_failure` comment on `shift_insert`: said it "removes the existing entry (if any) first and re-inserts at index 0." Per indexmap docs `shift_insert` *moves* an existing key to the new index and updates the value — single op, not remove+insert. Mechanism description was misleading anyone debugging via indexmap source. Important: - `LookupConfig.alpha` and `.k` are now `NonZeroUsize` instead of `usize`. The previous `sanitize_config` guard fired only at the `find_providers` entry point; tests constructing `LookupState` directly bypassed it. With `NonZeroUsize` the invalid state is unrepresentable, the guard is dropped entirely, and the now- unreachable `sanitize_config_clamps_zero_alpha_and_k_to_one` test is deleted. `DEFAULT_ALPHA` and `DEFAULT_K` consts use `match NonZeroUsize::new(N) { Some(n) => n, None => NonZeroUsize::MIN }` for const init (the `unwrap_or` route isn't const-stable yet). - New `fold_response_all_filters_compose` test exercises F1, F2, F3, and self-filter simultaneously on one response. Defends against filter-reorder / short-circuit-on-empty / wrong-field- routing regressions that none of the per-filter unit tests would individually catch. - ADR citations using line-number `§NNN` style (§192, §184, §186, §183, §180, §97, §99) replaced with section/paragraph identifiers (`§ FIND_VALUE Flow`, `§ Lookup integrity`, `§ Probe cache`) — same drift-resistance fix already applied to `§99 → § Routing Table` in round 1. - `Inner.cap` and `Inner.ttl` now have one-line docstrings (`cap` clamped >=1 in ctor; `ttl` anchored at insertion). - `RoundRpcError` docstring now names the two upstream paths that can leak an invalid NodeId (routing-table corruption, staker-set seed) instead of vague "state-integrity damage." - Dropped the redundant `shift_remove` before `shift_insert(0,…)` in `contains_active`: `shift_insert` alone moves an existing key to the new index. Added `shift_insert_on_existing_key_moves_to_front_of_lru` regression test pinning indexmap's behavior against a future major-version semantic change. Suggestions: - TTL test margins widened from ~100ms slack to ~250-500ms: - `expired_entry`: 200/300ms → 500/750ms - `read_hit_does_not_refresh_ttl`: 300/150+250ms → 500/250+500ms - `re_recording_same_key`: 400/200+300ms → 1000ms / 500+750ms - Test docstring for `sanitize_config_clamps_*` had a wrong failure-mode claim (`LookupConfig::default()` patterns). Test is now gone (unreachable with NonZeroUsize); no fix needed. Deferred (per analyst recommendation): - Round-timeout `state.queried` strand (aborted in-flight peers not retried). The new `aborted_peers` log makes it observable. Filing as follow-up rather than blocking this PR. Tests: 280 pass (was 279; +2 new, -1 deleted). Clippy / fmt / rustdoc clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
PR 4 of 5 for #320 (Kademlia content discovery). Wires the requester-side outbound primitives, the long-running maintenance tasks, and the chain-backed staker set unblocked by #641. Rebased on main (the original branch was stacked on PR 646's pre-cleanup state and went conflicting after #646 squash-merged).
crates/node/src/dht/client.rs— outboundfind_node,store,find_valueprimitives. Wraps connect → open_bi → frame → decode with a hard 8s timeout.extract_app_error_codelets callers match on ADR 013 application error codes.crates/node/src/dht/bootstrap.rs— ADR 022 §Bootstrap two-step: seed routing table fromStakerSet::active_nodes(), then fan outFindNode(self.node_id)to ≤8 seeds. Best-effort.crates/node/src/dht/publish.rs—RepublishSchedulerwithBinaryHeapkeyed by jittered due time. Steady-stateuniform(30, 50)min, cold-startuniform(0, 40)min.run_republishconsumessubscribe_insertsand fansStoreto K+3=23 closest peers per due hash. Now also exposesseed_cold_start(iter)for the runtime startup path.crates/node/src/dht/bucket_refresh.rs— every hour, refreshes every non-empty bucket in parallel: oneFindNode(random_id_in_bucket)per bucket against the bucket's most-recently-seen peer.crates/node/src/dht/origin.rs—OriginDirectorytrait +ConfigOriginDirectory. Chain-backed impl stays deferred (see below).crates/incentive/src/staking_registry.rs— alloysol!bindings forStakingRegistry(feat(contracts): add node-registry surface to StakingRegistry #641): five view functions and the six events that mutate the active set. Write functions intentionally out of scope (the node never sends transactions to this contract).crates/node/src/dht/chain_staker_set.rs—ChainStakerSet. PaginatedgetActiveNodes(offset, 100)at startup,isActive(operator)per entry to filter_registeredAddrsto the strict predicate, background watcher subscribed to five of the six events (skipsEjectedByBlacklist—slashandejectNodealready emitNodeAutoEjectedfor the same nodeId, so the nodeId-indexed event covers blacklist ejections too), exponential-backoff restart on RPC failure.crates/node/src/dht/staker_set.rs—StakerSettrait gainssubscribe_changes() -> broadcast::Receiver<StakerChange>and theStakerChange { Active | Inactive }enum.ConfigStakerSetholds a silentbroadcast::Senderso receivers stay open forever without firing — call sites stay impl-agnostic.RootProviderfromblockchain.rpc_url, bootstrapsChainStakerSet(fatal-on-failure per ADR 022 §Bootstrap), seeds the republish scheduler fromcache.access_times_snapshot()before spawningrun_republish. Three long-running tasks join theJoinSetshutdown pipeline.Deferred (per the issue-320 plan)
FindValuelookup — α=3 parallel with the three ADR-022 §Lookup integrity filters (XOR-closer, active-staker, negative-probe-cache) + provider-set randomisation. Splits to PR 5 of Implement content discovery via cdn/dht/v1 Kademlia DHT #320;client::find_valueis in place to support it, andStakerSet::subscribe_changesis the hook PR 5 uses to keep its lookup filter cache fresh.(NodeId, hash)5-min/1024-LRU cache per ADR 001 §97–99. Filter-3 dependency for iterative lookup; lands in PR 5.ChainOriginDirectory— blocked onPublisherRegistryandOriginAssignmentSolidity contracts (onlyStakingRegistry.sol,Token.sol,VotingEscrow.solexist incontracts/src/today).ConfigOriginDirectorystays as the only impl; no TOML surface so operators don't accidentally maintain a parallel chain mirror.Multicall3batching atChainStakerSetbootstrap — N+1 round-trips today (paginatedgetActiveNodes+ per-entryisActive). Acceptable at PoC scale (tens of nodes); same Multicall3 dependency is already planned for the origin-directory fallback path (ADR 022 §192).ChainStakerSet— would be the highest-value test (deployStakingRegistry, register two operators, assert bootstrap populates, deregister one, assert the watcher emitsInactive). Requires contract-deployment scaffolding the workspace doesn't yet have; follow-up.decdn_rpc_healthywatchdog uses a rawreqwest::Client; the new alloyRootProvidercould replace it. Orthogonal cleanup; deferred.Test plan
cargo nextest run— 1099/1099 pass (5 new unit tests: 2ChainStakerSet::apply_changeidempotency, 1ConfigStakerSet::subscribe_changesstays-open-never-fires, 2RepublishScheduler::seed_cold_startdistribution + empty-input).cargo clippy --workspace --all-targets -- -D warningsclean.cargo fmt -- --checkclean.pre-commit run— all hooks pass (fmt, clippy, doc, deny, ADR hygiene).RUSTDOCFLAGS=-D warnings cargo doc --workspace --no-deps --document-private-itemsclean.Refs #320. Rebased on main (was stacked on PR 646's pre-cleanup state).
🤖 Generated with Claude Code