Repository navigation
fix(rate-limit): pin the From<&Resolved*> mappings and make limiter wiring type-safe - #1462
Conversation
… transposition The two `From` impls in `crates/node/src/rate_limit.rs` are the single mapping point the runtime uses to build a rate limiter from resolved config, but nothing covered them. Since #1440 dropped `trusted_ips: HashSet<IpAddr>`, all eight remaining fields are `f64`/`u32`/`usize`, so every one can be swapped with a same-typed sibling and still compile. The impl bodies are also byte-identical, so a transposition in one is invisible to review-by-diff. Add one test per impl feeding eight pairwise-distinct sentinels through the conversion and pinning every landing slot, and correct the comment above the impls to split the guarantees: the compiler covers arity (the literals are exhaustive), the tests cover transposition. No change to either impl body or to any default value. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Warning Review limit reached
Next review available in: 11 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Free Run ID: 📒 Files selected for processing (5)
Note 🎁 Summarized by CodeRabbit FreeYour organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login. Comment |
Coverage reportTotal: 81.08% (was 81.03%, ▲ +0.05%) — 52540/64800 lines
History
|
Review follow-up on the #1457 tests. The comment above the `From` impls promises "Arity — the compiler", and that held for the impl literals and the `Resolved*` literals in the tests — but not for `assert_sentinels_in_place`, which read fields off `cfg` by name. A ninth field added to all three structs broke every literal (good) while the helper kept compiling and passing, asserting only the original eight. The new slot would ship mapped but unpinned: #1457's starting state, one field at a time. Destructure `RateLimitConfig` exhaustively (no `..`) so the helper joins the guard instead of opting out of it. Verified by threading a throwaway ninth field end-to-end: the helper now fails with E0027 "pattern does not mention field" until the field gets an assertion. Each assertion also carries its field name as the message. A transposition previously surfaced as a bare `left: 33.0 / right: 11.0` plus a backtrace to walk; it now reads `assertion failed: per_peer_rate_per_sec`. Re-ran the probe transposition to confirm — still red, still leaves the DHT test green. The sentinel block's `///` becomes `//`: it describes all eight constants but rustdoc attached it to `S_PER_PEER_RATE` alone. Neither impl body changes — `git diff` touches zero `r.*` lines. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ing gap Review of the #1457 transposition tests turned up one wrong claim in the comment they replaced, plus two adjacent gaps the tests do not reach. The Arity bullet said "a field added or dropped on either side fails the build here". A struct literal is exhaustive over the type it *constructs*; the `Resolved*` side is only read field-by-field, so a field added there is never mentioned by these impls and compiles clean. The guard exists, but it lives in the tests' exhaustive `Resolved*` fixture literals (and each type's `Default` impl in `common`) — so the comment was pointing a maintainer at a mechanism that would not stop them from relaxing those fixtures to `..Default::default()`, the one edit that silently reopens #1457. The helper doc claimed a ninth field "fails to compile until it is given an assertion". The destructure hard-errors (E0027) until the pattern *names* the field, and CI's `-D warnings` then rejects it as unused — but `field: _` and `..`, two of the three fixes rustc suggests, silence both links with no diagnostic. Says so now. Also corrected: "unauthenticated path" contradicted this file's own module doc (the `NodeId` is authenticated; ADR 005 §Why three layers says the weakness is that probers are unstaked and rotate `NodeId` for free), and "impl bodies" narrowed to the `Self { .. }` literals, which is what is actually byte-identical. Three gaps closed: - **Wiring.** `{Dht,Probe}RateLimitConfig` are aliases of the same struct, so `ProbeRateLimiter::new(&RateLimitConfig::from(&cfg.dht), ..)` compiled and no test failed — the #1457 hazard one level up, worth ADR 022's 20/sec in place of ADR 005's 5/sec on the probe path. Added `from_resolved` to both limiters, taking the `Resolved*` type so the wrong pairing is E0308, and switched the two runtime sites to it. - **Sentinel collisions.** Two same-type sentinels made equal would leave both transposition tests passing while disarming the guard for that pair. `const _` asserts catch it at compile time; a new test also pins that no sentinel can be mistaken for a `Default` value. - **Default duplication.** `RateLimitConfig::default()`, `ResolvedDht::default()`, and `DEFAULT_DHT_*` are three copies with nothing holding them in step, and the DHT resolver had no all-defaults test to match probe's. Added `dht_default_matches_engine_default`, `resolve_dht_absent_yields_adr022_defaults`, and `resolved_{dht,probe}_default_matches_resolver`; the probe limiter fixture now derives from the real mapping instead of hand-restating eight literals. Both new compile-time guards were proven to fire (E0308 on a swapped wiring arg, E0080 on a duplicated sentinel) and reverted. Gates: fmt clean, clippy `--workspace --all-targets -D warnings` clean, rustdoc `-D warnings` clean, 1282 tests pass across decdn-node + decdn-common. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Gas snapshotNo gas changes vs base. |
Contracts coverageLine coverage: 89.92% (2615/2908 lines) |
Closes the gap #1457 identified: the two
From<&Resolved*> for RateLimitConfigimpls incrates/node/src/rate_limit.rsare the single mapping point the runtime uses (runtime/mod.rs:858and:902), and nothing covered them.Review of the first pass then turned up a wrong claim in the comment those tests replaced, plus two adjacent gaps the tests do not reach — so this is no longer test-only. Three guards, three failure modes.
Transposition — the two tests
dht_mapping_is_not_transposedandprobe_mapping_is_not_transposedeach build aResolvedDht/ResolvedProbefrom eight pairwise-distinct sentinels — one per mapped field — and assert every one landed in its matchingRateLimitConfigslot. Sentinels are named constants (S_PER_PEER_RATE = 11.0, …S_MAX_TRACKED_PER_PEER = 88) shared by both tests via oneassert_sentinels_in_placehelper, so the sentinel identifies the slot and theResolved*type is what selects the impl under test. The helper destructures exhaustively (no..), so it joins the arity guard rather than opting out of it.Detection is complete: cross-type swaps cannot compile (
f64/u32/usizedo not coerce in a struct literal), and the sentinels are pairwise distinct within each type group, so every compiling permutation — plus duplicate source reads likeper_ip_burst: r.per_peer_burst— fails with the field name in the message.Two properties of the sentinels are now pinned rather than left to chance:
const _: () = assert!(…)blocks. A future edit making two same-type sentinels equal would otherwise leave both tests green while silently disarming the guard for that pair.Defaultvalue —sentinels_never_collide_with_defaults. That is what makes a mapping row that fell back to a default distinguishable from a correct map.Wiring —
from_resolvedon both limiters{Dht,Probe}RateLimitConfigare aliases of the sameRateLimitConfig, soProbeRateLimiter::new(&RateLimitConfig::from(&cfg.dht), …)compiled and no test failed — the #1457 hazard one level up, and the expensive direction: it puts ADR 022's per-peer 20/sec on the probe path in place of ADR 005's 5/sec.Added
ProbeRateLimiter::from_resolved/DhtRateLimiter::from_resolved, which take theResolved*type instead of the mapped config, and switched the two runtime sites to them. The wrong pairing is now a type error rather than a silent 4x loosening.Arity — the comment was wrong about who catches it
The old comment said "a field added or dropped on either side fails the build here". A struct literal is exhaustive over the type it constructs; the
Resolved*side is only read field-by-field, so a field added there is never mentioned by these impls and compiles clean. Quadrants:RateLimitConfigResolved{Dht,Probe}That quadrant is covered — but by the tests' exhaustive
Resolved*fixture literals (and each type's ownDefaultimpl incommon), not by the impls. The old wording pointed a maintainer at a mechanism that would not stop them from relaxing those fixtures to..Default::default(), which is the single edit that silently reopens #1457 for every future field. The comment now splits the credit and says so explicitly.Two other comment claims corrected:
E0027) until the pattern names the field, and CI's-D warningsthen rejects the unused binding — butfield: _and.., two of the three fixes rustc suggests, silence both links with no diagnostic. Now documented.NodeIdis authenticated; ADR 005 §Why three layers states the real weakness — probers are unstaked and can rotateNodeIdfor free. Rewritten to that, so the per-peer bucket's significance survives a reader who checks both comments. Also narrowed "impl bodies are byte-identical" to theSelf { .. }literals, which is what actually is.Defaults duplication
RateLimitConfig::default(),ResolvedDht::default(), andDEFAULT_DHT_*are three independent copies of the same eight values across two crates with no shared constant, and the DHT resolver had no all-defaults test to match probe's. Drift would leave every fixture built fromResolvedDht::default()exercising a configuration the resolver never emits. Added:dht_default_matches_engine_default(node) — tiesRateLimitConfig::default()to the DHT resolved defaults, the equivalence this module's docs assert.resolve_dht_absent_yields_adr022_defaults(common) — the counterpart toresolve_probe_absent_yields_adr005_defaults. Rates/bursts as ADR 022 literals on purpose; asserting against the same constant the resolver reads would pin nothing.max_tracked_*has no ADR literal (a DHT rate limiter: bound per-IP / per-peer keyed limiter keyspace #645 implementation cap) so those go through the constants.resolved_{dht,probe}_default_matches_resolver(common) — ties eachDefaultimpl to what the resolver emits, which the existing probe test does not cover.adr005_default_cfg()in the probe limiter tests now derives fromResolvedProbe::default()through the realFrommapping instead of hand-restating eight literals, so those behavioural tests exercise production's path and a drifted default surfaces as a burst assertion failing.Verification: every guard proven to fire
Each guard was mutated, observed failing, and reverted.
Transposition,
per_peer_rate_per_sec↔per_ip_rate_per_secin the probe impl:The probe per-peer sentinel came back holding the per-IP value — the security-relevant swap #1457 calls out. The DHT impl was exercised the same way (
max_tracked_per_ip↔max_tracked_per_peer), and separatelyper_peer_burst↔per_ip_burst; in every run the other test kept passing, so the two are independently targeted rather than one covering both.Wiring, passing
&cfg.dhtto the probe limiter — which compiled silently before this PR:Sentinel collision,
S_PER_IP_BURSTset to 22:Gate output
Clippy is CI's exact
--all-targetsform, so the new test code is linted too.clippy::float_cmpjoins the test module's existing#[allow(...)]list with an inline rationale — the mappedf64slots are copied literals, never computed, so exact equality is the property being pinned. That matches the established pattern inselection.rs:402,rtt_map.rs:162, andnode_top.rs:672.Not changed: neither
Fromimpl body, and no default value anywhere.git diffstill touches zeror.per_*/r.global_*/r.max_tracked_*lines. TheRelatedfollow-up (extracting a sharedRateLimitTuningintoconfig-types) remains out of scope.Closes #1457
🤖 Generated with Claude Code