Skip to content

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

Merged
thiras merged 8 commits into
mainfrom
feat/831-node-pull-through-reputation
Jun 10, 2026
Merged

thiras merged 8 commits into
mainfrom
feat/831-node-pull-through-reputation

Conversation

@thiras

@thiras thiras commented Jun 7, 2026

Copy link
Copy Markdown
Contributor

Reopens the node-to-node cache-miss pull-through + outbound reputation work after PR #833 was accidentally merged, then reverted (base feat/326-reputation-gossip-aggregation reset back to 4d47235, removing squash commit c568752; the auto-deleted head branch was restored at 45dc8ca). Same head branch and contents as #833; all four #833 review comments remain addressed in 45dc8ca.

🤖 Generated with Claude Code

thiras and others added 6 commits June 6, 2026 22:40
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]>
…, 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]>
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]>
#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]>
…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]>

@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 paid cache-miss pull-through (#831, ADR 001/022), allowing nodes to discover, probe, rank, and pull content from upstream peers on a cache miss. It introduces the NodeOrigin backend, the ChainNodeAddressDirectory for resolving node IDs to operator Ethereum addresses, and gates pull-through requests on proven channel ownership to prevent proxy abuse. Feedback from the review highlights two key areas for improvement: first, addressing a potential permanent drift in the node address directory when the blockchain event watcher experiences an outage by implementing a backfill or historical log query; second, optimizing the probe client by spawning the post-exchange linger in a background task to prevent synchronous blocking and reduce miss-latency during provider ranking.

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 on lines +199 to +223
let mut backoff = WATCHER_INITIAL_BACKOFF;
loop {
match run_watcher_once(&registry, &bindings, &metrics).await {
Ok(()) => {
debug!("node-address watcher stream ended cleanly; restarting subscription");
backoff = WATCHER_INITIAL_BACKOFF;
}
Err(err) => {
// Open a drift window: bindings arriving on-chain while filters
// are down are missed until the next re-establish, so those
// providers become unpayable and are skipped. Edge-trip the
// restart counter + start the down-seconds clock (mirrors the
// staker-set watcher, #788).
metrics.node_address_watcher_backoff_started();
warn!(
%err,
backoff_secs = backoff.as_secs(),
"ChainNodeAddressDirectory watcher RPC error; restarting after backoff \
(binding map may be briefly stale)"
);
tokio::time::sleep(backoff).await;
backoff = (backoff * 2).min(WATCHER_MAX_BACKOFF);
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

The background watcher_loop re-establishes the event filters using run_watcher_once after a backoff when an RPC or stream error occurs. However, any NodeRegistered or NodeDeregistered events that occurred on-chain during the backoff/outage window are completely missed because the new filters only watch from the current block.

Since there is no catch-up mechanism or periodic full resync, this creates a permanent drift in the in-memory bindings map until the entire node process is restarted. Missed registrations will cause those providers to be skipped as unpayable.

To resolve this, ensure that transient anomalies and event persistence failures are treated as retryable errors, and propagate them to trigger the watcher's backoff-and-retry mechanism. Additionally, consider tracking the last-seen block number and querying historical logs for the missed block range before starting the stream subscription to prevent dropping events.

References
  1. In blockchain or RPC watcher and backfill implementations, treat transient anomalies (such as invalid block ranges caused by replication lag) and event persistence failures as retryable errors. Do not silently skip or log them as warnings if doing so permanently disables the backfill or drops events; instead, propagate the error to trigger the watcher's backoff-and-retry mechanism.

Comment on lines +151 to +156

// ADR 015 §Session Ticket Management: linger up to 2x the measured RTT
// (clamped) so the server's NewSessionTicket reaches us and rustls caches
// it for the next attempt. The timeout elapsing is the expected case.
let linger = (rtt * 2).clamp(LINGER_MIN, LINGER_MAX);
let _ = tokio::time::timeout(linger, conn.closed()).await;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The post-exchange linger is currently awaited synchronously inside probe_once, which blocks the caller from receiving the probe response and RTT measurement until the linger timeout (at least 100ms and up to 2s) expires. Since probe_once is called for multiple candidates during the cache-miss provider-ranking phase, this synchronous block artificially inflates the cache-miss pull-through latency.

We can optimize this by spawning the linger and connection closure in a background task, allowing probe_once to return the response and RTT immediately after the exchange completes.

Suggested change
// ADR 015 §Session Ticket Management: linger up to 2x the measured RTT
// (clamped) so the server's NewSessionTicket reaches us and rustls caches
// it for the next attempt. The timeout elapsing is the expected case.
let linger = (rtt * 2).clamp(LINGER_MIN, LINGER_MAX);
let _ = tokio::time::timeout(linger, conn.closed()).await;
// ADR 015 §Session Ticket Management: linger up to 2x the measured RTT
// (clamped) so the server's NewSessionTicket reaches us and rustls caches
// it for the next attempt. The timeout elapsing is the expected case.
let linger = (rtt * 2).clamp(LINGER_MIN, LINGER_MAX);
let conn_clone = conn.clone();
tokio::spawn(async move {
let _ = tokio::time::timeout(linger, conn_clone.closed()).await;
conn_clone.close(0u32.into(), b"probe-done");
});

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 reintroduces and completes the node-to-node cache-miss pull-through feature by adding a NodeOrigin to the cache origin chain, wiring runtime provisioning (discovery + buyer channels + provider address resolution), and integrating outbound reputation capture/emit when the feature is enabled.

Changes:

  • Add a deferred-provisioned NodeOrigin origin to perform discovery → probe/rank → paid pull-through on cache misses (feature-gated).
  • Wire runtime dependencies: chain-backed NodeId → operator address resolver, buyer channel opener seam, pull-through miss hook in the client handler, and outbound reputation report drain.
  • Extend observability/config and add comprehensive runtime-orchestrated integration tests (including authorization-gate coverage).

Reviewed changes

Copilot reviewed 21 out of 21 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
crates/node/tests/sighup_signal.rs Updates resolved cache config seed with new pull-through fields.
crates/node/tests/node_origin_pull.rs New runtime-orchestrated tests for NodeOrigin pull-through outcomes + metrics + reputation capture.
crates/node/tests/client_loopback.rs Adds test ensuring pull-through is gated by proven channel ownership (CountingOrigin).
crates/node/src/runtime/reload.rs Extends resolved-cache defaults/tests to include new pull-through config fields.
crates/node/src/runtime/mod.rs Wires NodeOrigin into cache chain, bootstraps address resolver, arms pull-through hook, provisions NodeOrigin, wires report drain.
crates/node/src/probe_client.rs Adds node-side reusable cdn/probe/v1 transport client (0-RTT aware).
crates/node/src/node_origin.rs Implements the Origin performing node-to-node discovery/probe/rank/pull and reputation recording.
crates/node/src/metrics.rs Adds gauges/counters for pull-through and node-address watcher health.
crates/node/src/lib.rs Exposes new node_origin and probe_client modules.
crates/node/src/handlers/client.rs Adds pull-through deadline + authorization gate and invokes cache populate on eligible misses.
crates/node/src/dht/node_address.rs New chain-backed directory resolving provider NodeId → bonded operator address + watcher + metrics.
crates/node/src/dht/mod.rs Exposes node-address resolver types from the dht module.
crates/node/src/client_requester.rs Adds typed HashMismatch sentinel error for corruption classification without string matching.
crates/node/src/buyer_channel.rs Introduces object-safe ChannelOpener trait and impl for BuyerChannelService.
crates/config-types/src/origin_kind.rs Adds OriginKind::Peer for tagging paid peer pulls in admin/eviction output.
crates/common/src/config/types.rs Adds TOML config fields for enabling pull-through + probe fanout + pull timeout.
crates/common/src/config/resolved.rs Adds resolved cache fields for pull-through enable/fanout/timeout.
crates/common/src/config/mod.rs Defines defaults and resolves new cache config fields.
crates/cli/tests/config_validate.rs Updates resolved-config fixture with new pull-through fields.
crates/cli/src/commands/config.rs Displays pull-through enablement and knobs in config validation summary; documents defaults.
crates/cache/src/engine.rs Adds CacheEngine::populate (fill without counting client bytes/hits) + tests.

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

Comment on lines +889 to +891
if cfg.cache.node_to_node_pull_through_enabled {
client_handler.attach_pull_through(Duration::from_secs(cfg.cache.node_pull_timeout_sec));
}
Base automatically changed from feat/326-reputation-gossip-aggregation to main June 10, 2026 00:02
thiras and others added 2 commits June 10, 2026 03:09
Resolve conflicts in node metrics + runtime wiring:
- metrics.rs: keep both the #831 node-pull/address-watcher metric
  families and the #651 origin-directory watcher families (additive on
  both sides — struct fields, constructor inits, recorder methods, and
  the encode() down-seconds recompute).
- runtime/mod.rs: keep the #831 outbound report capture, local
  reputation + observation buffer, and node-origin provisioning.
- reload.rs (clean-merge artifact): #651 `discovery` and #831 node-pull
  cache fields together pushed for_test_with_setter past 100 lines;
  add #[allow(clippy::too_many_lines)] matching the existing idiom.

cargo clippy --workspace --all-targets -- -D warnings, fmt --check, and
the 553-test decdn-node suite all pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
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]>
@github-actions

Copy link
Copy Markdown

Coverage report

Total: 85.78% (was 87.46%, ▼ 1.68%) — 33311/38835 lines

File Coverage Lines Δ
crates/cache/src/engine.rs 93.15% 1685/1809 ▼ 0.41%
crates/cli/src/commands/config.rs 65.87% 110/167 ▲ +4.33%
crates/common/src/config/mod.rs 96.85% 5900/6092 ▲ +0.30%
crates/common/src/config/resolved.rs 100.00% 33/33 ● 0.00%
crates/config-types/src/origin_kind.rs 100.00% 45/45 ● 0.00%
crates/node/src/buyer_channel.rs 17.16% 64/373 ▼ 0.09%
crates/node/src/client_requester.rs 85.33% 221/259 ▲ +0.17%
crates/node/src/dht/node_address.rs 42.57% 86/202 new
crates/node/src/handlers/client.rs 76.80% 490/638 ● 0.00%
crates/node/src/metrics.rs 84.13% 705/838 ▼ 2.70%
crates/node/src/node_origin.rs 89.02% 235/264 new
crates/node/src/probe_client.rs 61.54% 72/117 new
crates/node/src/runtime/mod.rs 49.91% 878/1759 ▼ 2.75%
crates/node/src/runtime/reload.rs 95.16% 1436/1509 ▲ +0.07%
History
Commit Total Δ vs base
e675b08 (HEAD) 85.78% ▼ 1.68%

@thiras
thiras merged commit c602c52 into main Jun 10, 2026
19 checks passed
@thiras
thiras deleted the feat/831-node-pull-through-reputation branch June 10, 2026 00:22
thiras added a commit that referenced this pull request Jun 10, 2026
On a cache-miss pull-through the node pays the upstream by signing
cumulative vouchers, but `BuyerChannelService::record_progress` had zero
production callers: `stream_fetch` discarded the signed totals and
`pull_from_candidate` never persisted them. The buyer channel is reused
per-provider (~90 days), so on reuse `ChannelContext::for_buyer_channel`
rebuilt context from the open-time zeros and re-signed `nonce=1` with a
regressed cumulative `bytes_delivered`; the upstream rejected it
(`StaleNonce`/`BytesRegression`) and delivery aborted. The headline #834
channel-reuse feature worked exactly once per provider, then that
provider was permanently unusable until channel expiry.

Thread a `VoucherProgress` acked-watermark out-param through the pull
path, advanced only after each `VoucherAck`, and persist it after every
stream:

- client_requester: add `VoucherProgress` (encapsulated — `seed`,
  `commit_ack`, `acked`); `self_pay`/`fetch_inner` advance it post-ack;
  keep `stream_fetch -> Result<Bytes>` for the many simple callers via a
  thin wrapper, add `stream_fetch_tracked` carrying the out-param.
- buyer_channel: expose `record_progress` on the `ChannelOpener` seam.
- node_origin: `pull_from_candidate` persists progress on both Ok and Err
  paths when a voucher was acked (a mid-stream failure or paid-but-corrupt
  delivery still advanced the upstream's watermark). A persist failure
  does not fail the already-paid pull — it warns and bumps a new
  `node_pull_progress_persist_failures` counter.

Because the watermark only reflects *acked* vouchers, a lost ack after
the upstream commits under-records by one (self-corrects on rotation);
this residual is documented, not closed here.

Tests: extend `StubOpener` to model the persist→reuse loop; add a
two-pull resume regression test, a persist-failure test (pull still
delivers, counter increments), exact-total assertions on the
success/corruption paths, and empty-log assertions on the no-pull paths.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
thiras added a commit that referenced this pull request Jun 10, 2026
…872)

* fix(node): persist buyer voucher progress after pull-through (#852)

On a cache-miss pull-through the node pays the upstream by signing
cumulative vouchers, but `BuyerChannelService::record_progress` had zero
production callers: `stream_fetch` discarded the signed totals and
`pull_from_candidate` never persisted them. The buyer channel is reused
per-provider (~90 days), so on reuse `ChannelContext::for_buyer_channel`
rebuilt context from the open-time zeros and re-signed `nonce=1` with a
regressed cumulative `bytes_delivered`; the upstream rejected it
(`StaleNonce`/`BytesRegression`) and delivery aborted. The headline #834
channel-reuse feature worked exactly once per provider, then that
provider was permanently unusable until channel expiry.

Thread a `VoucherProgress` acked-watermark out-param through the pull
path, advanced only after each `VoucherAck`, and persist it after every
stream:

- client_requester: add `VoucherProgress` (encapsulated — `seed`,
  `commit_ack`, `acked`); `self_pay`/`fetch_inner` advance it post-ack;
  keep `stream_fetch -> Result<Bytes>` for the many simple callers via a
  thin wrapper, add `stream_fetch_tracked` carrying the out-param.
- buyer_channel: expose `record_progress` on the `ChannelOpener` seam.
- node_origin: `pull_from_candidate` persists progress on both Ok and Err
  paths when a voucher was acked (a mid-stream failure or paid-but-corrupt
  delivery still advanced the upstream's watermark). A persist failure
  does not fail the already-paid pull — it warns and bumps a new
  `node_pull_progress_persist_failures` counter.

Because the watermark only reflects *acked* vouchers, a lost ack after
the upstream commits under-records by one (self-corrects on rotation);
this residual is documented, not closed here.

Tests: extend `StubOpener` to model the persist→reuse loop; add a
two-pull resume regression test, a persist-failure test (pull still
delivers, counter increments), exact-total assertions on the
success/corruption paths, and empty-log assertions on the no-pull paths.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(node): measure pull elapsed before progress persistence

Address review: `record_progress` does a blocking fsync'd redb write, and
it ran before `started.elapsed()` was captured for the `Outcome::Delivered`
reputation signal — inflating the delivery-speed measurement with disk I/O
unrelated to the network pull. Capture `elapsed` immediately after
`stream_fetch_tracked` returns, before persistence.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
thiras pushed a commit that referenced this pull request Jun 13, 2026
…886)

* fix(node): feed RegionAccountant on delivered node→node pulls (#858)

`RegionAccountant::record_pulled` had zero production callers: #831/#834
landed the node-to-node cache-miss pull orchestrator but never wired the
accountant into it, so `bytes_in` stayed 0 in admin_v1_regionStats and the
periodic region_bandwidth log even while paid pulls flowed — the surface
operators use to reconcile pull spend by region (#750).

Pass the runtime's existing Arc<RegionAccountant> into NodeOriginDeps and
call record_pulled(&candidate.node_id, bytes.len()) in the delivered (Ok)
arm of pull_from_candidate, mirroring the serve path's record_served. On a
full delivery paid bytes == blob length; partially-paid failed pulls are
intentionally not counted.

Extends the headline pull test to assert bytes_in accumulates for the
upstream peer's region, and refreshes the now-stale record_pulled doc.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* test(node): assert Err-arm pulls record no bytes_in; clarify accounting comment

Follow-up to PR review of #858:

- Extend node_origin_pull_falls_through_a_stalled_candidate to map the
  stalled (Err-arm) and delivered (Ok-arm) candidates to distinct regions
  and assert the snapshot counts only the delivered one — guarding the
  "partially-paid failed pulls are not counted" contract and multi-candidate
  attribution in a single assertion.
- Tighten the record_pulled call-site comment: payment is incremental per
  voucher interval (the whole-blob hash check makes bytes.len() == paid
  cumulative on a full Ok delivery), and region bytes_in tracks delivered,
  not spent, bytes — so it diverges from the voucher watermark on failed
  pulls by design.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs(node): drop redundant (#852) ref from record_pulled comment

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs(node): drop issue-number refs (#858, #831) from PR comments

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs(node): restore issue-number refs (#852, #858, #831) in comments

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