Repository navigation
feat(incentive): bound ClientReputationLedger HashMap with LRU eviction (#664) - #666
Conversation
…on (#664) Adds `max_tracked_clients` (default 100_000; `0` = unbounded) to `ClientReputationConfig` and wires lazy LRU-by-`last_seen_us` eviction into `fold_event` so a new client at capacity evicts the entry with the oldest observation. Existing-client updates never evict — the `is_new` gate prevents the ledger from displacing live EWMA state. The eviction sits inside the existing write lock, so concurrent over-cap observers are single-flighted by the lock itself; no separate `AtomicBool`/PruneGuard is needed (contrast `dispatch.rs::ConnectionLimiter`, which prunes from a read-lock path and requires one). Two public accessors — `tracked_clients()` and `evictions_total()` — let the runtime metrics layer publish `decdn_client_reputation_tracked_clients` (gauge) and `decdn_client_reputation_evictions_total` (counter) without pulling `iroh-metrics` into this leaf crate. Runtime registration lands with the `cdn/client/v1` wiring (#317). Defense-in-depth for the Gemini high-priority comment on PR #663: each new client address costs the attacker an L2 channel-open (USDC deposit + gas), so Sybil growth is structurally rate-limited per ADR 003 §Corrupted delivery; this bound caps in-memory growth in the worst case the structural deterrent fails to hold. Refs #664. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
This PR adds a defense-in-depth bound to the in-memory ClientReputationLedger keyspace by introducing a max_tracked_clients config knob and evicting the least-recently-seen client (by last_seen_us) when inserting a new client at capacity. It also exposes lightweight accessors so the node runtime can publish reputation-ledger metrics without adding an iroh-metrics dependency to this crate.
Changes:
- Add
ClientReputationConfig.max_tracked_clients(default100_000,0= unbounded) and implement LRU-style eviction on new-key inserts at capacity. - Track process-lifetime evictions via
AtomicU64and exposetracked_clients()/evictions_total()accessors. - Add unit tests covering bounded growth, eviction correctness, and cap edge cases (
0and1).
💡 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 introduces a configurable limit on the number of tracked client addresses in the ClientReputationLedger, implementing an LRU eviction policy to prevent unbounded memory growth. It also adds metrics for tracking the current number of clients and total evictions, along with comprehensive unit tests. The review feedback suggests a minor refinement to the tracked_clients method to ensure consistent handling of poisoned locks, which maintains metric availability.
Coverage reportTotal: 90.27% (was 90.21%, ▲ +0.05%) — 19333/21418 lines
History
|
Two PR-review fixes for #666: - `tracked_clients()` now uses `unwrap_or_else(PoisonError::into_inner)` to match `admit`/`score`/`entry`/`snapshot`/`fold_event`. Returning `0` on a poisoned lock would silently crater the operator gauge after an unrelated panic — Copilot + Gemini both flagged it. - `from_snapshot()` now enforces `max_tracked_clients` at hydration time using `select_nth_unstable_by_key` to drop the entries with the smallest `last_seen_us`. Without this the cap was only a hard invariant on `record_*` paths — a torn or outdated store could re-introduce the unbounded-map shape the cap exists to prevent. Bulk-truncation count is folded into `evictions_total` so the operator metric reflects the hydration loss. Two new tests cover the from_snapshot path: - `from_snapshot_enforces_cap_keeping_newest_by_last_seen_us` - `from_snapshot_zero_cap_skips_hydration_truncation` 105/105 incentive tests pass; clippy + fmt + pre-commit clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Three review findings from the comprehensive review pass:
- `from_snapshot` bulk truncation now emits its own `tracing::warn!`
separate from the routine `info` summary. The docstring already
frames over-cap hydration as "the unbounded shape reappearing" —
that's an integrity signal an operator should hear, not a count
buried in the happy-path summary. Surfaced by silent-failure-hunter.
- `lru_eviction_drops_oldest_entry` now also asserts that an evicted
address re-admits as `AcceptCapped { new_client_cap_bytes }` (not a
zero-event ghost) and that re-recording it folds from `initial_score`
(not the decayed pre-eviction value). Surfaced by pr-test-analyzer.
- Dropped the "the issue scope calls out for 'if ever needed'" comment
in `from_snapshot` — direct violation of the project's "don't
reference current task/issue" rule. Refactored the cap-shrink path
out into a private `truncate_to_cap` helper, which also resolved a
cognitive-complexity clippy lint that fired after the warn split.
- Softened the speculative "order-of-magnitude estimate of concurrent
unique payers" claim in the `DEFAULT_MAX_TRACKED_CLIENTS` doc.
103/103 incentive tests pass; clippy + fmt + pre-commit clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Closes #664. Adds defense-in-depth keyspace bounding to
ClientReputationLedger.ClientReputationConfig.max_tracked_clientsfield (default100_000;0= unbounded — same sentinel convention asResolvedSecurity::max_tracked_sourcesindecdn-common).fold_eventnow distinguishes vacant vs. occupied entries; at capacity, a new client insert evicts the entry with the smallestlast_seen_us(oldest observation). Updates to an existing client never evict.AtomicBool/PruneGuard atomic is needed (contrastdispatch.rs::ConnectionLimiter, which prunes from a read-lock path and requires one). Linear scan is fine at the 100k default cap and bounded to one scan per new-key insert.tracked_clients()andevictions_total()— let the runtime metrics layer publishdecdn_client_reputation_tracked_clients(gauge) anddecdn_client_reputation_evictions_total(counter) without pullingiroh-metricsinto this leaf crate.Threat model framing (lifted from #664)
The unbounded
HashMapis not exploitable as a network-input DoS today: thecdn/client/v1handler (#317) is the future live consumer, and a stream requires an open payment channel — an L2 transaction with USDC deposit and gas cost (ADR 003 §Payment Channel Open / Close). "Sybil resistance is structural" via channel-open cost is exactly the framing in #482; each new ledger key costs the attacker an on-chain channel open.This PR is the deferred hardening: cap the in-memory growth in the worst case the structural deterrent fails to hold. The eviction policy benefits from real signals —
last_seen_us— that PR #663 already maintained on every update.Out of scope (lands with #317)
[client_reputation]TOML plumb, metrics registration againstDecdnMetrics— all part of thecdn/client/v1wiring.DiskClientReputationStore(redb-backedClientReputationStoreimpl).select_nth_unstable_by_keybulk-shrink path — issue says "if ever needed"; one-entry-per-insert linear scan is sufficient at N ~ 100k.from_snapshot— the runtime writes through the bounded ledger once wired, so the persistence-side cap is purely defensive against a torn store. If reviewers want it added, happy to do so.Test plan
cargo nextest run -p decdn-incentive— 101/101 pass (four new LRU tests;concurrent_record_does_not_lose_updatesstill holds itsevent_count == 8_000invariant).cargo clippy --all-targets -p decdn-incentive -- -D warningsclean.cargo fmt -- --checkclean.pre-commit run— fmt, clippy, doc, deny, ADR hygiene all pass.lru_eviction_bounds_growth_under_flood); oldest-wins LRU correctness with EWMA preservation (lru_eviction_drops_oldest_entry);max_tracked_clients == 0opt-out;max_tracked_clients == 1edge case (every new address evicts, but updates to the survivor do not).Refs #664.
🤖 Generated with Claude Code