Repository navigation
feat(incentive): add ClientReputationLedger building block (#482) - #663
Conversation
Implements the node-local acceptance-policy primitive from ADR 003
§Corrupted delivery: a per-`channel.client` Ethereum-address EWMA in
[0.0, 1.0] (matching the ADR 008 §3 per-peer fold rule, α=0.1, sample
1.0 on voucher received / 0.0 on withheld) plus a three-tier
Admission decision — Accept / AcceptCapped { byte_cap } / Reject —
that maps the score onto the ADR's "trusted / cap-bytes / refuse"
rungs. Unseen clients land in the capped tier with the new-client cap.
Shape mirrors the existing channel-store seam in this crate:
- `ClientReputationLedger` owns the in-memory `RwLock<HashMap<…>>`
of per-client EWMA state, exposing `record_voucher_received` /
`record_voucher_withheld` / `admit` / `score` / `snapshot` / `entry`
/ `from_snapshot` (the hydration path for a future redb-backed store);
- `ClientReputationStore` trait + `MemoryClientReputationStore` test
impl mirror `ChannelStateStore` / `MemoryChannelStateStore` and
re-use the existing `StoreError` enum from `crates/incentive/src/store.rs`
rather than introducing a parallel error type.
Scope is deliberately the leaf primitive only — no `crates/common`
config slot, no `crates/node` redb impl, no runtime instantiation.
The natural consumer is the `cdn/client/v1` paid-delivery handler
tracked under #317 (currently blocked); building the ledger now
means it is reviewed, tested, and ready to wire the moment that
handler lands. 18 unit tests cover EWMA convergence in both
directions, tier boundaries (inclusive on both `>=` thresholds),
unseen-client admission, snapshot hydration with corrupt-row skip,
the memory store's load_all / record / forget contract, and an
8-thread × 1000-event concurrency check that asserts no torn
read-modify-writes.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
Adds a new node-local “client reputation” building block to decdn-incentive to support future admission/acceptance policy decisions in the paid delivery path (cdn/client/v1), tracking per-client voucher completion EWMA and mapping it to a 3-tier Admission outcome.
Changes:
- Introduces
ClientReputationLedgerwith EWMA folding (record_voucher_received/record_voucher_withheld) andAdmissiondecision logic (admit). - Adds
ClientReputationStoretrait plusMemoryClientReputationStorefor persistence seam parity withChannelStateStore. - Re-exports the new types from
crates/incentive’s public API.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| crates/incentive/src/lib.rs | Exposes the new client reputation module and re-exports its public types. |
| crates/incentive/src/client_reputation.rs | Implements the ledger/config/admission model, store trait + memory store, and unit tests. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Coverage reportTotal: 90.29% (was 90.05%, ▲ +0.24%) — 17748/19656 lines
History
|
There was a problem hiding this comment.
Code Review
This pull request introduces a node-local client reputation ledger that implements EWMA-based scoring to manage client admission tiers according to ADR 003. Feedback highlights a potential DoS vulnerability due to the unbounded in-memory storage of reputation state, suggesting the implementation of capacity limits and eviction logic. Additionally, a documentation update was recommended to clarify edge cases where the last seen timestamp might be zero due to system clock settings.
Address three Copilot inline comments and one Gemini doc comment: - alpha == 0.0 was accepted by the closed-interval check but freezes the EWMA at initial_score for every future event — silently disables the ledger. The doc was already `(0.0, 1.0]`; add a dedicated ConfigError::AlphaCannotBeZero guard so validation matches the doc. - `admit` treated a hydrated entry with `event_count == 0` as a known borderline client (resolved by `completion_ratio`), not as unseen — so a snapshot round-trip of a default-constructed row would land in the wrong tier when `borderline_cap_bytes != new_client_cap_bytes`. Treat `event_count == 0` as unseen so persistence layers don't have to distinguish "never inserted" from "default row". - ClientReputationStore::load_all docs said corrupt entries should return StoreError; the ledger's design tolerates skipping invalid rows. Clarify that backend-level failures (truncated frame, bad magic) return StoreError but logically-invalid payloads SHOULD be skipped silently — aligns the trait contract with `from_snapshot`'s existing skip-on-invalid behavior. - `last_seen_us == 0` is ambiguous between "never observed" and a system clock behind the UNIX epoch (where the internal time helper saturates to 0). Doc now notes the edge case and points to `event_count` as the unambiguous "never observed" signal. Test updates: existing boundary test seeds `event_count: 1`; new `default_constructed_entry_treated_as_unseen` exercises the round-trip with `new_client_cap_bytes != borderline_cap_bytes` so the two paths are distinguishable. 19 tests pass (was 18). Gemini's high-priority DoS comment on the unbounded HashMap is filed as #664 for the runtime-wiring PR — the eviction policy needs live signals (last_seen_us, score) that this leaf-primitive PR has no consumer for; Sybil resistance is structural via L2 channel-open cost in the meantime. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Address the nine items raised by the parallel review-agent pass on PR #663 (code-reviewer, pr-test-analyzer, comment-analyzer, silent-failure-hunter, type-design-analyzer): - MemoryClientReputationStore::load_all now honours the trait's SHOULD-skip contract: drops rows whose completion_ratio is non-finite or outside [0.0, 1.0]. The memory impl is mostly a reference shape for the future redb impl reviewer, but the previous unfiltered behaviour made the trait self-inconsistent with its own docstring. - from_snapshot emits tracing::warn! per skipped row and tracing::info! with loaded/skipped counts at completion, so a redb migration that corrupts rows surfaces in the log instead of presenting as silent re-convergence from initial_score. - from_snapshot dead poison-recovery on a brand-new lock removed; the HashMap is built first, then the constructor takes ownership of it via RwLock::new(map) directly. - Module doc EWMA-equivalence claim qualified to mention the max_delta_per_update clamp the reputation crate carries and this ledger omits (math collapses at α=1, sample∈{0,1}). - ConfigError::ZeroCap variant + validate() guard for new_client_cap_bytes > 0 and borderline_cap_bytes > 0; a zero cap would silently degrade AcceptCapped to a functional Reject. - Admission is #[must_use] with an explanatory message; a careless cdn/client/v1 handler can no longer pattern-match `Accept | AcceptCapped { .. } => serve()` and silently strip the byte_cap deterrent. - last_seen_us doc consolidated; the redundant struct-level and field- level restatements were collapsed and the canonical "never observed" signal is now consistently event_count == 0 across module doc, struct doc, field doc, and admit doc. - admit body cleaned up: redundant inline rationale removed, both unseen branches share one named local. - concurrent_record_does_not_lose_updates restructured so the event_count == 8000 invariant is the headline assertion (a lost read-modify-write would skip an increment); the EWMA decay check is kept as a softer sanity signal with its weaker reach acknowledged in the test comment. New tests (26 total, was 19; +7): - alpha_one_replaces_score_with_sample (boundary on the α∈(0,1] range) - accept_threshold_one_is_valid_config (boundary on the [0,1] range) - zero_cap_config_rejected (covers both ZeroCap variants) - from_snapshot_skips_infinity_and_negative_completion_ratio (extends corruption coverage beyond NaN/2.0; also pins that -0.0 is NOT skipped, since it compares equal to 0.0 in the bounds check) - from_snapshot_empty_iterator_yields_empty_ledger (first-boot path) - counters_saturate_instead_of_wrapping (seeds u64::MAX - 1, asserts saturation rather than wrap on event_count + total_bytes_delivered) - memory_store_load_all_filters_invalid_rows (verifies the new skip filter on the memory impl) Explicitly NOT changing in this PR (verified, reasoned, deferred): - Private fields + constructor on ClientReputation / ClientReputationConfig. The workspace pattern is consistently pub-fields + validated-constructor (ChannelState at channel.rs:43-64, LocalReputationConfig at local.rs:75-99). With the load_all and from_snapshot filters in place, every external ingress is closed — the private `state` map is unreachable from outside the struct. Refactoring to private fields would deviate from the workspace pattern, not follow it. - event_count: Option<NonZeroU64> sentinel structuralisation. Would change the persistence layout before persistence is wired (#664 / #317 follow-up), purely speculative. - Counter-saturation tracing on event_count / total_bytes_delivered. Saturation thresholds are astronomical (9.2 quintillion events, 16 EiB delivered) and the realistic vector — a caller passing u64::MAX bytes — is a caller-contract violation, not a ledger concern. Adding first-saturation detection needs cross-call state for an unrealistic scenario. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…on (#664) (#666) * feat(incentive): bound ClientReputationLedger HashMap with LRU eviction (#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]> * fix(incentive): poison-recovery for tracked_clients + cap from_snapshot 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]> * chore(incentive): post-review tightening for #666 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]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Closes #482 (building-block scope; see "Deferred" below).
Implements the node-local acceptance-policy primitive from ADR 003 §Corrupted delivery:
channel.client(Ethereum funder address) EWMA in[0.0, 1.0], matching the per-peer fold rule incrates/reputation/src/local.rs(ADR 008 §3 default α = 0.1). Sample is1.0on voucher received,0.0on withheld — bytes are tracked separately on a saturating observability counter, not folded into the score.Admissiondecision (Accept/AcceptCapped { byte_cap }/Reject) mapping the score onto the ADR's "trusted / cap-bytes / refuse" rungs. Unseen clients land inAcceptCappedwith the new-client cap (default 1 GiB) until a run of completed vouchers lifts the score aboveaccept_threshold(default 0.70). Thresholds and caps are all knobs onClientReputationConfig.ClientReputationStoretrait +MemoryClientReputationStoremirror the existingChannelStateStore/MemoryChannelStateStorepair (crates/incentive/src/store.rs) and re-use the existingStoreErrorenum rather than introducing a parallel error type.Scope (deliberately the leaf primitive only)
crates/incentive/src/client_reputation.rs— ledger, EWMA, Admission, trait, memory impl, 18 unit testsDiskClientReputationStoreincrates/node(mirrorscrates/node/src/channel_store.rs)crates/incentive/src/lib.rs— public re-exportsResolvedClientReputationincrates/common/src/config/resolved.rscdn/client/v1handler (#317)The natural consumer is the
cdn/client/v1paid-delivery handler tracked under #317, which is currentlyblocked. Building this primitive now means it is reviewed, tested, and ready to wire the moment #317 unblocks — without doing anything cross-crate or producing dead instantiation code in the meantime.Why these defaults
accept = 0.70/reject = 0.30/α = 0.1/new_client_cap = borderline_cap = 1 GiB. With α = 0.1 the EWMA half-life is ~6.6 events, which approximates the issue's "last ~10 streams" intuition without an explicit rolling window. New clients are not auto-rejected — they getAcceptCapped(the cap-bytes-for-unestablished-history rung in the ADR) so legitimate first-time funders are not locked out. Every threshold is a config knob; the resolver wiring to expose them to operators ships in the follow-up.Test plan
cargo build -p decdn-incentivecleancargo clippy -p decdn-incentive --all-targets -- -D warningsclean (workspace deniesunwrap_used,expect_used,panic,indexing_slicing; the module usesunwrap_or_else(PoisonError::into_inner)for the read-locks and?propagation in tests)cargo nextest run -p decdn-incentive— 89/89 pass, including 18 new inclient_reputation::tests:>=thresholdsrecord_*returns post-update score, not prevfrom_snapshotskips non-finite / out-of-range entriesevent_count == 8000cargo fmt -- --checkcleanpre-commit runon changed files clean (fmt, clippy, cargo doc, cargo deny)No CI-relevant files outside
crates/incentivechange; this should be a clean rust-only PR with no contract or ADR-book hook activity.🤖 Generated with Claude Code