Skip to content

refactor(node): type-encode seed-leech cap units with Bytes/Percent newtypes (#894) - #911

Merged
yigitdot merged 4 commits into
mainfrom
feat/894-bytes-percent-newtypes
Jun 15, 2026
Merged

yigitdot merged 4 commits into
mainfrom
feat/894-bytes-percent-newtypes

Conversation

@yigitdot

@yigitdot yigitdot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

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 through LeechCaps::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

  • New transparent Bytes(u64) / Percent(u64) newtypes in the config-types leaf crate (matching the existing Hash/OriginUrl/RetryPolicy instinct). Percent owns the SHARE_RATIO_SCALE denominator and the scale_saturating math, centralizing the /100 that was inlined in the governor.
  • Threaded through CacheConfig → ResolvedCache → LeechCaps fields and constructor — kept typed end-to-end through resolve_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).
  • Boundary-only depth (per scoping decision): internal governor accumulators and the client.rs window math stay u64, 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.
  • Converted 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.

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_saturating overflow (high, f4ceec4): compute bytes * percent in u128 before the /100, then clamp via u64::try_from(..).unwrap_or(u64::MAX) (the established repo idiom). The prior u64 saturating_mul capped 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 a u64 fast path was declined — scale_saturating's sole call site is per-chunk under the governor Mutex, where the lock and QUIC transfer dominate a u128 divide; not worth the extra branch.)
  • Typed resolve_cache (f4ceec4): keep the seed-leech knobs as Bytes/Percent through the cross-field check (.get() inline) and ResolvedCache construction (field shorthand) instead of unwrapping to u64 and re-wrapping.
  • PartialEq, Eq on LeechCapsConfig (4239773): consistent with its Bytes/Percent fields and the sibling WindowExceedsBudget; enables config comparison in tests.
  • TOML round-trip test + #[doc(hidden)] (2dd9751): added a test parsing a real [cache] block into FileConfig and asserting the bare integers land in the Bytes/Percent fields — guards the #[serde(transparent)] non-breaking-wire-form promise, which was previously only tested on the bare newtype. Marked LeechCaps::new_unchecked #[doc(hidden)] (it is pub only because the node/tests integration crate needs it).

Test plan

  • cargo fmt --check clean; cargo clippy --workspace --all-targets 0 warnings.
  • cargo nextest run: decdn-config-types (serde round-trip + scale_saturating saturation/regression table), decdn-common config (TOML round-trip), decdn-node leech_governor, node_origin_pull, sighup_signal, decdn-cli config_validate all pass (996/996 across decdn-common + decdn-node).

Follow-up

🤖 Generated with Claude Code

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

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +45 to +48
#[must_use]
pub const fn scale_saturating(self, bytes: u64) -> u64 {
bytes.saturating_mul(self.0) / SHARE_RATIO_SCALE
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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
  1. To adhere to a 'no-as-cast' policy, avoid using as casts for integer conversions even when they are widening (e.g., usize to u64). Instead, use safe conversions like try_from with unwrap_or to maintain uniformity with narrowing conversions.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread crates/config-types/src/percent.rs Resolved
Comment thread crates/common/src/config/mod.rs Resolved
Comment thread crates/common/src/config/mod.rs Resolved
@github-actions

github-actions Bot commented Jun 15, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 85.70% (was 85.68%, ▲ +0.01%) — 37153/43354 lines

File Coverage Lines Δ
crates/cache/src/lib.rs 100.00% 28/28 ● 0.00%
crates/common/src/config/mod.rs 96.81% 6079/6279 ▼ 0.02%
crates/common/src/config/resolved.rs 100.00% 35/35 ● 0.00%
crates/config-types/src/bytes.rs 100.00% 22/22 new
crates/config-types/src/percent.rs 91.18% 31/34 new
crates/node/src/leech_governor.rs 94.68% 178/188 ▲ +0.09%
crates/node/src/runtime/mod.rs 49.01% 887/1810 ▲ +0.09%
crates/node/src/runtime/reload.rs 95.22% 1454/1527 ▲ +0.03%
History
Commit Total Δ vs base
cd6bbf5 85.70% ▲ +0.01%
f4ceec4 85.70% ▲ +0.02%
4239773 85.70% ▲ +0.01%
2dd9751 (HEAD) 85.70% ▲ +0.01%

…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]>
@yigitdot
yigitdot requested a review from Copilot June 15, 2026 05:09

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@yigitdot

Copy link
Copy Markdown
Contributor Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread crates/node/src/leech_governor.rs Resolved
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]>
@yigitdot

Copy link
Copy Markdown
Contributor Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +51 to +54
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)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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
  1. To adhere to a 'no-as-cast' policy, avoid using as casts for integer conversions even when they are widening. Instead, use safe conversions like try_from with unwrap_or to maintain uniformity with narrowing conversions.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@yigitdot
yigitdot merged commit a20aa51 into main Jun 15, 2026
40 checks passed
@yigitdot
yigitdot deleted the feat/894-bytes-percent-newtypes branch June 15, 2026 15:16
thiras added a commit that referenced this pull request Jun 16, 2026
…) (#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]>
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.

node: type-encode the seed-leech cap units (Bytes/Percent newtypes) to close the config→LeechCaps confusion seam

2 participants