Repository navigation
feat(node): iterative FindValue lookup + negative probe cache (PR 5/5 of #320) - #673
Conversation
There was a problem hiding this comment.
Pull request overview
Implements requester-side Kademlia content discovery by adding an iterative FindValue lookup loop (α-parallel) plus a bounded negative probe cache used to suppress known-bad (provider, hash) candidates, and wires these primitives into the node DHT module API.
Changes:
- Added
NegativeProbeCache: bounded (default 1024) LRU cache with TTL-based eviction, plus arecord_failurehook for future probe integration. - Added iterative
find_providerslookup with ADR-022 integrity filters (XOR-closer, active-staker, negative-cache) and provider randomization. - Added loopback integration tests covering happy path, staker filtering, negative-cache filtering, and convergence on empty routing tables.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| crates/node/src/dht/negative_cache.rs | New negative probe cache implementation (LRU + TTL) used by lookup-side filtering. |
| crates/node/src/dht/lookup.rs | New iterative requester-side FindValue lookup with α-parallel rounds, integrity filters, and randomized provider output. |
| crates/node/src/dht/mod.rs | Exposes the new lookup/cache modules and re-exports find_providers, LookupConfig, and NegativeProbeCache. |
| crates/node/tests/dht_lookup.rs | New multi-node loopback integration tests for iterative lookup behavior and filters. |
💡 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 requester-side iterative FindValue lookup and a negative probe cache as specified in ADR 022 and ADR 001. The changes include the core lookup logic with parallel RPC support, response filtering (XOR-distance, active-staker, and negative cache), and a bounded LRU cache for failed probes. Feedback focuses on refining the lookup termination criteria to prevent premature convergence, ensuring the requester's own ID is excluded from provider sets, and optimizing candidate tracking by replacing an O(N) search with a more efficient O(log N) key check.
…rs, 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]>
… 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]>
…rs, 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]>
60d4e1f to
4e8512a
Compare
Coverage reportTotal: 89.02% (was 88.82%, ▲ +0.20%) — 20993/23583 lines
History
|
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]>
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]>
The dht_lookup.rs permissive limiter helper constructed DhtRateLimitConfig without max_tracked_per_ip / max_tracked_per_peer, added in #676 (#645). Since dht_lookup.rs landed in #673 in parallel, the field additions never reached it, breaking the test, MSRV, and clippy jobs on main. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…719) Adds `crates/node/tests/dht_integration.rs` covering the iterative FindValue lookup path from PR #673, the behaviours that only manifest once the routing table and negative cache interact with a live lookup: - bucket-overflow LRU eviction + node departure (`remove`) — the routing table is LRU-on-overflow, not split-on-overflow Kademlia, so issue #711's "k-bucket split" maps onto eviction behaviour; - convergence after a peer departs the routing table; - an unreachable peer mid-lookup (handler dropped) does not wedge the pass — pinned with the dead peer as the *closest* candidate so the live, farther provider still surfacing is non-trivial, plus a wall-clock guard against a hang regression; - genuine two-round convergence via a `closer_nodes` referral, the first end-to-end coverage of the iterative `observed_closer` loop; - negative-cache TTL expiry un-suppresses a provider on the same cache instance, proving a stale entry does not poison future lookups. Promotes `NegativeProbeCache::with_capacity_and_ttl` to a documented `pub` test/tuning seam: the cache is `Instant`-anchored, so `tokio::time` cannot drive it and a short injected TTL is the only deterministic way to exercise expiry from an integration test. Production still uses `new()` with the ADR 001 defaults. Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…ort (#1869) * fix(client-pull): calibrate the watchdog unit deadline from measured checkpoint cost A fixed 600ms unit deadline is load-flaky: a contended runner can move 4MiB slower than it, falsely reassigning the healthy lane. Time one checkpoint through a fresh lane first, then rest the deadline a factor above it, floored for fast machines and capped well under the 20s outer bound. * test(node): bound the teardown deadline above the drain cap and return a ShutdownReport Pin SHUTDOWN_TIMEOUT > ABANDON_DRAIN_CAP at compile time (mirroring the CONVERGENCE_ROUND_TIMEOUT pattern) so a ceilinged drain can never consume the whole budget. Have support::shutdown return a ShutdownReport carrying the reaped/closed counts so a caller can assert on a breach rather than only see the warning line, and pin both behaviors under start_paused: the clean counts, and a stalled close (endpoint whose close() blocks on a never-draining connection) that still yields Ok with closed < M. * test(node): drop changelog voice and tighten a negative-cache test name The module header's 'introduced in PR #673' is changelog voice; state the present capability. Rename find_providers_negative_cache_expires_after_ttl to say what it asserts: the lookup stops suppressing once the negative entry expires. * test: make the stalled-close teardown test falsifiable and scale the wedge budget The close-path teardown test ran on a paused clock with its endpoint driver on another thread. A paused clock auto-advances past the deadline the moment the runtime idles, so the breach was manufactured by the clock rather than by the stranded connection: the test passed with the whole strand apparatus removed, and with no connection at all. Run the close paths on the real clock under a caller-chosen deadline, and pair the breach test with a control that dials the same peer and leaves the driver running. Flipping the strand off now fails the breach test, which is what makes it coverage of #1675 rather than of tokio's virtual clock. ShutdownReport carries its own denominators so is_clean() replaces a hardcoded endpoint total in the assertion, and the const assert pins the 1.5x margin its prose calls the sole derivation of SHUTDOWN_TIMEOUT, in nanoseconds. The wedge test's outer bound now rides on the same measurement as its unit deadline — a fixed bound against a scaled deadline only relocates the flake — the calibration takes the ceiling instead of failing the test under a lane-fault message when it trips its own watchdog, and it says so on stderr when the safety factor is capped. Its comment named a 20 s wedge; the wedge is 120 s. ABANDON_DRAIN_CAP is a doc-hidden re-export rather than a public module, so the one constant the test needs is the only thing exposed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01EdRw9i5zQDZEmQQnr94LJ5 * test(node): cover the reaped half of shutdown's breach line A stalled close pinned only the `closed` counter. The docstring claims both readings, and `reaped` short of N is the diagnosis that names this fixture's own defect rather than the stranded driver #1675 tracks. An abort only drops a task's future at its next poll, so a task that never yields never takes it. `spawn_blocking` parks one honestly, on a blocking-pool thread rather than a runtime worker, and waiting on a start signal first rules out the cancellation path that would reap cleanly instead. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01EdRw9i5zQDZEmQQnr94LJ5 --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Summary
PR 5 of 5 for #320 (Kademlia content discovery). Closes #320 and closes #649 (the split-out tracking issue for the iterative
FindValuelookup, ACs 12 / 13 / 14 of #320).Lands the requester-side iterative
FindValuelookup that #647'sclient::find_valuewas a primitive for, plus the negative probe cache it depends on. Stacked on #647 — base branch is set todht-bootstrap-republishso the diff here is just PR-5-specific work. After #647 merges, this PR will rebase ontomain.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_failureis the producer-side hook for the future outboundcdn/probe/v1client (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 Kademliafind_providerswith α=3 parallelism and the three ADR 022 §Lookup-integrity filters applied in order to every response:filter_xor_closer— dropcloser_nodesnot strictly closer to target than the responder itself (line 182).filter_active_stakers— drop non-staked NodeIds from bothprovidersandcloser_nodes(line 183), via theStakerSet::is_activeseam already wired by feat(node): chain-backed StakerSet + bootstrap + republish + bucket refresh (PR 4/5 of #320) #647.filter_negative_cache— drop(provider, target)pairs in the negative cache (line 184),providersonly.Termination follows textbook Kademlia: stop on
providers.len() >= kOR a full round completes without any candidate strictly closer than the current best-queried distance. Final provider list is shuffled before return — ADR 022 §186 calls randomisation "the load-bearing defense against ordering manipulation."Module wiring (
crates/node/src/dht/mod.rs): re-exportfind_providers,LookupConfig,NegativeProbeCache. No runtime wiring — PR 5 lands the primitive; the caller (cdn/client/v1 cache-miss path, issue Implement cdn/client/v1 paid delivery protocol (StreamRequest, StreamResponse, ChunkData, vouchers) #317) will constructArc<NegativeProbeCache>once at startup and pass it intofind_providersalong with the existingArc<dyn StakerSet>/Arc<Mutex<RoutingTable>>.Stays deferred
PublisherRegistry.solis on main (feat(contracts): add PublisherRegistry — namespaces and content claims #667) butOriginAssignment.solisn't, so the on-chain origin-directory fallback chain (ADR 022 §192) can't be completed yet. Follow-up alongside OriginAssignment.cdn/probe/v1client + positive probe cache (ADR 001 §93) — same probe-cache home as the negative cache eventually, but the outbound probe client is its own piece of work.NegativeProbeCache::record_failureinvocation from a real probe client — the method ships now (and is tested) but the production caller doesn't exist yet.Test plan
cargo nextest run— 1116/1116 pass (17 new: 6 negative_cache unit + 7 lookup unit + 4 lookup integration).cargo clippy --workspace --all-targets -- -D warningsclean.cargo fmt -- --checkclean.RUSTDOCFLAGS=-D warnings cargo doc --workspace --no-deps --document-private-itemsclean.pre-commit run— all hooks pass.Unit tests cover:
NegativeProbeCache: absent-key, insert→contains, TTL expiry + auto-eviction on read, LRU eviction at cap, read-hit LRU bumping, re-record refreshes TTL.filter_xor_closer: drops at-or-beyond responder distance, keeps strictly-closer.filter_active_stakers: drops non-staked, keeps staked.filter_negative_cache: drops only(provider, target)pairs present and unexpired; leavescloser_nodesuntouched.LookupState: pick-closest-α + mark queried, strictly-closer tracking, provider dedup, randomisation truncates-and-shuffles.Integration tests (multi-node loopback) cover:
(provider, target)→ empty result.Refs #320. Closes #649. Stacked on #647 (now merged; this PR is rebased onto
main).🤖 Generated with Claude Code