Skip to content

fix(reputation): implement ADR 008 score decay-to-neutral in the local scorer - #1425

Merged
alpergundogdu merged 2 commits into
mainfrom
claude/pr-follow-up-hitkqg
Jul 24, 2026
Merged

alpergundogdu merged 2 commits into
mainfrom
claude/pr-follow-up-hitkqg

Conversation

@alpergundogdu

@alpergundogdu alpergundogdu commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to the post-merge review on #1418 (comment).

Problem

ADR 008 § Score Decay requires local per-peer scores to decay 10% toward neutral (0.5) per idle week, and #1418's description said decay-to-neutral was kept. But that PR removed the network scorer, which is where the lazy decay_to implementation actually lived. The surviving LocalReputation stored only a bare HashMap<NodeId, f64> — no last-update timestamp, no elapsed-time math — so score() returned the raw stored value forever.

Consequence: a peer rewarded or penalized once held that selection weight for the daemon's entire lifetime instead of rehabilitating/converging back to 0.5. That directly contradicts the new local-only design's stale-opinion and exploration guarantees (a never-recently-used peer is supposed to drift back to neutral and stay selectable).

Fix

All changes are contained to crates/reputation/src/local.rs; no ADR change — the ADR was already correct, the code had regressed against it.

  • Timestamped entries. Store { score, last_update_secs } per peer and apply closed-form decay neutral + (score − neutral) · (1 − rate)^weeks lazily on record, score, and snapshot. The ADR's iterative weekly rule is exactly this closed form sampled at whole weeks.
  • Injectable clock. New Clock trait — SystemClock in production, a manual clock in tests — so decay is exercised deterministically without sleeping. The public API (new, record, score, snapshot) is unchanged, so node (node_origin.rs, runtime/mod.rs) needs no edits.
  • Monotonic timestamp. A backward clock read neither decays nor rewinds the stored update time, so a later forward read can't over-decay.
  • Config knob. decay_rate_per_week added as a validated field (default 0.10, matching the ADR; 0.0 disables), consistent with the other ADR §3 parameters already in LocalReputationConfig.
  • Bounded eviction. New evict() drops entries that have decayed within 0.05 of neutral AND been idle > 26 weeks — information-lossless (a re-seen peer just re-inserts at neutral), keeping the map bounded under peer churn. Public, best-effort maintenance; correctness never depends on it.

Tests

8 new clock-controlled tests (28/28 pass in decdn-reputation):

  • decay against the ADR week-1/5/10/20/30 examples, high seed (→ 0.95 … 0.521) and low seed (→ 0.05 … 0.479), both within 0.05 of neutral by ~30 weeks;
  • record folds from the decayed base, not the stale stored value;
  • snapshot reflects decay;
  • backward-clock safety (no decay, no timestamp rewind);
  • rate-0 freezes the score;
  • decay_rate_per_week validation;
  • evict AND-predicate boundaries (idle+neutral dropped; recent-but-non-neutral and near-neutral-but-not-idle-enough retained).

Verification

  • cargo test -p decdn-reputation — 28 passed, 0 failed
  • cargo clippy -p decdn-reputation --all-targets — clean
  • cargo fmt -p decdn-reputation -- --check — clean
  • cargo build -p decdn-node — clean (API compatibility)
  • rustdoc with -D warnings (--document-private-items) — clean

🤖 Generated with Claude Code


Generated by Claude Code

Summary by CodeRabbit

  • New Features
    • Added time-based decay for local reputation scores, gradually moving values toward neutral over time.
    • Introduced a configurable weekly decay rate (including the ability to disable decay).
    • Added eviction for inactive entries once they meet neutral-band and idle-duration criteria.
    • Updated reputation scoring and snapshots to automatically return decayed (current) values.
  • Bug Fixes
    • Added validation to reject invalid decay configuration values.

…orer

ADR 008 §Score Decay requires local per-peer scores to decay 10% toward
neutral (0.5) per idle week, and PR #1418 claimed decay-to-neutral was
kept. But the surviving `LocalReputation` stored only a bare score per
peer, with no last-update timestamp — the lazy decay implementation lived
in the deleted network scorer. As a result a peer rewarded or penalized
once held that selection weight for the daemon's entire lifetime instead
of rehabilitating toward neutral, breaking the local-only design's
stale-opinion and exploration guarantees.

Restore conformance:

- Store `{ score, last_update_secs }` per peer and apply closed-form decay
  (`neutral + (score - neutral) * (1 - rate)^weeks`) lazily on `record`,
  `score`, and `snapshot`. The iterative weekly rule in the ADR is exactly
  this closed form sampled at whole weeks.
