Repository navigation
refactor(node): type-encode seed-leech cap units with Bytes/Percent newtypes (#894) - #911
Conversation
…ewtypes (#894) The three seed-leech cap knobs were bare u64s carrying two different units (two byte quantities, one percent), distinguished only by field name and threaded positionally through LeechCaps::new. A bytes<->percent transposition compiled, ran, and was absorbed by the governor's saturating arithmetic, silently mis-pricing the abuse caps. Introduce transparent Bytes(u64) / Percent(u64) newtypes in the config-types leaf crate (Percent owns the SHARE_RATIO_SCALE denominator and the scale_saturating math) and thread them through CacheConfig -> ResolvedCache -> LeechCaps fields and constructor. serde(transparent) keeps the TOML/JSON wire form an unchanged bare integer. Internal governor accumulators and the client.rs window math stay u64, unwrapped at the boundary (full-arithmetic variant deferred to #910). Also convert LeechCaps::new / new_unchecked from positional args to a named LeechCapsConfig struct so a pull_ahead<->max_unrecouped (bytes<->bytes) swap is now a compile error too. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces Bytes and Percent transparent newtypes to enforce type safety and prevent the accidental transposition of byte quantities and percentage ratios in configuration settings. The changes update configuration parsing, resolution, validation, and the LeechGovernor to use these new types. The review feedback highlights a potential bug in Percent::scale_saturating where premature saturation can occur during u64 multiplication before division, suggesting an intermediate u128 calculation. Additionally, the reviewer recommends keeping variables strongly-typed as Bytes and Percent during configuration resolution to maintain compile-time safety against transposition.
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.
| #[must_use] | ||
| pub const fn scale_saturating(self, bytes: u64) -> u64 { | ||
| bytes.saturating_mul(self.0) / SHARE_RATIO_SCALE | ||
| } |
There was a problem hiding this comment.
Performing saturating multiplication on u64 before division can cause premature saturation and lead to highly incorrect results when bytes * percent overflows u64::MAX. For example, if percent is 200 (2.0x) and bytes is u64::MAX / 2 + 1, the multiplication saturates to u64::MAX, and the subsequent division by 100 yields a result that is ~100x smaller than the input, rather than the expected saturated value of u64::MAX.
Using u128 for the intermediate calculation prevents this premature saturation. Additionally, to adhere to the repository's 'no-as-cast' policy, avoid using as casts for integer conversions. Instead, use safe conversions like u128::from and try_from with unwrap_or.
#[must_use]
pub fn scale_saturating(self, bytes: u64) -> u64 {
let res = (u128::from(bytes) * u128::from(self.0)) / u128::from(SHARE_RATIO_SCALE);
u64::try_from(res).unwrap_or(u64::MAX)
}References
- To adhere to a 'no-as-cast' policy, avoid using
ascasts for integer conversions even when they are widening (e.g.,usizetou64). Instead, use safe conversions liketry_fromwithunwrap_orto maintain uniformity with narrowing conversions.
There was a problem hiding this comment.
Fixed in f4ceec4. scale_saturating now computes bytes * percent in u128 and clamps with u64::try_from(..).unwrap_or(u64::MAX) (the established repo idiom — incentive/channel.rs:344, node/metrics.rs:2466), so an overflowing product saturates correctly instead of dividing a pre-clamped u64::MAX. No as casts; dropped const since try_from isn't const-stable and nothing calls it in a const context.
Coverage reportTotal: 85.70% (was 85.68%, ▲ +0.01%) — 37153/43354 lines
History
|
…ting + typed resolve_cache - Percent::scale_saturating: compute bytes*percent in u128 before dividing, then clamp via u64::try_from(..).unwrap_or(u64::MAX). The prior u64 saturating_mul capped the product at u64::MAX *before* the /100, returning ~100x too small instead of a true saturated value when the product overflowed u64. Drop the now-impossible const (try_from isn't const-stable); nothing calls it in a const context. Add a mid-range overflow regression test. - resolve_cache: keep the seed-leech knobs typed as Bytes/Percent through the cross-field check (via .get() inline) and ResolvedCache construction (field shorthand) instead of unwrapping to u64 and re-wrapping, closing the in-resolver transposition surface. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces the Bytes and Percent transparent newtypes to prevent silent transposition of byte quantities and percentages in configuration values. It also refactors LeechCaps initialization to use a new LeechCapsConfig struct rather than positional arguments, preventing parameter transposition. The reviewer suggested deriving PartialEq and Eq on LeechCapsConfig to support easier configuration comparison and consistency with the inner types.
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.
Consistent with its Bytes/Percent fields (both derive them) and the sibling WindowExceedsBudget in the same file; enables config comparison in tests and future reload-validation. Zero-cost. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…w_unchecked (#911 review) Multi-agent review of #911 found no defects; these are the two in-branch hardening items it surfaced: - Add a round-trip test parsing a real [cache] TOML block into FileConfig and asserting the bare integers land in the Bytes/Percent newtypes. The newtypes' #[serde(transparent)] wire-compat promise was only tested on the bare type, never through CacheConfig — a future rename/derive slip would compile and pass yet break every operator's existing config line. - Mark LeechCaps::new_unchecked #[doc(hidden)]. It is pub only because the node/tests integration crate needs it; doc-hiding keeps it off the public API surface. No debug_assert added — the fn exists to build deliberately out-of-range pairings, which such an assert would reject. Remaining polish nits tracked in #914. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces Bytes and Percent newtypes to wrap u64 configuration values, preventing silent transposition of different units at compile time. It updates configuration resolution, validation, and the LeechGovernor to use these typed values. Feedback on the changes suggests optimizing the scale_saturating method in Percent by using checked_mul to bypass expensive u128 division when the product fits within a u64.
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.
| pub fn scale_saturating(self, bytes: u64) -> u64 { | ||
| let scaled = u128::from(bytes) * u128::from(self.0) / u128::from(SHARE_RATIO_SCALE); | ||
| u64::try_from(scaled).unwrap_or(u64::MAX) | ||
| } |
There was a problem hiding this comment.
On 64-bit platforms, u128 division is typically implemented via software routines (e.g., __udivti3), which can be significantly slower than u64 division. Since SHARE_RATIO_SCALE is a constant (100), if we can perform the division in u64, the compiler can optimize it into a highly efficient multiplication and bit-shift sequence (taking only 1-2 CPU cycles).
By checking if bytes * self.0 fits in u64 using checked_mul, we can bypass the expensive u128 division path for almost all practical inputs (where the product does not overflow u64), while still safely falling back to the robust u128 saturating logic when an overflow actually occurs. Additionally, this avoids using as casts for the narrowing conversion, adhering to the repository's no-as-cast policy by using try_from with unwrap_or.
pub fn scale_saturating(self, bytes: u64) -> u64 {
if let Some(product) = bytes.checked_mul(self.0) {
product / SHARE_RATIO_SCALE
} else {
let scaled = u128::from(bytes) * u128::from(self.0) / u128::from(SHARE_RATIO_SCALE);
u64::try_from(scaled).unwrap_or(u64::MAX)
}
}References
- To adhere to a 'no-as-cast' policy, avoid using
ascasts for integer conversions even when they are widening. Instead, use safe conversions liketry_fromwithunwrap_orto maintain uniformity with narrowing conversions.
There was a problem hiding this comment.
Declining this one. The premise is right — u128 division is software-emulated (__udivti3) and slower than a u64 divide-by-constant — but scale_saturating has a single call site, poll_admission (leech_governor.rs:251), which runs once per chunk on the cache-miss pull-through path with its whole body under the governor Mutex. The lock acquire/release and the per-chunk QUIC transfer the decision gates dominate one __udivti3 by orders of magnitude, so the u64 fast path saves tens of cycles on a network-bound path — unmeasurable here. Against that, it splits a two-line, obviously-correct body into two paths to test, and the u128-before-divide ordering is exactly what the existing comment + saturation regression test guard. Keeping the current form for clarity; will revisit if scale_saturating ever lands on a hot, lock-free loop.
…) (#923) * refactor(node): thread Bytes through leech-governor + window math (#910) Pushes the `Bytes` newtype (#894/#911) past the config boundary into the hot-path byte arithmetic so the unrecouped-leech accounting is type-checked end-to-end, not just at the edge: - leech_governor: `LeechState.{global_pulled,global_served}` and `PeerLeech.{pulled,served}` become `Bytes`; `poll_admission` budget/allowance math and the `record_pulled`/`record_served` accumulators follow. Public method params stay `u64` (wrapped internally) so region accounting and the admin-RPC wire DTOs are untouched. - client.rs window-paced serve loop: `pull_ahead_bytes`, the `window`, and the `pulled`/`served_paid` frontier become `Bytes`; the voucher-interval locals (`unvouchered`/`pending`/`delta`) stay `u64` (voucher domain). - config-types: add `Bytes::saturating_add`/`saturating_sub` (typed both sides). Also folds in #914 items 2 & 3 (a clean #910 requires exactly these): - `Percent::scale_saturating` now takes/returns `Bytes` instead of `u64`. - `WindowExceedsBudget` payload fields are `Bytes`. Closes #910. Resolves #914 items 2 & 3. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * refactor(node): apply review polish — Bytes::is_zero + boundary docs Addresses the multi-agent review of #923 (no critical/important findings; these are the suggested polish items): - Add `Bytes::is_zero()` (const) and use it for the "0 disables the cap" sentinel checks in `LeechCaps::new` and `poll_admission`, keeping the budget logic in the type's vocabulary instead of `.get() > 0`. The adjacent `initial > max` compare stays `.get()`-based — derived `Ord` is not const-callable and `LeechCaps::new` is a `const fn`. - Document why `record_pulled`/`record_served` take `u64` (network-boundary `chunk.len()` cast, wrapped to `Bytes` internally) so the asymmetry vs the `Bytes`-typed `attach_window_pull_through` reads as intentional. - Annotate the deliberately-`u64` voucher-domain locals (`unvouchered`, `pending`) in the window loop, mirroring the `total` Bytes annotation. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Closes #894.
Problem
The three seed-leech cap knobs were bare
u64s carrying two different units (two byte quantities, one percent), distinguished only by field name and threaded positionally throughLeechCaps::new. A bytes↔percent transposition compiled, ran, and did not panic — the governor's saturating arithmetic absorbed it, silently mis-pricing the abuse caps.Change
Bytes(u64)/Percent(u64)newtypes in theconfig-typesleaf crate (matching the existingHash/OriginUrl/RetryPolicyinstinct).Percentowns theSHARE_RATIO_SCALEdenominator and thescale_saturatingmath, centralizing the/100that was inlined in the governor.CacheConfig→ResolvedCache→LeechCapsfields and constructor — kept typed end-to-end throughresolve_cache(cross-field check + struct construction), so a transposition inside the resolver is a compile error too.#[serde(transparent)]keeps the TOML/JSON wire form an unchanged bare integer (non-breaking).client.rswindow math stayu64, unwrapped at the edge. The full-arithmetic variant is deferred to node: thread Bytes through leech-governor accumulators + client.rs window math (full-arithmetic newtype, follow-up to #894) #910.LeechCaps::new/new_uncheckedfrom positional args to a namedLeechCapsConfigstruct, so apull_ahead↔max_unrecouped(bytes↔bytes) swap is now a compile error too.A unit transposition — bytes↔percent or bytes↔bytes — is now caught at compile time end-to-end.
Review fixes (Gemini Code Assist + multi-agent review)
Percent::scale_saturatingoverflow (high,f4ceec4): computebytes * percentinu128before the/100, then clamp viau64::try_from(..).unwrap_or(u64::MAX)(the established repo idiom). The prioru64saturating_mulcapped the product before dividing, returning ~100× too small instead of a true saturated value on overflow. Added a mid-range overflow regression test. (A later suggestion to add au64fast path was declined —scale_saturating's sole call site is per-chunk under the governorMutex, where the lock and QUIC transfer dominate au128divide; not worth the extra branch.)resolve_cache(f4ceec4): keep the seed-leech knobs asBytes/Percentthrough the cross-field check (.get()inline) andResolvedCacheconstruction (field shorthand) instead of unwrapping tou64and re-wrapping.PartialEq, EqonLeechCapsConfig(4239773): consistent with itsBytes/Percentfields and the siblingWindowExceedsBudget; enables config comparison in tests.#[doc(hidden)](2dd9751): added a test parsing a real[cache]block intoFileConfigand asserting the bare integers land in theBytes/Percentfields — guards the#[serde(transparent)]non-breaking-wire-form promise, which was previously only tested on the bare newtype. MarkedLeechCaps::new_unchecked#[doc(hidden)](it ispubonly because thenode/testsintegration crate needs it).Test plan
cargo fmt --checkclean;cargo clippy --workspace --all-targets0 warnings.cargo nextest run:decdn-config-types(serde round-trip +scale_saturatingsaturation/regression table),decdn-common config(TOML round-trip),decdn-node leech_governor,node_origin_pull,sighup_signal,decdn-cli config_validateall pass (996/996 acrossdecdn-common+decdn-node).Follow-up
Bytesnewtype through governor accumulators +client.rswindow math.scale_saturating/WindowExceedsBudget, doc-link + cross-crate doc nits).🤖 Generated with Claude Code