Skip to content

feat(node,cache): record store + Store/FindValue + cache hook (PR 3/4 of #320) - #646

Merged
thiras merged 11 commits into
mainfrom
dht-record-store
May 22, 2026
Merged

thiras merged 11 commits into
mainfrom
dht-record-store

Conversation

@thiras

@thiras thiras commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

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 PR 4 will consume. Stacked on #643.

  • crates/node/src/dht/records.rs — receiver-side RecordStore enforcing the ADR 022 §Content Records and TTL admission rules: per-publisher cap of 200 (hard reject), global cap of 100k (LRU eviction when over cap and inserting publisher is below their quota), per-hash provider cap of 50 (evict oldest holder for that hash), receiver-anchored TTL of 1 hour (refresh-in-place on re-publish), periodic GC + on-demand expiry scrub.
  • crates/node/src/dht/staker_set.rs — StakerSet trait + in-memory ConfigStakerSet (constructed with a known HashSet for tests, or ::empty() for the runtime stand-in). Chain-backed ChainStakerSet lands with PR 4 of Implement content discovery via cdn/dht/v1 Kademlia DHT #320; same trait, drop-in swap at the runtime construction site.
  • crates/node/src/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). The previous dispatch placeholder behavior is replaced; the narrowing-enum + unsupported-variant flow added in PR-2 round-2 is unchanged.
  • crates/cache/src/engine.rs — CacheEngine::subscribe_inserts() broadcast hook. Emits the committed hash from the pull_through success arm; the local-store-hit short-circuit deliberately does NOT emit (a hit doesn't start a new TTL cycle).
  • Runtime wires ConfigStakerSet::empty() with a loud startup warn; every inbound cdn/dht/v1 Store is rejected with accepted: false per ADR 022 line 140 until PR 4 ships ChainStakerSet. No TOML surface — operators don't curate a parallel staker list.

Deferred (per the approved issue-320 plan)

Test plan

  • cargo nextest run — 1068/1068 pass (20 new tests: 11 record-store, 4 staker-set, 2 cache subscribe, 3 DHT loopback store_admission).
  • cargo clippy --all-targets -- -D warnings clean.
  • cargo fmt -- --check clean.
  • pre-commit run — every hook passes (fmt, clippy, doc, deny, ADR hygiene).
  • Record-store covers: insert/refresh/quota/global LRU/per-hash cap/TTL expiry/GC sweep.
  • Cache subscribe covers: emit on pull-through, NO emit on cache hit.
  • DHT loopback covers: real Store→FindValue round-trip for staked publisher; rejection for non-staked publisher; rejection for holder != authenticated NodeId (lying-holder attack).

Refs #320. Stacked on #643.

🤖 Generated with Claude Code

thiras and others added 7 commits May 21, 2026 19:20
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]>
…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]>
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]>
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]>
Copilot AI review requested due to automatic review settings May 21, 2026 18:00

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request implements the DHT record store and active-staker filtering logic. It introduces a RecordStore to manage content records with specific admission policies, including per-publisher quotas, global LRU eviction, and receiver-anchored TTL. Additionally, it adds a StakerSet abstraction to filter publishers based on an active-staker set. The DhtHandler is updated to perform authenticated Store and FindValue operations. Feedback was provided regarding the gc method in RecordStore, suggesting an optimization to avoid a full scan by leveraging the sorted order of the LRU set to identify expired records more efficiently.

Comment thread crates/node/src/dht/records.rs Resolved

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 is the third slice of the Kademlia content-discovery stack (#320), replacing PR2’s placeholder DHT Store/FindValue behavior with a spec-driven admission pipeline backed by a new in-memory receiver-side record store, adding a staker-set abstraction for publisher admission, and exposing a cache insert broadcast hook for the upcoming republish scheduler (PR4).

Changes:

  • Add receiver-side RecordStore with ADR-022 caps/TTL semantics and integrate it into the DHT handler’s real Store admission + FindValue provider lookup.
  • Introduce StakerSet trait + ConfigStakerSet implementation and wire dht.static_active_nodes through config resolution into the runtime/handler.
  • Add CacheEngine::subscribe_inserts() broadcast hook emitting hashes on successful pull-through commits, plus tests and updated DHT loopback coverage.

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
crates/node/tests/dht_loopback.rs Expands loopback tests to cover real Store/FindValue admission/round-trips and related rejection cases.
crates/node/src/runtime/mod.rs Wires RecordStore and StakerSet into the runtime’s DHT handler construction.
crates/node/src/handlers/dht.rs Implements real responder-side Store and FindValue logic using authenticated peer identity, staker filtering, and record-store integration.
crates/node/src/dht/staker_set.rs Adds StakerSet trait and file-config-backed ConfigStakerSet implementation with unit tests.
crates/node/src/dht/records.rs Introduces the receiver-side record store with admission caps, TTL refresh, and GC APIs + unit tests.
crates/node/src/dht/mod.rs Exposes new records and staker_set modules/types.
crates/common/src/config/types.rs Adds dht.static_active_nodes field to the config schema.
crates/common/src/config/resolved.rs Adds resolved static_active_nodes: HashSet<NodeId> to ResolvedDht.
crates/common/src/config/mod.rs Parses dht.static_active_nodes via parse_node_id_hex into the resolved config.
crates/cache/src/engine.rs Adds broadcast channel + subscribe_inserts() API, emits on pull-through success, and adds tests for emit/no-emit behavior.

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

Comment thread crates/node/src/runtime/mod.rs Resolved
Comment thread crates/node/src/dht/records.rs Resolved
Comment thread crates/node/src/dht/records.rs Resolved
Comment thread crates/common/src/config/mod.rs Resolved
Comment thread crates/node/tests/dht_loopback.rs Resolved
thiras and others added 2 commits May 21, 2026 21:16
…on, 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]>
… + 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]>
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]>
@github-actions

github-actions Bot commented May 22, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 90.30% (was 90.27%, ▲ +0.03%) — 19875/22010 lines

File Coverage Lines Δ
crates/cache/src/engine.rs 93.12% 1490/1600 ▼ 0.04%
crates/common/src/config/mod.rs 96.06% 4409/4590 ● 0.00%
crates/node/src/dht/records.rs 97.23% 351/361 new
crates/node/src/dht/staker_set.rs 94.23% 49/52 new
crates/node/src/handlers/dht.rs 71.28% 201/282 ▲ +4.01%
crates/node/src/metrics.rs 83.71% 375/448 ▼ 0.24%
crates/node/src/runtime/mod.rs 51.97% 474/912 ▲ +0.69%
History
Commit Total Δ vs base
42d43e7 90.18% ▼ 0.03%
f37d4ca (HEAD) 90.30% ▲ +0.03%

…nding 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]>
@thiras
thiras merged commit 90b447b into main May 22, 2026
31 of 38 checks passed
@thiras
thiras deleted the dht-record-store branch May 22, 2026 12:46
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.

2 participants