Repository navigation
feat(node): add DHT prefetch popularity signal + decision engine (#650) - #819
Conversation
Core slice of #650: ADR-022-canonical FIND_VALUE popularity tracker and prefetch-decision engine behind prefetch.enabled=false, with config surface and metrics. Real network acquisition + OriginAssignment subscription deferred to a follow-up. Notes that the issue's local-cache-miss 'Signal 2' is stale (superseded by ADR 037). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…sion engine Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…650) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…#650) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…650) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
#650) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ns (#650) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ealization (#650) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request implements the speculative-prefetch operator policy (ADR 022), introducing a [prefetch] configuration block, a PopularityTracker for FIND_VALUE query frequency, a PrefetchPolicy decision engine with gate-ordered checks, and corresponding metrics. Feedback highlights a performance bottleneck on the hot path where lock acquisition and queue pruning are performed unconditionally even when prefetching is disabled, as well as a potential deadlock risk from holding a lock across a third-party trait call.
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
This PR introduces the core (off-by-default) DHT prefetch “decide-and-meter” pipeline in decdn-node: a responder-side FIND_VALUE popularity tracker feeding a prefetch decision policy (enabled → demand-quality throttle → authorized-origin → budget), along with config surface and observability metrics.
Changes:
- Adds
[prefetch]configuration (file + resolved + validation + CLI summary/default template) and wires it into runtime config resolution. - Implements
crates/node/src/prefetch/(popularity tracker, decision policy/ledgers, engine façade) and hooks it into the DHT FIND_VALUE handler + runtime construction. - Adds a prefetch metrics family and updates ADR observability docs; includes an end-to-end loopback test asserting FIND_VALUE traffic bumps the authorized acquisition counter.
Reviewed changes
Copilot reviewed 18 out of 18 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| docs/superpowers/specs/2026-06-05-dht-prefetch-popularity-decision-design.md | Adds design spec for the popularity signal + decision engine slice. |
| docs/superpowers/plans/2026-06-05-dht-prefetch-popularity-decision.md | Adds detailed implementation plan for the prefetch pipeline. |
| crates/common/src/config/types.rs | Introduces [prefetch] file config (PrefetchConfig) on FileConfig. |
| crates/common/src/config/resolved.rs | Adds ResolvedPrefetch and wires it into ResolvedConfig. |
| crates/common/src/config/mod.rs | Adds resolver defaults/validation + resolver plumbing + unit tests for [prefetch]. |
| crates/cli/src/commands/config.rs | Surfaces prefetch_enabled in config validate summary and adds [prefetch] template block. |
| crates/cli/tests/config_validate.rs | Adds CLI test ensuring the summary includes prefetch_enabled. |
| crates/node/src/lib.rs | Exposes the new prefetch module. |
| crates/node/src/prefetch/mod.rs | Implements PrefetchEngine façade and outcome enum tying tracker + policy + directory. |
| crates/node/src/prefetch/popularity.rs | Implements responder-side sliding-window popularity tracker with bounded tracking. |
| crates/node/src/prefetch/decision.rs | Implements prefetch decision policy + budget/quality ledgers with unit tests. |
| crates/node/src/metrics.rs | Adds prefetch counters/gauges and helpers for recording decisions/quality. |
| crates/node/src/handlers/dht.rs | Adds optional prefetch engine to DHT handler and feeds it from FIND_VALUE. |
| crates/node/src/runtime/mod.rs | Constructs and attaches prefetch engine at runtime and publishes enabled gauge. |
| crates/node/src/runtime/reload.rs | Updates test config literals to include ResolvedPrefetch. |
| crates/node/tests/sighup_signal.rs | Updates test config literals to include ResolvedPrefetch. |
| crates/node/tests/dht_loopback.rs | Adds loopback integration test asserting FIND_VALUE triggers authorized prefetch metric bump. |
| adr/appendix-observability.md | Reconciles metric naming to iroh_metrics constraints (no labels; integer gauge scaling). |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Coverage reportTotal: 87.40% (was 87.33%, ▲ +0.07%) — 29678/33955 lines
History
|
#650) - PopularityTracker::observe is now edge-triggered (fires once when the count first reaches the threshold, re-arms after the window drains) so a decision is not re-run / re-metered on every FIND_VALUE above the threshold. - run_prefetch short-circuits unless a decision is made: disabled / below- threshold queries do zero metrics or lock work; quality gauges refresh only on a decision. - PrefetchPolicy::decide releases the ledger lock before the OriginDirectory trait call (avoids holding a lock across arbitrary third-party code). - Runtime seeds the demand-quality gauges to a sane baseline (ratio=1.0, throttle=false) at startup so they never read a misleading 0. - Spec status updated to reflect implementation in #819 / follow-up #820. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alpergundogdu
left a comment
There was a problem hiding this comment.
Review — DHT prefetch popularity signal + decision engine
Nicely structured, genuinely off-by-default slice. Anti-panic compliance is clean throughout (every lock is if let Ok(..) else { error!; safe-fallback }, u32::try_from(..).unwrap_or(u32::MAX), no indexing, the as i64 gauge cast clamped under a scoped #[allow]), the gate ordering is right, and lock hygiene is exactly right — gates 2 & 4 are computed under one short-lived lock that's explicitly released before the OriginDirectory trait call to dodge a lock-ordering hazard with a future chain-backed directory, with the rationale commented inline. enabled=false short-circuits to Inert before any lock/metric work while still publishing the gauges (seeded ratio=1.0/throttle=false) for a uniform schema. Config validation is thorough and uses the shared error bag. Two things I'd want resolved before merge, then nits:
1. (Should-fix) Wall-clock time feeds a tracker documented as "monotonic." popularity.rs opens with "The caller supplies a monotonic now (seconds)", but the production caller in handlers/dht.rs::handle_find_value passes now_us / 1_000_000 where now_us() is wall-clock SystemTime::now(). Failure modes:
- Backward NTP correction:
now.saturating_sub(*ts)saturates to 0 → pruning stalls, in-window entries linger, and a single hot hash'sVecDeque<u64>grows unbounded until the clock catches up.MAX_TRACKED_HASHESonly caps distinct hashes, not per-hash deque length — so this is an unbounded-memory edge, not just a metering glitch. The spend/served/acquired ledgers indecision.rsinherit the same skew. - Mis-set clock →
now_us()== 0: every observation lands atnow=0, nothing prunes while the clock is bad.
Fix options: drive prefetch from a monotonic Instant-derived seconds source, or — if wall-clock is acceptable for a metering-only slice — drop the "monotonic" claim in the docstring and add a bounded-length guard on each per-hash deque so a stuck/backward clock can't grow it without limit. At minimum the docstring shouldn't assert a property the caller violates.
2. (Should-fix — naming/intent) The "latched" throttle isn't latched. decision.rs describes the demand-quality auto-throttle as "latched active," but compute_throttle recomputes from the current ratio every call and throttle_latches_below_ratio_and_clears_on_recovery shows it clears immediately once the ratio recovers — i.e. it's level-triggered with no hysteresis. Either rename to "active/level-triggered," or, if ADR 022 actually wants hysteresis (stay throttled until the ratio clears a higher band), that's a behavioral gap. Worth confirming against the ADR.
3. (Nit) lookup_origins(hash).is_empty() clones a Vec to discard it. Gate 3 calls ConfigOriginDirectory::lookup_origins (get(hash).cloned().unwrap_or_default()) just to test emptiness, on the threshold-cross path. A has_origin(&self, hash) -> bool on the OriginDirectory trait avoids the clone while the trait is still small.
4. (Note, not a bug) The budget gate can't fire in production this slice. Acquisition is deferred, so record_acquisition is never called → prefetch_spend_usdc_total and prefetch_budget_exhaustion_events_total stay 0, and with a nonzero budget every threshold-cross re-decides Acquire. Documented as expected; just make sure the prefetch.enabled docs warn that enabling before the #650 follow-up only meters. (The default budget_usdc_per_hour = 0 makes 0 >= 0 → BudgetExhausted, so an accidental default-on is safely inert — good.)
5. (Fragility note) Edge-trigger uses == threshold. observe fires on window.len() == self.threshold, which is correct only because each call pushes exactly one timestamp after pruning. If a future change ever batches arrivals per call, the == silently skips the trigger; a prev < threshold && now >= threshold guard would be robust to that. The unwrap_or(u32::MAX) fallback is the right no-panic choice.
6. (Tests) A few gaps worth closing: no assertion that set_prefetch_quality clamps a non-finite/negative ratio to 0 (the !is_finite() branch is untested); no integration assertion on the prefetch_throttle_active gauge transition; and evict_least_recent's tie-break when two hashes share the same newest timestamp is untested.
Metrics naming cross-checks out against the existing _total-suffix convention, and the loopback test asserting the exact visible decdn_prefetch_acquisitions_authorized_total 1 is a good end-to-end guard. The scope-reconciliation note (Signal 1 only, Signal 2 superseded by ADR 037) is helpful context. No blockers — I'd prioritize #1 and #2 before merge.
Generated by Claude Code
…te (#650) Alper's review of the DHT prefetch slice: - popularity.rs: drop the false "monotonic now" claim — the production caller feeds wall-clock seconds (now_us), consistent with the wall-clock-anchored DHT TTLs. Cap each per-hash window at `threshold` so a backward/stuck clock (pruning stalls when now regresses) can't grow a hot hash's deque without bound. Replace the `== threshold` edge trigger with a `before < threshold && after >= threshold` upward-crossing guard, robust to future per-call batching. - decision.rs: the demand-quality auto-throttle is level-triggered, not latched (ADR 022: "pauses until it recovers" — no hysteresis). Remove the vestigial `throttled` ledger field (written+read in one lock scope, never persisted) and reword the "latched" docstrings. - origin.rs/decision.rs: add OriginDirectory::has_origin so gate 3 tests origin presence without cloning the candidate Vec. - config.rs: warn in the [prefetch] template that this slice only meters (no acquisition / no USDC spend until the #650 follow-up). - tests: gauge clamp branch + throttle 0->1->0 transition, evict tie-break, window length cap, has_origin emptiness parity. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The prefetch_enabled summary line put write_validate_summary right at the clippy too_many_lines boundary (100 lines locally, 104 under CI's count). The PR's earlier config.rs edit busted decdn-cli's clippy fingerprint cache, which had been warm-started from main and never re-linted on this branch, unmasking the latent failure. The function is a flat per-field writeln! sequence; an allow matches the codebase convention for long linear renderers rather than splitting it across helpers. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… (#899) * feat(node): wire live DHT prefetch acquisition + ledger feedback (#820) Closes AC 7 of #650. PR #819 landed the prefetch decision engine but it only decided and metered. This wires the live acquisition on top: - On a `PrefetchDecision::Acquire`, the DHT handler fires a bounded, non-blocking background acquisition (`PrefetchAcquirer`) that drives `cache.populate` → the existing NodeOrigin pull-through (discover → probe → paid pull → ingest). Concurrency-capped (semaphore), per-hash deduped, cancelled on shutdown. - Spend feeds back via a new `AcquisitionObserver` on `NodeOriginDeps`: it fires on every pull that spent (success OR paid-but-failed, whose voucher watermark advanced #852) and records per-pull spend/bytes only for prefetch-initiated pulls (gated by the in-flight set), so demand-miss pulls never charge the prefetch budget. `decdn_prefetch_spend_usdc_total` now non-zero. - A bounded, TTL'd `PrefetchAcquiredSet` tags prefetch content; the client serve path credits `record_served` for those blobs, feeding the demand-quality auto-throttle. - Two new `[prefetch]` config knobs: `max_concurrent_acquisitions` (4) and `acquisition_timeout_secs` (30). New acquisition-outcome metrics. Note: the issue's "OriginAssignment subscription" task was already shipped by #830 (`ChainOriginDirectory`), so only acquisition + ledger feedback remained. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(node): address PR review on prefetch acquisition (#820) - InflightGuard::drop now recovers a poisoned lock (PoisonError::into_inner) so the RAII cleanup always runs (gemini) — leaving a hash armed would wedge dedupe + the observer gate. - InflightSet::arm logs on a poisoned lock, matching PrefetchAcquiredSet::insert, so a dropped acquisition is diagnosable (copilot). - Corrected prefetch_spend_usdc + add_prefetch_spend docs: spend is charged on any prefetch-initiated paid pull that acked vouchers (success OR paid-but- failed), not only successes (copilot). - Raised the e2e poll budget (35s) above the acquirer's 30s deadline so a slow CI pull is not declared a failure prematurely (copilot). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Summary
Core slice of #650 (DHT prefetch & popularity signals). Lands the ADR-022-canonical FIND_VALUE popularity oracle and prefetch-decision engine in
decdn-node, plus its[prefetch]config block and metrics, all behindprefetch.enabled = false. The FIND_VALUE handler decides and meters but does not yet fire the real network acquisition.Scope reconciliation (ADR is source of truth)
The issue text predates an ADR change: ADR 022 §255 now drives speculative prefetch from a single signal — FIND_VALUE query frequency. The issue's "Signal 2" (local cache-miss frequency) was superseded by ADR 037 (reactive chunk-paced pull-through) and is implemented as observability only, not a prefetch trigger. This PR implements Signal 1 only.
What's included
[prefetch]config block —enabled(false),require_authorized_origin(true),budget_usdc_per_hour(0),find_value_threshold(5),threshold_window_secs(300),demand_quality_min_ratio(0.1),demand_quality_window_secs(3600). File + resolved structs, validation,config validatesummary line, andconfig inittemplate.PopularityTracker— responder-side sliding-window per-hash FIND_VALUE counter, bounded LRU, injected clock.PrefetchPolicy— decision engine with gates in order: enabled → demand-quality throttle → authorized-origin (reuses the existingOriginDirectorytrait) → rolling-1h budget. Ledgers fully unit-tested.PrefetchEnginefaçade tying tracker + policy + origin directory;on_find_valueobserves and, on a threshold-cross, decides.enabled.iroh_metricshas no labels, so the{gate_result}split is realized as three sibling counters (decdn_prefetch_acquisitions_{authorized,unauthorized,bypassed}_total) and the ratio gauge is integer ×1000 (…_milli); the appendix is updated to match.DhtHandler.with_prefetch(engine); runtime builds the engine and publishesdecdn_prefetch_enabled. Withenabled = falsethe whole path is inert.Deferred to follow-up (AC 7)
Real
FindValue → probe → cdn/client/v1 pull-throughacquisition,OriginAssignmentevent subscription for a live gate cache, and feeding served/acquired bytes back into the ledgers. The decision engine'srecord_*methods ship complete and unit-tested so the follow-up only has to call them. AC 8 (demand derives from FIND_VALUE) is satisfied here — the tracker is live and metered.Design spec and implementation plan are committed under
docs/superpowers/.Test Plan
cargo nextest run --workspace— 1468 tests pass (incl. new config resolver, tracker, decision-engine, façade, and an end-to-enddht_loopbacktest asserting FIND_VALUE traffic bumpsdecdn_prefetch_acquisitions_authorized_total)cargo clippy --workspace --all-targetsclean (anti-panic + pedantic)cargo fmt --check,cargo deny checkcleanprefetch.enabled = false); no behavior change unless opted in🤖 Generated with Claude Code