Skip to content

feat(node): node-to-node cache-miss pull-through + outbound reputation (#831) - #833

Merged
thiras merged 2 commits into
feat/326-reputation-gossip-aggregationfrom
feat/831-node-pull-through-reputation
Jun 7, 2026
Merged

thiras merged 2 commits into
feat/326-reputation-gossip-aggregationfrom
feat/831-node-pull-through-reputation

Conversation

@thiras

@thiras thiras commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Closes #831.

What

Implements #831 — the node-to-node cache-miss pull-through orchestration, then wires ADR-008 outbound reputation capture + reputation-consuming selection on top of it. Closes the half deferred from #326/#832 ("the node aggregates inbound reports but does not yet emit them" / "selection does not consume reputation").

Stacked on #832 (base = feat/326-reputation-gossip-aggregation); review #832 first.

The whole feature is gated behind cache.node_to_node_pull_through_enabled (default OFF).

How

NodeOrigin — a new Origin impl appended last in the cache engine's origin chain (so configured HTTP/FS/S3 origins are tried first, the paid network pull is the final fallback). CacheEngine only ingests via the Origin trait, so this is the natural seam. On a miss it:

  1. discovers providers — DHT find_providers, falling back to the origin directory;
  2. probes each candidate (cdn/probe/v1) for rate/RTT and ranks them by combined_score(local, network, cfg) (selection::rank_candidates);
  3. opens/reuses a buyer channel and paid-pulls via client_requester::stream_fetch, falling back through MAX_PROVIDER_ATTEMPTS;
  4. records the per-provider Outcome into LocalReputation + the ObservationBuffer.

The engine verifies + ingests the returned bytes; stream_fetch does its own whole-blob BLAKE3 check, so a dishonest provider is detected and scored Corruption rather than surfaced.

Supporting pieces:

  • dht::node_address::ChainNodeAddressDirectory — resolves a provider NodeId → 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. No new contract surface.
  • buyer_channel::ChannelOpener — object-safe seam erasing BuyerChannelService<P>'s provider generic (so the dyn Origin can hold it).
  • probe_client — node-side copy of the transport-only probe_once.
  • report_drain is wired (publisher spawns) when the feature is on, so the node finally emits reports about the upstreams it pulled from.
  • OriginKind::Peer tags the (USDC-billed) network origin for eviction-cost output.

Delivery-path hook (handlers/client): a cache miss triggers the pull only for a request that proves ownership of the named channel (a verified client binding matching the channel's authorized client). Channel ids are public on-chain, so existence cannot authorize spend — this closes the unpaid-egress / griefing vector where a leech drains the buyer deposit. 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, #788), and the node_address_directory_size gauge.

Config

cache.node_to_node_pull_through_enabled (default false), cache.node_pull_probe_fanout (5), cache.node_pull_timeout_sec (20). Reuses blockchain.buyer_deposit_micro_usdc for the deposit hint.

Review

A multi-agent review (code / tests / errors / types / comments) ran on these changes. The one Critical it surfaced — the cache-miss gate originally checked channel existence not ownership, allowing unpaid upstream egress — is fixed here (the ownership gate above), and the flagged observability cluster + test gaps are addressed in this PR.

Deferred (follow-ups)

  • ChainOriginDirectory (config + DHT discovery only for now); serving-side reputation capture; a typed stream_fetch error to replace the corruption-vs-unreachable string match; multi-hop node→node pulls (the requester would need to send a binding).

Test plan

  • cargo fmt --all -- --check ✅
  • cargo clippy --workspace --all-targets -- -D warnings ✅
  • cargo nextest run --workspace → 1618 passed ✅
  • New tests: runtime-orchestrated miss→pull→serve; no-providers / unresolvable-address / probe-unreachable / corruption-classification orchestration cases; the delivery-path authorization-gate test (proves unbound + wrong-owner requests never reach the paid pull).

🤖 Generated with Claude Code

#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]>
Copilot AI review requested due to automatic review settings June 6, 2026 23:15

@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 implements node-to-node cache-miss pull-through (ADR 001/022), allowing nodes to discover, probe, rank, and paid-pull content from upstream nodes on a cache miss. It introduces configuration options, a Node ID to Ethereum address resolver, a NodeOrigin cache engine origin, and a reusable QUIC 0-RTT probe client, alongside corresponding metrics and integration tests. The review feedback highlights a performance improvement opportunity in node_origin.rs to probe candidate providers in parallel rather than sequentially to minimize latency on the cache-miss path.

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.

Comment thread crates/node/src/node_origin.rs Resolved

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 the node-side orchestration for node-to-node cache-miss pull-through (via a new NodeOrigin appended last in the cache origin chain) and wires outbound reputation capture + selection consumption on top, gated by cache.node_to_node_pull_through_enabled (default off).

Changes:

  • Add NodeOrigin + runtime provisioning (DHT discover → probe/rank → open/reuse buyer channel → paid pull) and attach a delivery-path pull-through hook gated by proven channel ownership.
  • Wire outbound reputation emission by feeding LocalReputation + ObservationBuffer from pull outcomes and enabling report_drain only when pull-through is enabled.
  • Add node-side probe client, node-address resolver (NodeId→operator address), config knobs, metrics, and integration tests covering orchestration and the authorization gate.

Reviewed changes

Copilot reviewed 19 out of 19 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
crates/node/tests/sighup_signal.rs Updates resolved-cache test fixture with new pull-through config defaults.
crates/node/tests/node_origin_pull.rs New end-to-end tests for NodeOrigin orchestration outcomes (success, no providers, unresolvable address, unreachable, corruption).
crates/node/tests/client_loopback.rs New test ensuring pull-through is only triggered when request proves channel ownership (binding gate).
crates/node/src/runtime/reload.rs Adds new resolved-cache defaults to runtime reload state + tests.
crates/node/src/runtime/mod.rs Appends NodeOrigin to cache origin chain, bootstraps resolver/buyer deps, wires pull-through hook + report drain, provisions origin.
crates/node/src/probe_client.rs Adds node-side cdn/probe/v1 client (0-RTT aware) used by provider probing.
crates/node/src/node_origin.rs Implements the pull-through origin (Origin) with discovery/probe/rank/pull and reputation+metrics recording.
crates/node/src/metrics.rs Adds metrics for node pull-through, node-address watcher health, and directory size gauge.
crates/node/src/lib.rs Exposes new node_origin and probe_client modules.
crates/node/src/handlers/client.rs Adds pull-through deadline wiring + ownership gate, and miss-path trigger for authorized requests.
crates/node/src/dht/node_address.rs Adds chain-backed NodeId→operator address directory with watcher + metrics.
crates/node/src/dht/mod.rs Exports new node-address directory types/traits.
crates/node/src/buyer_channel.rs Adds ChannelOpener trait to erase provider generic for use behind dyn Origin.
crates/config-types/src/origin_kind.rs Adds OriginKind::Peer for tagging paid peer origin in admin/eviction output.
crates/common/src/config/types.rs Adds cache config knobs for pull-through enablement, probe fanout, and pull timeout.
crates/common/src/config/resolved.rs Adds resolved cache fields for pull-through enablement and tuning.
crates/common/src/config/mod.rs Defines defaults and resolves new cache config knobs.
crates/cli/tests/config_validate.rs Updates CLI config validation fixture with new resolved-cache fields.
crates/cli/src/commands/config.rs Surfaces pull-through enablement + knobs in config validate summary and default config template.

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

Comment thread crates/node/src/dht/node_address.rs Resolved
Comment thread crates/node/src/handlers/client.rs Resolved
Comment thread crates/node/src/node_origin.rs Resolved
…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]>
@thiras
thiras merged commit c568752 into feat/326-reputation-gossip-aggregation Jun 7, 2026
@thiras
thiras deleted the feat/831-node-pull-through-reputation branch June 7, 2026 17:49
@thiras
thiras restored the feat/831-node-pull-through-reputation branch June 7, 2026 18:25
@thiras

thiras commented Jun 7, 2026

Copy link
Copy Markdown
Contributor Author

This PR was merged by accident. The merge has been reverted (base feat/326-reputation-gossip-aggregation reset to 4d47235, removing squash commit c568752). Since a merged PR can't be reopened, the work continues in #834 (same head branch feat/831-node-pull-through-reputation at 45dc8ca, identical contents). Please direct further review there.

thiras added a commit that referenced this pull request Jun 10, 2026
#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]>
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.

2 participants