Repository navigation
feat(node): selection algorithm + ADR 008 §9 tie-break (#322) - #380
Conversation
There was a problem hiding this comment.
Code Review
This pull request implements the provider selection algorithm as specified in ADR 001 and ADR 008, introducing the selection module to rank candidate nodes based on price, latency, and reputation. The implementation includes a four-tier tie-breaking system (load, geo-diversity, stake, and randomness) and a comprehensive set of unit tests. Feedback suggests optimizing vector removals using swap_remove, reducing allocations in the tie-breaking logic to improve performance, and correcting the tie-grouping condition to properly handle candidates with a score of zero.
Bite-sized TDD plan to implement ADR 001 §Node Selection Algorithm plus ADR 008 §9 four-tier tie-break (load → geo → stake → random), landing as a pure ranking module at crates/node/src/selection.rs. Stake stays Option<u64> until on-chain lookup is wired; reputation is taken as f32 per Candidate so ReputationEngine can ship later. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Skeleton for the node-selection algorithm specified in ADR 001 and ADR 008. Issue #322.
Implements ADR 001's unified score formula. Reputation is clamped to a 0.1 floor so a node at 0.0 reputation scores identically to one at 0.1 (100x multiplier vs perfect reputation). Issue #322.
No tie-breaking yet — that lands in tasks 4-7. Uses f64::total_cmp so the comparator is total even though score values are always finite. Issue #322.
Adds tie-group detection on the 1% score-equivalence threshold from ADR 001 and orders tied candidates by LoadHint (bandwidth_utilization first, then active_streams). Tiers 2-4 follow. Issue #322.
Refactors apply_tiebreaker into a stateful per-pick loop that prefers candidates in regions not yet emitted. Tier-1 load winners across multiple regions are now distributed before duplicates of the same region. Issue #322.
Stake is Option<u64> because on-chain stake lookup is deferred (not in NodeAnnounce). When all pool candidates have stake = None the tier is a no-op and the next tier decides. Issue #322. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
When all four tiers tie, picks uniformly at random from the remaining pool. The internal rank_candidates_with_rng entry point keeps tests deterministic via a seeded StdRng. Issue #322.
geo_diversity_prefers_unseen_region was flaky: with three candidates fully tied by score and load, the tier-4 random tier could pick DE first, breaking the [US, DE, US] assertion ~1 in 3 runs. Switching to rank_candidates_with_rng with a fixed seed makes the path deterministic. Issue #322.
Replaces the seed-2 golden-output check with a loop over 32 seeds that asserts the actual invariant — WHEN the first pick is US, the second pick MUST be DE (the only unseen region). Robust to rand RNG changes and input ordering. Also adds a comment explaining why the random tier's pool.get(idx).copied().unwrap_or(0) is unreachable-None. Issue #322.
top_n(candidates, MAX_PROVIDER_ATTEMPTS) is the canonical entry point for the future cache-miss-pull caller — issue #322's 'max 3 provider attempts before returning error to caller' requirement. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The emitted_regions HashSet was declared outside the outer while loop in apply_tiebreaker, so a region picked in one score tie group biased the geo tier of subsequent unrelated tie groups. ADR 008 §9 scopes tie-breaking to a single group; resetting the tracker per group fixes the leak and matches the function's doc comment. Adds a regression test using two distinct-score tie groups with overlapping regions. Issue #322. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
CI's rustdoc lint denies private_intra_doc_links: a public doc comment on rank_candidates can't link to the private rank_candidates_with_rng helper. Replace the [`...`] link with plain code formatting; the test module already uses the helper directly so no functional reference is lost. Issue #322. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The PoC/production split in §12 was decorative rather than load-bearing — this PR's selection module ships the full 4-tier tie-breaker that §12 listed as production-only, which is the cleanest evidence the framing isn't predicting what gets implemented. Following the trim pattern from PRs #388 and the architecture intro, drop the section so §9's tie-break spec stands as the single source of truth. What's wired vs. what's deferred remains visible in code and issue tracking. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
5be75a8 to
d16487d
Compare
`pick_best_in_group` rescans the group from scratch on every iteration, so the order inside the Vec doesn't matter. swap_remove is O(1) where remove is O(K). Negligible at PoC scale but mechanical to fix. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Replace the load_tied / geo_pool / stake_pool intermediates with a single Vec<usize> filtered in place across the four tiers. Allocates one Vec per call regardless of group size, instead of three per call plus a clone in the geo-empty branch. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The previous denom <= 0.0 guard treated zero-score candidates as ungroupable: each became its own singleton tie group, so the load / geo / stake / random tiers were silently skipped between them. Replace with: a zero pivot ends the group only when the next score is strictly positive (zero is strictly better than any positive score), and zero scores tie with each other. Adds two regression tests: - zero_score_candidates_group_together_for_tie_break — two zero scores go through the load tier - zero_score_beats_positive_score — zero is not tied with positive Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request implements the provider selection algorithm in a new selection module, as specified in ADR 001 and ADR 008. The implementation includes a unified scoring formula based on price, latency, and reputation, along with a four-tier tie-breaking system (load, geo-diversity, stake, and randomness). The PR also updates the reputation ADR and adds a comprehensive implementation plan. Feedback was provided to change the REPUTATION_FLOOR constant type to f64 to ensure consistency with the score calculation and avoid unnecessary type casting.
| pub const MAX_PROVIDER_ATTEMPTS: usize = 3; | ||
|
|
||
| /// Reputation floor in the score denominator (ADR 001). | ||
| const REPUTATION_FLOOR: f32 = 0.1; |
There was a problem hiding this comment.
Done in aaf9e42 — REPUTATION_FLOOR is now f64, and compute_score clamps directly in f64 (f64::from(reputation).max(REPUTATION_FLOOR)). Dropped the intermediate rep_clamped variable. Side note: 0.1f32 promotes to ~0.10000000149f64, slightly above the f64 floor, so an exact-floor reputation input no longer aliases the clamped output — the two clamp tests now compare two sub-floor inputs (both clamp identically) to preserve the original "clamping happens" semantic without depending on the f32→f64 promotion artifact.
There was a problem hiding this comment.
Reconsidered in 0b5cfc5 — reverted to REPUTATION_FLOOR: f32, with the cast inlined:
let rep = f64::from(reputation.max(REPUTATION_FLOOR));The aaf9e42 form (f64 floor, promote then clamp) addressed the type-consistency concern but introduced a subtle boundary: f32(0.1) is not exactly representable in f32 (true value ~0.10000000149), so promoting it to f64 lands just above the f64 floor and skips the clamp. That forced both clamp-tests to compare two sub-floor inputs instead of the natural clamped-zero == compute_score(_, _, 0.1) assertion — a code smell where the test had to work around the implementation.
Clamping in f32 first (the input domain) and promoting once at the end keeps the floor type matching the input, restores the natural test, and still gets your underlying cleanup intent (single conversion, no intermediate variable). Rule of thumb that fell out of this: convert at the latest sensible point.
Rankings are mathematically identical between the two forms (sub-ULP differences after squaring); this is purely a code-quality / test-ergonomics call.
Implements per-peer EWMA reputation scoring in the previously-stub
`decdn-reputation` crate. Scope is ADR 008 §14a (PoC):
- `LocalReputation` store keyed by `iroh::PublicKey`, RwLock-shared
- `Outcome::{Unreachable, Corruption, Delivered{bytes, elapsed}}` enum
forecloses nonsensical states (e.g. unreachable-but-delivered)
- `LocalReputationConfig` with ADR §3 defaults (α=0.1, initial=0.5,
weights 40/40/20) validated at `LocalReputation::new`; rejects
non-finite values, weights not summing to 1.0, zero `expected_bps`
- §8 per-report ±0.05 clamp wired but defaults to no-op (1.0) per
§14a's "no clamping" PoC scope; production opts in via config
- 17 unit tests including default-config pinning, zero-elapsed safety,
multi-thread concurrency, and config-validation rejects
In-memory only — persistence is intentionally not implemented per ADR
008 §14a.3, superseding the `data_dir` line in the issue body. Network
gossip aggregation deferred to #326; outcome producer wiring waits on
#317 (paid delivery handler); selection consumer waits on #380.
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
…ve, ADR refs - Add `#[non_exhaustive]` to `Candidate` and `RankedCandidate` so future tie-break fields don't break downstream extractors. - Pair the unreachable safe fallbacks (slice bounds, pick_idx, empty group, random tier) with `debug_assert!` so invariant breaks surface in tests while release keeps the clippy-required indexing guard. - Fix Tier 3 comment: ADR 023 doesn't exist; stake-lookup wiring lives in ADR 001 §Node Registry / ADR 019. - Document why `compare_load` orders by `bandwidth_utilization` first (utilization is the primary saturation signal; `active_streams` is a coarser proxy). - Soften the ADR 008 §9 citation in `apply_tiebreaker` — §9 lists the four tiers but doesn't prescribe per-group scoping; that's this module's interpretation. - Add `some_zero_stake_beats_none_stake` test pinning the `Some(0)` vs `None` boundary (Some(0) wins because `max_stake = Some(0)` then retain drops `None` entries). Findings from /pr-review-toolkit:review-pr (5 specialist agents). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Plan completed; implementation lives in crates/node/src/selection.rs. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
Adds a pure Rust selection/ranking module to decdn-node implementing the ADR-defined node selection score and four-tier tie-break (load → geo → stake → random), and updates related documentation/ADRs to reflect the current design.
Changes:
- Introduces
crates/node/src/selection.rswithCandidate/RankedCandidate, score computation, tie-grouping, tie-break tiers, and unit tests; plustop_nandMAX_PROVIDER_ATTEMPTS = 3. - Exposes the new module from
crates/node/src/lib.rs. - Adds an implementation plan doc and trims PoC-scope text from ADR 008.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| docs/superpowers/plans/2026-04-29-node-selection.md | New step-by-step implementation plan for the node selection module. |
| crates/node/src/selection.rs | Implements the node selection ranking algorithm and tie-break tiers with deterministic test coverage. |
| crates/node/src/lib.rs | Exports the new selection module from the node crate. |
| adr/008-reputation.md | Removes PoC-scope text/rows to align ADR 008 with current direction and ADR 001 references. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| let slice = ranked.get(start..end); | ||
| debug_assert!( | ||
| slice.is_some(), | ||
| "tie_group_end produced out-of-bounds range {start}..{end} for len {}", | ||
| ranked.len() | ||
| ); | ||
| let mut group: Vec<RankedCandidate> = | ||
| slice.map_or_else(Vec::new, <[RankedCandidate]>::to_vec); | ||
| while !group.is_empty() { |
There was a problem hiding this comment.
Done in aaf9e42 — apply_tiebreaker now drains the front tie group out of ranked (ranked.drain(..split_at).collect()) instead of cloning via to_vec(). Removes K String clones per K-sized tie group and lets us drop the start: usize walk variable + the .get(start..end) ceremony required by clippy::indexing_slicing. One nit: the "later clones again into output via pushes" framing was off — output.push(pick) is a move, not a clone. So the actual win is one set of clones avoided per tie group, not two.
…ly_tiebreaker Addresses two open review threads on PR #380: - gemini: REPUTATION_FLOOR was f32 but compute_score works in f64; declaring the floor as f64 lets us promote-then-clamp in one expression and drop the intermediate `rep_clamped`. - Copilot: apply_tiebreaker cloned each tie group via `to_vec()`, copying every RankedCandidate (including its String region). Switching to `Vec::drain` moves elements out of `ranked` instead, eliminating K String clones per K-sized tie group. Also lets us drop the `start: usize` walk variable and the `.get(start..end)` ceremony required by clippy::indexing_slicing. Side effect of the f64 floor: `0.1f32` promotes to ~0.10000000149f64, slightly above the floor, so an exact-floor input no longer aliases the clamp output. The two clamp tests now compare two sub-floor inputs (0.0 and 0.01, or -0.5 and 0.01), which both clamp identically — preserves the original "clamping happens" semantic without depending on the f32→f64 promotion artifact. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Round-2 review pass on PR #380 surfaced four polish items and four missing boundary tests. None block correctness; all are cheap quality wins. Doc nits: - tie_group_end: state the termination contract ("returns > start whenever start < ranked.len()") so the drain-the-front loop's progress invariant is local-to-read. - pick_best_in_group: state the order-independence INVARIANT that apply_tiebreaker's swap_remove relies on, and document the pool-index validity invariant (only shrinks via retain → every entry is a valid group index). - Tier 3 ADR ref: cite ADR 001's actual heading "Contract Interface: Node Registry" for greppability. New tests: - score_floor_value_is_zero_point_one — pins REPUTATION_FLOOR=0.1 by value (existing tests pin clamping behavior but not the floor value). - at_1_percent_boundary_counts_as_tied — covers the exact 1.0% boundary; tie_group_end uses `> TIE_THRESHOLD` so 1.0% is *inclusive*. Guards against a future change to `>=`. - three_way_zero_stake_falls_through_to_random_tier — two `Some(0)` plus one `None`; verifies tier 3 retains both `Some(0)` survivors and tier 4 picks fairly between them. Guards the `Some(0)` semantic from some_zero_stake_beats_none_stake against a one-winner short-circuit. - top_n_with_zero_returns_empty — locks the n=0 contract against a future truncate(n.max(1)). Drop #[non_exhaustive] from Candidate and RankedCandidate — the `node` crate doesn't expose a stable downstream API surface yet, and the markers were forward-looking insurance with no current consumer to protect. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Revert aaf9e42's REPUTATION_FLOOR f32→f64 change. The cleaner resolution to gemini's original concern is to inline the cast rather than change the constant's type: // before aaf9e42 (had intermediate var) let rep_clamped = reputation.max(REPUTATION_FLOOR); let rep = f64::from(rep_clamped); // aaf9e42 (f64 floor — promote then clamp) let rep = f64::from(reputation).max(REPUTATION_FLOOR); // now (f32 floor — clamp then promote, single line) let rep = f64::from(reputation.max(REPUTATION_FLOOR)); The aaf9e42 form had a subtle boundary surprise: f32(0.1) is not exactly representable in f32 (its true value is ~0.10000000149), and promotes to a value slightly above the f64 floor — so an exact-0.1 reputation input slipped past the clamp. That forced the two clamp-tests to compare two sub-floor inputs instead of the natural "clamped-zero == compute_score(_, _, 0.1)" assertion. Clamping in f32 (the input's domain) and promoting once at the end keeps the floor's type matching the input's, restores the natural test, and applies gemini's actual cleanup intent (one conversion, no intermediate variable). Rule of thumb: convert at the latest sensible point. Tests: - score_reputation_0_0_clamps_to_floor / score_negative_reputation_clamps_to_floor: reverted the sub-floor-vs-sub-floor workaround. - score_floor_value_is_zero_point_one: tolerance loosened from 1e-3 to 1e-2 to absorb the f32(0.1) → f64 promotion artifact (~3e-3 in score). Still catches a floor drift to 0.05 or 0.2. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Resolves two conflicts in adr/008-reputation.md: - §14 PoC Scope (main's elaborated 14a/14b): dropped per d16487d's intent. This PR ships the full 4-tier tie-breaker that §14b listed as "deferred to production", which is the cleanest evidence the PoC/production framing isn't predicting what gets implemented. - Consequences/Negative bullets: took main's version (#500's drop of the stale gauge-eligibility tier bullets that referenced now-deleted ADR 027 and ADR 007). The PoC reference bullet is dropped since §14 no longer exists. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Coverage reportTotal: 88.55% (was 88.27%, ▲ +0.28%) — 12767/14418 lines
History
|
Summary
Implements ADR 001 §Node Selection Algorithm and ADR 008 §9 four-tier tie-break as a pure ranking module at
crates/node/src/selection.rs. The output is consumed by the future cache-miss-pull caller viatop_n(candidates, MAX_PROVIDER_ATTEMPTS).rate_per_mb × rtt_ms × (1 / max(reputation, 0.1)²)— lower is better. Reputation is clamped to a 0.1 floor (caps the worst-case multiplier at 100×, prevents div-by-zero).bandwidth_utilization, thenactive_streams)Option<u64>— no-op until on-chain lookup is wired)top_n+MAX_PROVIDER_ATTEMPTS = 3is the canonical entry point for the cache-miss-pull caller (issue Implement node selection algorithm (rate × rtt × 1/reputation²) #322's "max 3 provider attempts before returning error" requirement).Implementation notes
tokio. Inputs are produced upstream by probe + gossip + reputation; this module only ranks. Keepsnode's wiring layer in charge of integration per ADR 001 "Contract Interface: Node Registry" (and ADR 019 onboarding).Option<u64>.NodeAnnouncedoes not carry stake yet and on-chain stake lookup is out of scope for Implement node selection algorithm (rate × rtt × 1/reputation²) #322 — when all candidates havestake = Nonetier 3 is a no-op and tier 4 decides.Some(0)is treated as a known-zero-stake operator and beatsNone("not yet looked up") — pinned bysome_zero_stake_beats_none_stakeandthree_way_zero_stake_falls_through_to_random_tier.f64::total_cmpfor sort. Scores are always finite, buttotal_cmpgives a total order without anunwrapand stays clear of the anti-panic policy.compute_scoredoesf64::from(reputation.max(REPUTATION_FLOOR))— clamp in the input's natural type, then promote once for the f64 score arithmetic. Convert at the latest sensible point.apply_tiebreakerdrains the front tie group out ofrankedrather than cloning viato_vec()— saves one set ofStringclones per tie group and lets us drop thestart: usizewalk +.get(start..end)ceremony required byclippy::indexing_slicing.emitted_regionsHashSetis reset between within-1% groups so a region picked in one tie group doesn't bias the geo tier of an unrelated downstream group. Regression test included.rank_candidates_with_rngis an internal variant that takes an explicit RNG so the random tier doesn't make tests flaky. The probabilistic tests assert behavioral invariants ("if first pick is US, second pick must be DE") across seed sweeps rather than pinning a single seed.unwrap/expect/ indexing in non-test code; bounds use.get()with safe defaults paired withdebug_assert!so invariant breaks surface in debug builds while release keeps the clippy-required guard.Review fixes applied
After three rounds of review (
/review-pr+ gemini + Copilot), the following landed:Round 1 (
28f3f87):debug_assert!s paired with the unreachable safe fallbacks inapply_tiebreakerandpick_best_in_group.compare_loadfield-order rationale.some_zero_stake_beats_none_staketest for theSome(0)vsNoneboundary.Round 1.5 (
aaf9e42then revisited in0b5cfc5):REPUTATION_FLOOR: f32 → f64suggestion, but it created a boundary surprise:f32(0.1)rounds up to~0.10000000149f64and skips an exact-floor clamp. Reverted to f32 floor with the cast inlined:f64::from(reputation.max(REPUTATION_FLOOR))— single conversion, no intermediate variable, natural test semantics restored.apply_tiebreakerswitched fromslice.to_vec()clone toranked.drain(..split_at).collect()move (Copilot's suggestion).Round 2 (
82be218):tie_group_endtermination contract;pick_best_in_grouporder-independence INVARIANT and pool-index validity invariant; Tier 3 ADR ref now cites ADR 001's actual heading "Contract Interface: Node Registry" for greppability.score_floor_value_is_zero_point_one(pins floor by value),at_1_percent_boundary_counts_as_tied(covers exact 1.0% boundary),three_way_zero_stake_falls_through_to_random_tier(verifies tier 4 fairness when twoSome(0)candidates compete),top_n_with_zero_returns_empty(boundary).#[non_exhaustive]fromCandidateandRankedCandidate— no current downstream consumer to protect.Deferred (out of scope for #322; tracked for the wiring PR):
tracinginstrumentation around tier decisions — module has no callers yet.proptestpermutation invariant — workspace dep already exists; bundle with the wiring PR.Stakeenum (replacingOption<u64>) — bundle with the on-chain stake lookup PR.Reputation/Regionnewtypes — defer; current invariants enforced upstream and bycompute_score's defensive clamp.Test plan
cargo fmt -- --checkcleancargo clippy --workspace --all-targets -- -D warningscleancargo nextest run -p decdn-node selection::— 31/31 passingcargo nextest run --workspacecleanCloses #322
🤖 Generated with Claude Code