- Inject a `Clock` (system clock in production, controllable in tests) so
  decay is exercised deterministically. The public API (`new`, `record`,
  `score`, `snapshot`) is unchanged, so `node` call sites need no edits.
- Clamp the stored timestamp monotonically so a backward clock read
  neither decays nor rewinds the update time (no later over-decay).
- Add `decay_rate_per_week` as a validated config field (default 0.10,
  matching the ADR; 0.0 disables), consistent with the other §3 params.
- Add bounded `evict()`: drop entries that have decayed within 0.05 of
  neutral AND been idle > 26 weeks, so the map stays bounded under churn.

Tests: clock-controlled decay against the ADR week-1/5/10/20/30 examples
(high and low seeds), decay-before-fold on `record`, snapshot decay,
backward-clock safety, rate-0 freeze, config validation, and the evict
AND-predicate boundaries. 28/28 pass.

Follow-up to #1418.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_019WsEEjtyfczFH4g7F4DPFK
Copilot AI review requested due to automatic review settings July 23, 2026 23:12
@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: 00071ff2-b1b5-4a16-be61-d17352eda43c

📥 Commits

Reviewing files that changed from the base of the PR and between 6a6f82c and 076d2be.

📒 Files selected for processing (1)
  • crates/reputation/src/local.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/reputation/src/local.rs

Walkthrough

Adds ADR 008 score decay to local reputation scoring, including configurable weekly decay, injected clocks, lazy score updates, neutral-entry eviction, validation, and deterministic tests for decay and clock behavior.

Changes

Local reputation decay

Layer / File(s) Summary
Decay configuration and contracts
crates/reputation/src/local.rs
Adds decay constants, the public decay_rate_per_week configuration field, defaulting and validation, plus the Clock and SystemClock APIs.
Lazy decay and eviction
crates/reputation/src/local.rs
Stores per-peer scores with update timestamps, applies closed-form decay during scoring operations, supports injected clocks, and evicts idle entries near neutral.
Deterministic decay coverage
crates/reputation/src/local.rs
Adds manual-clock helpers and tests for trajectories, disabled decay, backward clocks, folding, snapshots, eviction, defaults, and invalid rates.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant LocalReputation
  participant Clock
  Caller->>LocalReputation: score or record peer
  LocalReputation->>Clock: now_secs()
  Clock-->>LocalReputation: current timestamp
  LocalReputation->>LocalReputation: decay stored score toward neutral
  LocalReputation-->>Caller: decayed score or folded update
Loading

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

Comment @coderabbitai help to get the list of available commands.

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

Implements ADR 008 score decay-to-neutral for the local-only reputation scorer by timestamping per-peer entries and applying a lazy closed-form decay on reads and updates, with deterministic testing via an injectable clock.

Changes:

  • Store { score, last_update_secs } per peer and apply decay toward neutral based on elapsed idle time in record, score, and snapshot.
  • Add a configurable decay_rate_per_week (default 0.10) plus a best-effort evict() to bound map growth under churn.
  • Introduce a Clock abstraction (SystemClock + test manual clock) and add comprehensive decay/eviction tests.

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

Comment thread crates/reputation/src/local.rs Outdated
Comment on lines +160 to +163
/// A clock before the Unix epoch (or a `duration_since` error) reads as `0`,
/// which the decay math treats as maximal age; a genuine pre-1970 host is not
/// a real deployment, so this can only ever over-decay a freshly seeded score
/// toward neutral — never inflate one.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 076d2be — reworded the SystemClock doc to describe the actual conservative behavior: because decay saturates elapsed time at 0, a 0 read yields no decay rather than over-decaying.

Comment on lines +240 to +243
// Clamp the effective "now" so a backward clock read never rewinds
// `last_update_secs`, which would make a later `score()` apply extra
// decay. `decay_to` also saturates elapsed at 0; this keeps the stored
// timestamp monotonic too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 076d2be — corrected decay_to to decay.

@github-actions

github-actions Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 81.13% (was 81.07%, ▲ +0.05%) — 52607/64846 lines

File Coverage Lines Δ
crates/reputation/src/local.rs 98.99% 587/593 ▼ 0.50%
History
Commit Total Δ vs base
6a6f82c 81.05% ▲ +0.04%
076d2be (HEAD) 81.13% ▲ +0.05%

…er name

Address PR #1425 review: the SystemClock rustdoc claimed a pre-epoch
clock read over-decays toward neutral, but decay() saturates elapsed at
0, so a 0 read yields no decay. Fix the doc to describe the actual
conservative behavior, and correct a stale decay_to reference to decay.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alpergundogdu
alpergundogdu merged commit fa8f606 into main Jul 24, 2026
24 checks passed
@alpergundogdu
alpergundogdu deleted the claude/pr-follow-up-hitkqg branch July 24, 2026 15:45
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.

3 participants