Skip to content

feat(incentive): bound ClientReputationLedger HashMap with LRU eviction (#664) - #666

Merged
thiras merged 3 commits into
mainfrom
client-reputation-lru-bound
May 22, 2026
Merged

thiras merged 3 commits into
mainfrom
client-reputation-lru-bound

Conversation

@thiras

@thiras thiras commented May 22, 2026

Copy link
Copy Markdown
Contributor

Summary

Closes #664. Adds defense-in-depth keyspace bounding to ClientReputationLedger.

  • New ClientReputationConfig.max_tracked_clients field (default 100_000; 0 = unbounded — same sentinel convention as ResolvedSecurity::max_tracked_sources in decdn-common).
  • fold_event now distinguishes vacant vs. occupied entries; at capacity, a new client insert evicts the entry with the smallest last_seen_us (oldest observation). Updates to an existing client never evict.
  • Eviction sits inside the existing write lock — concurrent over-cap observers are single-flighted by the lock itself, so no AtomicBool/PruneGuard atomic is needed (contrast dispatch.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.
  • 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.

Threat model framing (lifted from #664)

The unbounded HashMap is not exploitable as a network-input DoS today: the cdn/client/v1 handler (#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)

  • Runtime instantiation, [client_reputation] TOML plumb, metrics registration against DecdnMetrics — all part of the cdn/client/v1 wiring.
  • DiskClientReputationStore (redb-backed ClientReputationStore impl).
  • select_nth_unstable_by_key bulk-shrink path — issue says "if ever needed"; one-entry-per-insert linear scan is sufficient at N ~ 100k.
  • Periodic GC task — the ledger has no "stale" notion (only at-capacity), so lazy-on-insert is the right shape.
  • Enforcing the cap inside 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_updates still holds its event_count == 8_000 invariant).
  • cargo clippy --all-targets -p decdn-incentive -- -D warnings clean.
  • cargo fmt -- --check clean.
  • pre-commit run — fmt, clippy, doc, deny, ADR hygiene all pass.
  • New tests cover: bounded growth under flood (lru_eviction_bounds_growth_under_flood); oldest-wins LRU correctness with EWMA preservation (lru_eviction_drops_oldest_entry); max_tracked_clients == 0 opt-out; max_tracked_clients == 1 edge case (every new address evicts, but updates to the survivor do not).

Refs #664.

🤖 Generated with Claude Code

…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]>
Copilot AI review requested due to automatic review settings May 22, 2026 12:01

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 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 (default 100_000, 0 = unbounded) and implement LRU-style eviction on new-key inserts at capacity.
  • Track process-lifetime evictions via AtomicU64 and expose tracked_clients() / evictions_total() accessors.
  • Add unit tests covering bounded growth, eviction correctness, and cap edge cases (0 and 1).

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request introduces 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.

@github-actions

github-actions Bot commented May 22, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 90.27% (was 90.21%, ▲ +0.05%) — 19333/21418 lines

File Coverage Lines Δ
crates/incentive/src/client_reputation.rs 96.71% 883/913 ▼ 0.63%
History
Commit Total Δ vs base
e37a830 90.25% ▲ +0.03%
76907ac 90.27% ▲ +0.05%
a434260 (HEAD) 90.27% ▲ +0.05%

thiras and others added 2 commits May 22, 2026 15:09
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]>
@thiras
thiras merged commit e2f67d1 into main May 22, 2026
19 checks passed
@thiras
thiras deleted the client-reputation-lru-bound branch May 22, 2026 12:20
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.

ClientReputationLedger: bound HashMap with LRU eviction by last_seen_us

2 participants