Skip to content

fix(rate-limit): pin the From<&Resolved*> mappings and make limiter wiring type-safe - #1462

Merged
thiras merged 3 commits into
mainfrom
fix/1457-rate-limit-from-impl-transposition-tests
Jul 26, 2026
Merged

thiras merged 3 commits into
mainfrom
fix/1457-rate-limit-from-impl-transposition-tests

Conversation

@yigitdot

@yigitdot yigitdot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Closes the gap #1457 identified: the two From<&Resolved*> for RateLimitConfig impls in crates/node/src/rate_limit.rs are the single mapping point the runtime uses (runtime/mod.rs:858 and :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_transposed and probe_mapping_is_not_transposed each build a ResolvedDht / ResolvedProbe from eight pairwise-distinct sentinels — one per mapped field — and assert every one landed in its matching RateLimitConfig slot. Sentinels are named constants (S_PER_PEER_RATE = 11.0, … S_MAX_TRACKED_PER_PEER = 88) shared by both tests via one assert_sentinels_in_place helper, so the sentinel identifies the slot and the Resolved* 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/usize do not coerce in a struct literal), and the sentinels are pairwise distinct within each type group, so every compiling permutation — plus duplicate source reads like per_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:

  • Pairwise distinctness — three 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.
  • No collision with any Default value — 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_resolved on both limiters

{Dht,Probe}RateLimitConfig are aliases of the same RateLimitConfig, so ProbeRateLimiter::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 the Resolved* 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:

added dropped
RateLimitConfig E0063 ✅ E0560 ✅
Resolved{Dht,Probe} silent E0609 ✅

That quadrant is covered — but by the tests' exhaustive Resolved* fixture literals (and each type's own Default impl in common), 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:

  • 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 the unused binding — but field: _ and .., two of the three fixes rustc suggests, silence both links with no diagnostic. Now documented.
  • "on an unauthenticated path" contradicted this file's own module doc ("authenticated QUIC handlers"). The NodeId is authenticated; ADR 005 §Why three layers states the real weakness — probers are unstaked and can rotate NodeId for 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 the Self { .. } literals, which is what actually is.

Defaults duplication

RateLimitConfig::default(), ResolvedDht::default(), and DEFAULT_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 from ResolvedDht::default() exercising a configuration the resolver never emits. Added:

  • dht_default_matches_engine_default (node) — ties RateLimitConfig::default() to the DHT resolved defaults, the equivalence this module's docs assert.
  • resolve_dht_absent_yields_adr022_defaults (common) — the counterpart to resolve_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 each Default impl to what the resolver emits, which the existing probe test does not cover.

adr005_default_cfg() in the probe limiter tests now derives from ResolvedProbe::default() through the real From mapping 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_sec in the probe impl:

thread 'rate_limit::tests::probe_mapping_is_not_transposed' panicked at crates/node/src/rate_limit.rs:547:9:
assertion `left == right` failed
  left: 33.0
 right: 11.0
Summary [0.108s] 2 tests run: 1 passed, 1 failed, 865 skipped

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 separately per_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.dht to the probe limiter — which compiled silently before this PR:

error[E0308]: mismatched types
    |         ^^^^^^^^ expected `&ResolvedProbe`, found `&ResolvedDht`
error: could not compile `decdn-node` (lib) due to 1 previous error

Sentinel collision, S_PER_IP_BURST set to 22:

error[E0080]: evaluation panicked: the three u32 sentinels must stay pairwise distinct
   --> crates/node/src/rate_limit.rs:580:19

Gate output

$ cargo fmt -- --check
FMT: clean          # no output

$ cargo clippy --workspace --all-targets -- -D warnings
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 9.80s

$ RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 41.15s

$ cargo nextest run -p decdn-node -p decdn-common --no-fail-fast
     Summary [16.799s] 1282 tests run: 1282 passed, 0 skipped

Clippy is CI's exact --all-targets form, so the new test code is linted too. clippy::float_cmp joins the test module's existing #[allow(...)] list with an inline rationale — the mapped f64 slots are copied literals, never computed, so exact equality is the property being pinned. That matches the established pattern in selection.rs:402, rtt_map.rs:162, and node_top.rs:672.

Not changed: neither From impl body, and no default value anywhere. git diff still touches zero r.per_* / r.global_* / r.max_tracked_* lines. The Related follow-up (extracting a shared RateLimitTuning into config-types) remains out of scope.

Closes #1457

🤖 Generated with Claude Code

… 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]>
@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@thiras, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 11 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: a55ec7d8-47c7-4405-b3df-373be1686f89

📥 Commits

Reviewing files that changed from the base of the PR and between 19a3964 and 98d4452.

📒 Files selected for processing (5)
  • crates/common/src/config/mod.rs
  • crates/node/src/dht/rate_limit.rs
  • crates/node/src/handlers/probe_rate_limit.rs
  • crates/node/src/rate_limit.rs
  • crates/node/src/runtime/mod.rs

Note

🎁 Summarized by CodeRabbit Free

Your 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 @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Jul 25, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 81.08% (was 81.03%, ▲ +0.05%) — 52540/64800 lines

File Coverage Lines Δ
crates/common/src/config/mod.rs 97.04% 6853/7062 ▲ +0.01%
crates/node/src/dht/rate_limit.rs 98.77% 483/489 ▼ 1.23%
crates/node/src/handlers/probe_rate_limit.rs 72.97% 81/111 ▼ 5.97%
crates/node/src/rate_limit.rs 96.74% 297/307 ▲ +11.59%
crates/node/src/runtime/mod.rs 46.85% 1085/2316 ▲ +0.04%
History
Commit Total Δ vs base
815fd11 81.12% ▲ +0.05%
0735fc5 81.12% ▲ +0.05%
98d4452 (HEAD) 81.08% ▲ +0.05%

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]>
@github-actions

Copy link
Copy Markdown

Gas snapshot

No gas changes vs base.

@github-actions

Copy link
Copy Markdown

Contracts coverage

Line coverage: 89.92% (2615/2908 lines)
▲ +0.00pp vs base (89.92% → 89.92%)
Run: 30204929375

@thiras thiras changed the title test(rate-limit): pin the two From<&Resolved*> mappings against field transposition fix(rate-limit): pin the From<&Resolved*> mappings and make limiter wiring type-safe Jul 26, 2026
@thiras
thiras merged commit 519fba2 into main Jul 26, 2026
24 checks passed
@thiras
thiras deleted the fix/1457-rate-limit-from-impl-transposition-tests branch July 26, 2026 14:04
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.

rate-limit: the two From<&Resolved*> for RateLimitConfig impls are untested and transposition-blind

2 participants