Repository navigation
feat: network reputation gossip aggregation + settlement indexer (#326) - #832
Conversation
Implement ADR 008 network reputation end to end: - protocol: signed `ReputationReport`/`ReportMetrics` at the frozen GossipPayload discriminant 1. - reputation: the aggregation engine (reporter weight w/ distinct-counterparty diversity discount + exponential time decay + 3x cap, ±0.05 per-report clamp, 10%/wk decay, 3-distinct-reporter threshold, combined 0.7/0.3) and the derived regional-coverage signal; pure, trait-abstracted, unit-tested. - gossip: cdn/reputation/v1 subscribe/publish, signature+recency validation, receiver-enforced rate limiting, and the ReputationSink/ReportDrain/ StakedReporterSet seams (gossip stays leaf w.r.t. the scoring engine). - node: a network-wide ChannelSettled indexer that resolves both parties via CapacityBond.nodeIdOf and feeds reporter-credibility weights; admin_v1_reputation RPC + `decdn node reputation <node-id>` CLI; config knobs gossip.subscribe_reputation / reputation_publish_interval_sec; indexer metrics and a periodic eviction sweep that bound the in-memory maps. Deferred to #831 (gated on the unbuilt node-to-node cache-miss pull-through orchestration): outbound report capture (feeding the observation buffer from delivery/probe outcomes) and node selection consuming the combined score. The node currently aggregates inbound reports and serves scores but does not yet emit reports or let reputation influence provider selection. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request implements network-wide reputation aggregation and regional-coverage signals (ADR 008) by introducing a new CLI reputation command, an admin RPC endpoint, a gossip transport layer for reputation reports, and an on-chain settlement indexer to compute reporter credibility weights. Feedback on the changes highlights three critical issues: a correctness bug in the settlement indexer where transient RPC errors during startup can cause the initial backfill to be permanently skipped; another bug where transient RPC failures during address resolution permanently prevent crediting a settlement; and a performance bottleneck on the gossip subscriber hot path due to an expensive O(N) scan performed for every accepted report.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
There was a problem hiding this comment.
Pull request overview
Implements ADR-008 network reputation end-to-end across protocol, gossip transport, reputation engine, and node wiring, including a settlement-driven reporter-weight indexer plus admin/CLI introspection and related config/metrics.
Changes:
- Extend gossip protocol with signed
ReputationReportpayloads and add validation + receiver-side rate limiting oncdn/reputation/v1. - Add
decdn-reputationengine modules for settlement-weighting, network aggregation/decay, regional coverage, and outbound observation buffering. - Wire node runtime with a network-wide on-chain settlement indexer, reputation aggregation state, new metrics, and an admin/CLI endpoint to query scores/coverage.
Reviewed changes
Copilot reviewed 29 out of 29 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/reputation/src/settlement.rs | Pure settlement-based reporter weighting (decay + diversity discount) with unit tests. |
| crates/reputation/src/observation.rs | Coalescing in-memory buffer for outbound report observations. |
| crates/reputation/src/network.rs | Network-score EWMA aggregation + decay/eviction + combined-score helper. |
| crates/reputation/src/local.rs | Refactor local scoring to use shared interaction formula helpers. |
| crates/reputation/src/lib.rs | Expose new reputation modules and public API re-exports. |
| crates/reputation/src/interaction.rs | Centralize shared interaction-score and speed normalization arithmetic. |
| crates/reputation/src/coverage.rs | Regional coverage signal derived from validated network reports. |
| crates/protocol/src/lib.rs | Re-export new protocol types for reputation reporting. |
| crates/protocol/src/gossip.rs | Add GossipPayload::ReputationReport and define signed report/body/metrics. |
| crates/node/tests/sighup_signal.rs | Update config seed to include reputation gossip fields. |
| crates/node/src/runtime/reload.rs | Include reputation gossip fields in resolved config + ignored-section warning. |
| crates/node/src/runtime/mod.rs | Wire reputation aggregation, gossip reputation topic config, indexer spawn, eviction sweep, admin handles. |
| crates/node/src/reputation_wiring.rs | Implement node-side trait seams: staked gate, settlement source, sink, and report drain. |
| crates/node/src/reputation_indexer.rs | Add network-wide chain watcher/backfill to feed settlement history for reporter weights. |
| crates/node/src/metrics.rs | Add settlement indexer observability counters + bump helpers. |
| crates/node/src/lib.rs | Export new reputation_indexer and reputation_wiring modules. |
| crates/node/src/admin.rs | Add admin_v1_reputation handler + node-id parsing and tests. |
| crates/gossip/src/validation.rs | Make NodeAnnounce validator explicitly reject non-announce payload variants. |
| crates/gossip/src/service.rs | Add reputation topic subscriber/publisher tasks, wiring, and publish trigger. |
| crates/gossip/src/reputation.rs | Reputation envelope validation + rate limiting + trait seams for sink/staker/drain. |
| crates/gossip/src/lib.rs | Re-export reputation transport types and wiring handles. |
| crates/common/src/config/types.rs | Add TOML config fields for reputation gossip enable + publish interval. |
| crates/common/src/config/resolved.rs | Add resolved config fields for reputation gossip enable + publish interval. |
| crates/common/src/config/mod.rs | Resolve defaults/validation for new reputation gossip config fields + tests. |
| crates/common/src/cli/node.rs | Add decdn node reputation CLI subcommand args. |
| crates/common/src/cli/mod.rs | Re-export ReputationArgs from CLI module. |
| crates/common/src/admin.rs | Add admin request/response structs + error code for reputation endpoint. |
| crates/cli/tests/config_validate.rs | Extend resolved-config test fixture with reputation gossip fields. |
| crates/cli/src/commands/node.rs | Implement decdn node reputation command + output formatting tests. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Coverage reportTotal: 86.29% (was 87.46%, ▼ 1.17%) — 32768/37974 lines
History
|
…, API snapshot CI: regenerate decdn-protocol public-API snapshot for the new ReputationReport / ReputationReportBody / ReportMetrics surface (the only failing check). Review fixes: - reputation_indexer: don't clear `backfill_from` until the whole backfill window succeeds, so a transient RPC error retries the backfill instead of silently skipping it (Gemini high). - reputation_indexer: `resolve_binding` / `process_settled` now return `Result`; a transient `nodeIdOf` RPC error propagates to the watcher's backoff-and-retry and the channel is NOT marked seen, so the settlement is retried rather than permanently dropped. Genuinely unbound keys and amount overflow stay fail-closed (Ok(None) / marked seen) (Gemini high). - reputation_wiring: cache `max_effective_settled_value` behind a 60s TTL, invalidated on each recorded settlement, so the O(reporters×records) scan no longer runs once per accepted gossip report (gossip hot-path DoS) (Gemini high / Copilot). - network: stop inserting into `distinct_reporters` once the threshold is met to bound per-provider memory under large networks (Copilot). - docs: correct the `staked_counterparty` comment (current-membership proxy, not at-settlement-time) and the runtime comment claiming the reputation publisher already runs (it isn't spawned while report_drain is None) (Copilot). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…c/metric accuracy Addresses findings from the multi-agent review of the prior fix commit: - reputation_indexer: a transient resolution error on a *live* ChannelSettled event re-arms `backfill_from` from that event's block before returning Err, so the resubscribe re-queries the window instead of losing the event at `.watch()` head (the previous fix only retried the backfill path). The process_settled doc no longer overstates the guarantee (silent-failure HIGH). - metrics: correct the reputation_indexer_rpc_failures doc — a resolution failure no longer "skips a party"; both stream and resolution errors now share the backoff/resubscribe path, so the counter measures watcher-cycle terminations (silent-failure MEDIUM). - reputation_indexer: the amount-overflow warn now includes routed_amount (silent-failure LOW). - reputation_wiring: replace the `computed_at_secs == 0` sentinel with `RwLock<Option<CachedMax>>` so a pre-epoch clock can't masquerade as stale, and document the cache's reliance on immutable min_counterparties + the bounded best-effort invalidation race (type-design + code-reviewer suggestions). - reputation (settlement.rs): align the leaf-crate SettlementRecord doc — how "staked" is resolved (current vs at-settlement membership) is the source's concern, not "at settlement time" (comment-analyzer drift). - network: add cap_does_not_regress_threshold_above_min_reporters — proves the distinct_reporters insertion cap keeps the peer scored and still folds post-threshold reports into the EWMA (test GAP-2). Follow-up noted (not in this commit): a mocked-transport unit test for process_settled's transient-error-no-mark-seen vs permanent-resolve-mark-seen contract (test GAP-1) needs an alloy mock provider harness with no repo precedent; the pure crediting logic remains covered via apply_settlement. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request implements the network reputation aggregation and gossip transport system (ADR 008), including an on-chain settlement indexer to weight reporter credibility and a new decdn node reputation CLI command and admin RPC endpoint. Feedback suggests optimizing the sorting of regions in the admin RPC response by using sort_unstable_by instead of stable sorting, as the keys are unique.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
Resolve remaining PR #832 review threads: - network::record and coverage::record stored `last_update_secs`/ `last_interaction_at` directly from the report's `now`, so an out-of-order or backward-clock report rewound the timestamp into the past and a later `score`/`coverage` read applied extra decay. Clamp the effective now to `max(now, stored)` for both the decay computation and the stored timestamp, completing decay_to's existing "clock backwards yields no decay" intent (Copilot). Added regression tests on both paths. - admin::reputation uses sort_unstable_by for the region list (unique keys, no stability needed) (Gemini). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
c568752 to
4d47235
Compare
…ossip-aggregation # Conflicts: # crates/node/src/metrics.rs
#831) (#834) * feat: network reputation gossip aggregation + settlement indexer (#326) Implement ADR 008 network reputation end to end: - protocol: signed `ReputationReport`/`ReportMetrics` at the frozen GossipPayload discriminant 1. - reputation: the aggregation engine (reporter weight w/ distinct-counterparty diversity discount + exponential time decay + 3x cap, ±0.05 per-report clamp, 10%/wk decay, 3-distinct-reporter threshold, combined 0.7/0.3) and the derived regional-coverage signal; pure, trait-abstracted, unit-tested. - gossip: cdn/reputation/v1 subscribe/publish, signature+recency validation, receiver-enforced rate limiting, and the ReputationSink/ReportDrain/ StakedReporterSet seams (gossip stays leaf w.r.t. the scoring engine). - node: a network-wide ChannelSettled indexer that resolves both parties via CapacityBond.nodeIdOf and feeds reporter-credibility weights; admin_v1_reputation RPC + `decdn node reputation <node-id>` CLI; config knobs gossip.subscribe_reputation / reputation_publish_interval_sec; indexer metrics and a periodic eviction sweep that bound the in-memory maps. Deferred to #831 (gated on the unbuilt node-to-node cache-miss pull-through orchestration): outbound report capture (feeding the observation buffer from delivery/probe outcomes) and node selection consuming the combined score. The node currently aggregates inbound reports and serves scores but does not yet emit reports or let reputation influence provider selection. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(node): address #832 review — indexer retry, gossip hot-path cache, API snapshot CI: regenerate decdn-protocol public-API snapshot for the new ReputationReport / ReputationReportBody / ReportMetrics surface (the only failing check). Review fixes: - reputation_indexer: don't clear `backfill_from` until the whole backfill window succeeds, so a transient RPC error retries the backfill instead of silently skipping it (Gemini high). - reputation_indexer: `resolve_binding` / `process_settled` now return `Result`; a transient `nodeIdOf` RPC error propagates to the watcher's backoff-and-retry and the channel is NOT marked seen, so the settlement is retried rather than permanently dropped. Genuinely unbound keys and amount overflow stay fail-closed (Ok(None) / marked seen) (Gemini high). - reputation_wiring: cache `max_effective_settled_value` behind a 60s TTL, invalidated on each recorded settlement, so the O(reporters×records) scan no longer runs once per accepted gossip report (gossip hot-path DoS) (Gemini high / Copilot). - network: stop inserting into `distinct_reporters` once the threshold is met to bound per-provider memory under large networks (Copilot). - docs: correct the `staked_counterparty` comment (current-membership proxy, not at-settlement-time) and the runtime comment claiming the reputation publisher already runs (it isn't spawned while report_drain is None) (Copilot). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(node): second review pass — live-event retry, cache as Option, doc/metric accuracy Addresses findings from the multi-agent review of the prior fix commit: - reputation_indexer: a transient resolution error on a *live* ChannelSettled event re-arms `backfill_from` from that event's block before returning Err, so the resubscribe re-queries the window instead of losing the event at `.watch()` head (the previous fix only retried the backfill path). The process_settled doc no longer overstates the guarantee (silent-failure HIGH). - metrics: correct the reputation_indexer_rpc_failures doc — a resolution failure no longer "skips a party"; both stream and resolution errors now share the backoff/resubscribe path, so the counter measures watcher-cycle terminations (silent-failure MEDIUM). - reputation_indexer: the amount-overflow warn now includes routed_amount (silent-failure LOW). - reputation_wiring: replace the `computed_at_secs == 0` sentinel with `RwLock<Option<CachedMax>>` so a pre-epoch clock can't masquerade as stale, and document the cache's reliance on immutable min_counterparties + the bounded best-effort invalidation race (type-design + code-reviewer suggestions). - reputation (settlement.rs): align the leaf-crate SettlementRecord doc — how "staked" is resolved (current vs at-settlement membership) is the source's concern, not "at settlement time" (comment-analyzer drift). - network: add cap_does_not_regress_threshold_above_min_reporters — proves the distinct_reporters insertion cap keeps the peer scored and still folds post-threshold reports into the EWMA (test GAP-2). Follow-up noted (not in this commit): a mocked-transport unit test for process_settled's transient-error-no-mark-seen vs permanent-resolve-mark-seen contract (test GAP-1) needs an alloy mock provider harness with no repo precedent; the pure crediting logic remains covered via apply_settlement. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(reputation): clamp decay clock against backward/out-of-order reports Resolve remaining PR #832 review threads: - network::record and coverage::record stored `last_update_secs`/ `last_interaction_at` directly from the report's `now`, so an out-of-order or backward-clock report rewound the timestamp into the past and a later `score`/`coverage` read applied extra decay. Clamp the effective now to `max(now, stored)` for both the decay computation and the stored timestamp, completing decay_to's existing "clock backwards yields no decay" intent (Copilot). Added regression tests on both paths. - admin::reputation uses sort_unstable_by for the region list (unique keys, no stability needed) (Gemini). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(node): node-to-node cache-miss pull-through + outbound reputation (#831) Builds the production node-to-node pull-through orchestration and wires ADR-008 outbound reputation capture + reputation-consuming selection on top of it. Gated behind `cache.node_to_node_pull_through_enabled` (default OFF). Orchestration (`NodeOrigin`, an `Origin` impl appended last in the cache chain): on a miss it discovers providers (DHT `find_providers` + origin-directory fallback), probes each for rate/RTT, ranks them by the combined local+network reputation score, opens/reuses a buyer channel, and paid-pulls via `stream_fetch` with `MAX_PROVIDER_ATTEMPTS` fallback. The cache engine verifies + ingests the bytes. - `dht::node_address::ChainNodeAddressDirectory`: resolves a provider `NodeId` to its bonded operator address from the same `CapacityBond` data the staker set reads (`getActiveNodes`/`NodeRegistered` carry `ethAddress`) — needed to open the channel and verify `slash_sig`. - `buyer_channel::ChannelOpener`: object-safe seam erasing `BuyerChannelService<P>`'s provider generic. - `probe_client`: node-side copy of the transport-only `probe_once`. - Outbound capture: each pull/probe outcome folds into `LocalReputation` + the `ObservationBuffer`; `report_drain` is wired when the feature is on, so the gossip publisher emits reports about pulled-from upstreams. - Selection consumes `combined_score(local, network, cfg)`. - `OriginKind::Peer` tags the (USDC-billed) network origin. Delivery-path hook (`handlers/client`): a cache miss triggers the pull only for a request that PROVES ownership of the named channel (a verified binding matching the channel's client) — channel ids are public, so existence cannot authorize spend; this closes the unpaid-egress / griefing vector. Bounded by a timeout. Observability: `node_pull_{attempts,success,no_providers,corruption, unreachable,channel_open_failures}_total`, `node_pull_through_{timeouts, errors}_total`, the `node_address_watcher_{restarts_total,down_seconds}` drift metrics (mirroring the staker-set watcher), and the `node_address_directory_size` gauge. Config: `cache.node_to_node_pull_through_enabled` / `node_pull_probe_fanout` / `node_pull_timeout_sec`. Tests: a runtime-orchestrated miss→pull→serve integration test plus no-providers, unresolvable-address, probe-unreachable, and corruption classification cases, and the delivery-path authorization-gate test. cargo fmt + clippy --all-targets -D warnings clean; nextest 1618 passed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(node): address PR #833 review (probe parallelism, metrics, typed errors) - node_origin: probe candidates CONCURRENTLY (`join_all`) so the probe phase is bounded by one PROBE_TIMEOUT, not fanout × PROBE_TIMEOUT — a few slow peers can't burn the pull budget before a healthy one is tried (gemini). - node_origin / client_requester: replace the brittle corruption classification (substring match on the error message) with a typed `HashMismatch` sentinel that `stream_fetch` returns and `NodeOrigin` matches via `downcast_ref`; the `Display` text is unchanged so existing tests still pin it (Copilot). - cache: add `CacheEngine::populate(hash)` — fills the store via the coalesced pull-through WITHOUT returning bytes or bumping `bytes_returned`/`hits`, and use it for the delivery-path miss hook so an internal fill isn't miscounted as client-served egress (Copilot). New test asserts the metric contract. - dht::node_address: `set_binding` now republishes the directory-size gauge only on a new key (cardinality change), matching its doc + `remove_binding` (Copilot). - docs: correct the `pull_through` field comment (proven-ownership gate, not channel-presence; `cache.populate`, not `cache.get`). cargo fmt + clippy --all-targets -D warnings clean; nextest 1619 passed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * chore(deny): ignore RUSTSEC-2026-0173 (proc-macro-error2 unmaintained) New unmaintained advisory for proc-macro-error2, a build-time-only proc-macro fork pulled transitively via alloy-sol-macro -> alloy. No runtime exposure and no maintained successor — same class as the already-ignored RUSTSEC-2024-0370 (its parent crate). Unblocks the cargo-deny CI gate. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
What
Implements #326 — network reputation gossip aggregation (ADR 008) end to end, plus the settlement-indexer + observability follow-up.
Included
ReputationReport/ReputationReportBody/ReportMetricsappended at the frozenGossipPayloaddiscriminant 1 (pinned by test).reputationcrate) — shared interaction formula,settlement(diversity discount, exponential time decay, 3× weight cap),network(NetworkReputation: weighted EWMA, ±0.05 clamp, 10%/wk decay, 3-distinct-reporter threshold, combined 0.7/0.3),coverage(regional-coverage map + decay + eviction),observationbuffer. Leaf-crate clean (chain-free; trait seams).cdn/reputation/v1subscribe + publish tasks,validate_reputation_envelope(signature + recency + staked-reporter gate), receiver-enforced rate limiter (1/(reporter,node)/hr, 10/reporter/hr),ReputationSink/ReportDrain/StakedReporterSettraits.SettlementIndexer(watches network-wideChannelOpened/ChannelSettled, resolves both parties viaCapacityBond.nodeIdOf, credits the sharedNodeSettlementSourceso reporter weights are live),admin_v1_reputationRPC +decdn node reputationCLI, thegossip.subscribe_reputation/reputation_publish_interval_secconfig knobs, indexer metrics, and a periodic eviction sweep bounding the in-memory maps.Deferred → #831 (gated on the unbuilt node-to-node cache-miss pull-through orchestration)
ObservationBufferfrom delivery/probe outcomes) —report_drainis intentionallyNone, so the node aggregates inbound reports but does not yet emit them.Indexer limitations (flagged)
Bounded recent backfill + in-memory rebuild each boot;
settled_at≈ index time;staked_counterpartyuses current membership. Durable full-52-week indexing is a refinement.Review
A multi-agent review (code/tests/errors/types/comments) ran on the branch; all accepted findings are fixed in this PR — indexer metrics (dead-indexer observability),
u128saturation skip+meter, unbounded-growth eviction/pruning,RegionalCoverageconfig validation, the orphaned-publisher removal, plus added tests and comment/dead-trait cleanup.Test plan
cargo fmt --all -- --check✅cargo clippy --workspace --all-targets -- -D warnings✅cargo nextest run --workspace→ 1601 passed ✅🤖 Generated with Claude Code